diff --git a/bower.json b/bower.json index bf22311..185639d 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "ml", - "version": "2.0.0", + "version": "2.1.0", "main": [ "dist/ml.js", "dist/ml.min.js" diff --git a/dist/ml.js b/dist/ml.js index c4d0cd0..004b24e 100644 --- a/dist/ml.js +++ b/dist/ml.js @@ -11,41 +11,41 @@ return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; - +/******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { - +/******/ /******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) +/******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; - +/******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; - +/******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - +/******/ /******/ // Flag the module as loaded /******/ module.l = true; - +/******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } - - +/******/ +/******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; - +/******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; - +/******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; - +/******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { @@ -56,7 +56,7 @@ return /******/ (function(modules) { // webpackBootstrap /******/ }); /******/ } /******/ }; - +/******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? @@ -65,15 +65,15 @@ return /******/ (function(modules) { // webpackBootstrap /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; - +/******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; - +/******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; - +/******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 169); +/******/ return __webpack_require__(__webpack_require__.s = 97); /******/ }) /************************************************************************/ /******/ ([ @@ -83,8 +83,8 @@ return /******/ (function(modules) { // webpackBootstrap "use strict"; -module.exports = __webpack_require__(3).Matrix; -module.exports.Decompositions = module.exports.DC = __webpack_require__(138); +module.exports = __webpack_require__(4).Matrix; +module.exports.Decompositions = module.exports.DC = __webpack_require__(187); /***/ }), @@ -117,22 +117,24 @@ euclidean.squared = squaredEuclidean; "use strict"; -exports.array = __webpack_require__(14); -exports.matrix = __webpack_require__(160); +exports.array = __webpack_require__(76); +exports.matrix = __webpack_require__(248); /***/ }), /* 3 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__symbol_species__ = __webpack_require__(163); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__symbol_species___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__symbol_species__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__ = __webpack_require__(23); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__util__ = __webpack_require__(15); -__webpack_require__(139); -var abstractMatrix = __webpack_require__(37); -var util = __webpack_require__(7); -class Matrix extends abstractMatrix(Array) { + +class Matrix extends __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__abstractMatrix__["a" /* default */])(Array) { constructor(nRows, nColumns) { var i; if (arguments.length === 1 && typeof nRows === 'number') { @@ -200,7 +202,7 @@ class Matrix extends abstractMatrix(Array) { * @return {Matrix} this */ removeRow(index) { - util.checkRowIndex(this, index); + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["a" /* checkRowIndex */])(this, index); if (this.rows === 1) { throw new RangeError('A matrix cannot have less than one row'); } @@ -220,8 +222,8 @@ class Matrix extends abstractMatrix(Array) { array = index; index = this.rows; } - util.checkRowIndex(this, index, true); - array = util.checkRowVector(this, array, true); + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["a" /* checkRowIndex */])(this, index, true); + array = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["b" /* checkRowVector */])(this, array, true); this.splice(index, 0, array); this.rows += 1; return this; @@ -233,7 +235,7 @@ class Matrix extends abstractMatrix(Array) { * @return {Matrix} this */ removeColumn(index) { - util.checkColumnIndex(this, index); + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["c" /* checkColumnIndex */])(this, index); if (this.columns === 1) { throw new RangeError('A matrix cannot have less than one column'); } @@ -255,8 +257,8 @@ class Matrix extends abstractMatrix(Array) { array = index; index = this.columns; } - util.checkColumnIndex(this, index, true); - array = util.checkColumnVector(this, array); + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["c" /* checkColumnIndex */])(this, index, true); + array = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["d" /* checkColumnVector */])(this, array); for (var i = 0; i < this.rows; i++) { this[i].splice(index, 0, array[i]); } @@ -264,9 +266,8 @@ class Matrix extends abstractMatrix(Array) { return this; } } +/* harmony export (immutable) */ __webpack_exports__["a"] = Matrix; -exports.Matrix = Matrix; -Matrix.abstractMatrix = abstractMatrix; /***/ }), @@ -276,15253 +277,32876 @@ Matrix.abstractMatrix = abstractMatrix; "use strict"; -class BaseRegression { - predict(x) { - var y2; - if (Array.isArray(x)) { - y2 = new Array(x.length); - for (var i = 0; i < x.length; i++) { - y2[i] = this._predict(x[i]); +__webpack_require__(188); +var abstractMatrix = __webpack_require__(62); +var util = __webpack_require__(16); + +class Matrix extends abstractMatrix(Array) { + constructor(nRows, nColumns) { + var i; + if (arguments.length === 1 && typeof nRows === 'number') { + return new Array(nRows); + } + if (Matrix.isMatrix(nRows)) { + return nRows.clone(); + } else if (Number.isInteger(nRows) && nRows > 0) { // Create an empty matrix + super(nRows); + if (Number.isInteger(nColumns) && nColumns > 0) { + for (i = 0; i < nRows; i++) { + this[i] = new Array(nColumns); + } + } else { + throw new TypeError('nColumns must be a positive integer'); + } + } else if (Array.isArray(nRows)) { // Copy the values from the 2D array + const matrix = nRows; + nRows = matrix.length; + nColumns = matrix[0].length; + if (typeof nColumns !== 'number' || nColumns === 0) { + throw new TypeError('Data must be a 2D array with at least one element'); + } + super(nRows); + for (i = 0; i < nRows; i++) { + if (matrix[i].length !== nColumns) { + throw new RangeError('Inconsistent array dimensions'); + } + this[i] = [].concat(matrix[i]); } - } else if (Number.isFinite(x)) { - y2 = this._predict(x); } else { - throw new TypeError('x must be a number or array'); + throw new TypeError('First argument must be a positive number or an array'); } - return y2; + this.rows = nRows; + this.columns = nColumns; + return this; } - _predict() { - throw new Error('_compute not implemented'); + set(rowIndex, columnIndex, value) { + this[rowIndex][columnIndex] = value; + return this; } - train() { - //Do nothing for this package + get(rowIndex, columnIndex) { + return this[rowIndex][columnIndex]; } - toString() { - return ''; + /** + * Creates an exact and independent copy of the matrix + * @return {Matrix} + */ + clone() { + var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns); + for (var row = 0; row < this.rows; row++) { + for (var column = 0; column < this.columns; column++) { + newMatrix.set(row, column, this.get(row, column)); + } + } + return newMatrix; } - toLaTeX() { - return ''; + /** + * Removes a row from the given index + * @param {number} index - Row index + * @return {Matrix} this + */ + removeRow(index) { + util.checkRowIndex(this, index); + if (this.rows === 1) { + throw new RangeError('A matrix cannot have less than one row'); + } + this.splice(index, 1); + this.rows -= 1; + return this; } /** - * Return the correlation coefficient of determination (r) and chi-square. - * @param {Array} x - * @param {Array} y - * @return {object} + * Adds a row at the given index + * @param {number} [index = this.rows] - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this */ - modelQuality(x, y) { - let n = x.length; - var y2 = new Array(n); - for (let i = 0; i < n; i++) { - y2[i] = this._predict(x[i]); + addRow(index, array) { + if (array === undefined) { + array = index; + index = this.rows; } - var xSum = 0; - var ySum = 0; - var chi2 = 0; - var rmsd = 0; - var xSquared = 0; - var ySquared = 0; - var xY = 0; + util.checkRowIndex(this, index, true); + array = util.checkRowVector(this, array, true); + this.splice(index, 0, array); + this.rows += 1; + return this; + } - 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 (y[i] !== 0) { - chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i]; - } - rmsd = (y[i] - y2[i]) * (y[i] - y2[i]); + /** + * Removes a column from the given index + * @param {number} index - Column index + * @return {Matrix} this + */ + removeColumn(index) { + util.checkColumnIndex(this, index); + if (this.columns === 1) { + throw new RangeError('A matrix cannot have less than one column'); } - - var r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum)); - - return { - r: r, - r2: r * r, - chi2: chi2, - rmsd: rmsd * rmsd / n - }; + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 1); + } + this.columns -= 1; + return this; } + /** + * Adds a column at the given index + * @param {number} [index = this.columns] - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + addColumn(index, array) { + if (typeof array === 'undefined') { + array = index; + index = this.columns; + } + util.checkColumnIndex(this, index, true); + array = util.checkColumnVector(this, array); + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 0, array[i]); + } + this.columns += 1; + return this; + } } -module.exports = BaseRegression; +exports.Matrix = Matrix; +Matrix.abstractMatrix = abstractMatrix; /***/ }), /* 5 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__symbol_species__ = __webpack_require__(207); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__symbol_species___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__symbol_species__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__ = __webpack_require__(28); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__util__ = __webpack_require__(17); -var abstractMatrix = __webpack_require__(37); -var Matrix = __webpack_require__(3); -class BaseView extends abstractMatrix() { - constructor(matrix, rows, columns) { - super(); - this.matrix = matrix; - this.rows = rows; - this.columns = columns; - } - static get [Symbol.species]() { - return Matrix.Matrix; +class Matrix extends __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__abstractMatrix__["a" /* default */])(Array) { + constructor(nRows, nColumns) { + var i; + if (arguments.length === 1 && typeof nRows === 'number') { + return new Array(nRows); + } + if (Matrix.isMatrix(nRows)) { + return nRows.clone(); + } else if (Number.isInteger(nRows) && nRows > 0) { // Create an empty matrix + super(nRows); + if (Number.isInteger(nColumns) && nColumns > 0) { + for (i = 0; i < nRows; i++) { + this[i] = new Array(nColumns); + } + } else { + throw new TypeError('nColumns must be a positive integer'); + } + } else if (Array.isArray(nRows)) { // Copy the values from the 2D array + const matrix = nRows; + nRows = matrix.length; + nColumns = matrix[0].length; + if (typeof nColumns !== 'number' || nColumns === 0) { + throw new TypeError('Data must be a 2D array with at least one element'); + } + super(nRows); + for (i = 0; i < nRows; i++) { + if (matrix[i].length !== nColumns) { + throw new RangeError('Inconsistent array dimensions'); + } + this[i] = [].concat(matrix[i]); + } + } else { + throw new TypeError('First argument must be a positive number or an array'); + } + this.rows = nRows; + this.columns = nColumns; + return this; } -} - -module.exports = BaseView; + set(rowIndex, columnIndex, value) { + this[rowIndex][columnIndex] = value; + return this; + } -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { + get(rowIndex, columnIndex) { + return this[rowIndex][columnIndex]; + } -"use strict"; - - -exports.maybeToPrecision = function maybeToPrecision(value, digits) { - if (value < 0) { - value = -1 * value; - if (digits) { - return '- ' + value.toPrecision(digits); - } else { - return '- ' + value.toString(); - } - } else { - if (digits) { - return value.toPrecision(digits); - } else { - return value.toString(); + /** + * Creates an exact and independent copy of the matrix + * @return {Matrix} + */ + clone() { + var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns); + for (var row = 0; row < this.rows; row++) { + for (var column = 0; column < this.columns; column++) { + newMatrix.set(row, column, this.get(row, column)); + } } + return newMatrix; } -}; - - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; - - -var Matrix = __webpack_require__(3); - -/** - * @private - * Check that a row index is not out of bounds - * @param {Matrix} matrix - * @param {number} index - * @param {boolean} [outer] - */ -exports.checkRowIndex = function checkRowIndex(matrix, index, outer) { - var max = outer ? matrix.rows : matrix.rows - 1; - if (index < 0 || index > max) { - throw new RangeError('Row index out of range'); + /** + * Removes a row from the given index + * @param {number} index - Row index + * @return {Matrix} this + */ + removeRow(index) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["a" /* checkRowIndex */])(this, index); + if (this.rows === 1) { + throw new RangeError('A matrix cannot have less than one row'); + } + this.splice(index, 1); + this.rows -= 1; + return this; } -}; -/** - * @private - * Check that a column index is not out of bounds - * @param {Matrix} matrix - * @param {number} index - * @param {boolean} [outer] - */ -exports.checkColumnIndex = function checkColumnIndex(matrix, index, outer) { - var max = outer ? matrix.columns : matrix.columns - 1; - if (index < 0 || index > max) { - throw new RangeError('Column index out of range'); + /** + * Adds a row at the given index + * @param {number} [index = this.rows] - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + addRow(index, array) { + if (array === undefined) { + array = index; + index = this.rows; + } + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["a" /* checkRowIndex */])(this, index, true); + array = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["b" /* checkRowVector */])(this, array, true); + this.splice(index, 0, array); + this.rows += 1; + return this; } -}; -/** - * @private - * Check that the provided vector is an array with the right length - * @param {Matrix} matrix - * @param {Array|Matrix} vector - * @return {Array} - * @throws {RangeError} - */ -exports.checkRowVector = 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'); + /** + * Removes a column from the given index + * @param {number} index - Column index + * @return {Matrix} this + */ + removeColumn(index) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["c" /* checkColumnIndex */])(this, index); + if (this.columns === 1) { + throw new RangeError('A matrix cannot have less than one column'); + } + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 1); + } + this.columns -= 1; + return this; } - 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} - */ -exports.checkColumnVector = function checkColumnVector(matrix, vector) { - if (vector.to1DArray) { - vector = vector.to1DArray(); - } - if (vector.length !== matrix.rows) { - throw new RangeError('vector size must be the same as the number of rows'); + /** + * Adds a column at the given index + * @param {number} [index = this.columns] - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + addColumn(index, array) { + if (typeof array === 'undefined') { + array = index; + index = this.columns; + } + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["c" /* checkColumnIndex */])(this, index, true); + array = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["d" /* checkColumnVector */])(this, array); + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 0, array[i]); + } + this.columns += 1; + return this; } - return vector; -}; +} +/* harmony export (immutable) */ __webpack_exports__["a"] = Matrix; -exports.checkIndices = function checkIndices(matrix, rowIndices, columnIndices) { - var rowOut = rowIndices.some(r => { - return r < 0 || r >= matrix.rows; - }); - var columnOut = columnIndices.some(c => { - return c < 0 || c >= matrix.columns; - }); +/***/ }), +/* 6 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - if (rowOut || columnOut) { - throw new RangeError('Indices are out of range'); - } +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__symbol_species__ = __webpack_require__(220); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__symbol_species___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__symbol_species__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__ = __webpack_require__(31); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__util__ = __webpack_require__(18); - if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') { - throw new TypeError('Unexpected type for row/column indices'); - } - if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); - if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices); - return { - row: rowIndices, - column: columnIndices - }; -}; -exports.checkRange = function checkRange(matrix, startRow, endRow, startColumn, endColumn) { - if (arguments.length !== 5) throw new TypeError('Invalid argument type'); - var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) { - return typeof arg !== 'number'; - }); - if (notAllNumbers) throw new TypeError('Invalid argument type'); - 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'); + +class Matrix extends __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__abstractMatrix__["a" /* default */])(Array) { + constructor(nRows, nColumns) { + var i; + if (arguments.length === 1 && typeof nRows === 'number') { + return new Array(nRows); + } + if (Matrix.isMatrix(nRows)) { + return nRows.clone(); + } else if (Number.isInteger(nRows) && nRows > 0) { // Create an empty matrix + super(nRows); + if (Number.isInteger(nColumns) && nColumns > 0) { + for (i = 0; i < nRows; i++) { + this[i] = new Array(nColumns); + } + } else { + throw new TypeError('nColumns must be a positive integer'); + } + } else if (Array.isArray(nRows)) { // Copy the values from the 2D array + const matrix = nRows; + nRows = matrix.length; + nColumns = matrix[0].length; + if (typeof nColumns !== 'number' || nColumns === 0) { + throw new TypeError('Data must be a 2D array with at least one element'); + } + super(nRows); + for (i = 0; i < nRows; i++) { + if (matrix[i].length !== nColumns) { + throw new RangeError('Inconsistent array dimensions'); + } + this[i] = [].concat(matrix[i]); + } + } else { + throw new TypeError('First argument must be a positive number or an array'); + } + this.rows = nRows; + this.columns = nColumns; + return this; } -}; -exports.getRange = function getRange(from, to) { - var arr = new Array(to - from + 1); - for (var i = 0; i < arr.length; i++) { - arr[i] = from + i; + set(rowIndex, columnIndex, value) { + this[rowIndex][columnIndex] = value; + return this; } - return arr; -}; -exports.sumByRow = function sumByRow(matrix) { - var sum = Matrix.Matrix.zeros(matrix.rows, 1); - for (var i = 0; i < matrix.rows; ++i) { - for (var j = 0; j < matrix.columns; ++j) { - sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j)); - } + get(rowIndex, columnIndex) { + return this[rowIndex][columnIndex]; } - return sum; -}; -exports.sumByColumn = function sumByColumn(matrix) { - var sum = Matrix.Matrix.zeros(1, matrix.columns); - for (var i = 0; i < matrix.rows; ++i) { - for (var j = 0; j < matrix.columns; ++j) { - sum.set(0, j, sum.get(0, j) + matrix.get(i, j)); + /** + * Creates an exact and independent copy of the matrix + * @return {Matrix} + */ + clone() { + var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns); + for (var row = 0; row < this.rows; row++) { + for (var column = 0; column < this.columns; column++) { + newMatrix.set(row, column, this.get(row, column)); + } } + return newMatrix; } - return sum; -}; -exports.sumAll = function sumAll(matrix) { - var v = 0; - for (var i = 0; i < matrix.rows; i++) { - for (var j = 0; j < matrix.columns; j++) { - v += matrix.get(i, j); + /** + * Removes a row from the given index + * @param {number} index - Row index + * @return {Matrix} this + */ + removeRow(index) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["a" /* checkRowIndex */])(this, index); + if (this.rows === 1) { + throw new RangeError('A matrix cannot have less than one row'); } + this.splice(index, 1); + this.rows -= 1; + return this; } - return v; -}; + /** + * Adds a row at the given index + * @param {number} [index = this.rows] - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + addRow(index, array) { + if (array === undefined) { + array = index; + index = this.rows; + } + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["a" /* checkRowIndex */])(this, index, true); + array = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["b" /* checkRowVector */])(this, array, true); + this.splice(index, 0, array); + this.rows += 1; + return this; + } -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Removes a column from the given index + * @param {number} index - Column index + * @return {Matrix} this + */ + removeColumn(index) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["c" /* checkColumnIndex */])(this, index); + if (this.columns === 1) { + throw new RangeError('A matrix cannot have less than one column'); + } + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 1); + } + this.columns -= 1; + return this; + } -"use strict"; + /** + * Adds a column at the given index + * @param {number} [index = this.columns] - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + addColumn(index, array) { + if (typeof array === 'undefined') { + array = index; + index = this.columns; + } + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["c" /* checkColumnIndex */])(this, index, true); + array = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["d" /* checkColumnVector */])(this, array); + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 0, array[i]); + } + this.columns += 1; + return this; + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = Matrix; -const Matrix = __webpack_require__(0); -const GaussianKernel = __webpack_require__(120); -const PolynomialKernel = __webpack_require__(121); -const ANOVAKernel = __webpack_require__(123); -const CauchyKernel = __webpack_require__(124); -const ExponentialKernel = __webpack_require__(125); -const HistogramKernel = __webpack_require__(126); -const LaplacianKernel = __webpack_require__(127); -const MultiquadraticKernel = __webpack_require__(128); -const RationalKernel = __webpack_require__(129); -const SigmoidKernel = __webpack_require__(122); +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -const kernelType = { - gaussian: GaussianKernel, - rbf: GaussianKernel, - polynomial: PolynomialKernel, - poly: PolynomialKernel, - anova: ANOVAKernel, - cauchy: CauchyKernel, - exponential: ExponentialKernel, - histogram: HistogramKernel, - min: HistogramKernel, - laplacian: LaplacianKernel, - multiquadratic: MultiquadraticKernel, - rational: RationalKernel, - sigmoid: SigmoidKernel, - mlp: SigmoidKernel -}; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__symbol_species__ = __webpack_require__(233); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__symbol_species___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__symbol_species__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__ = __webpack_require__(35); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__util__ = __webpack_require__(19); -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); + +class Matrix extends __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__abstractMatrix__["a" /* default */])(Array) { + constructor(nRows, nColumns) { + var i; + if (arguments.length === 1 && typeof nRows === 'number') { + return new Array(nRows); + } + if (Matrix.isMatrix(nRows)) { + return nRows.clone(); + } else if (Number.isInteger(nRows) && nRows > 0) { // Create an empty matrix + super(nRows); + if (Number.isInteger(nColumns) && nColumns > 0) { + for (i = 0; i < nRows; i++) { + this[i] = new Array(nColumns); + } } else { - throw new Error('unsupported kernel type: ' + type); + throw new TypeError('nColumns must be a positive integer'); + } + } else if (Array.isArray(nRows)) { // Copy the values from the 2D array + const matrix = nRows; + nRows = matrix.length; + nColumns = matrix[0].length; + if (typeof nColumns !== 'number' || nColumns === 0) { + throw new TypeError('Data must be a 2D array with at least one element'); + } + super(nRows); + for (i = 0; i < nRows; i++) { + if (matrix[i].length !== nColumns) { + throw new RangeError('Inconsistent array dimensions'); + } + this[i] = [].concat(matrix[i]); } - } else 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'); + throw new TypeError('First argument must be a positive number or an array'); } + this.rows = nRows; + this.columns = nColumns; + return this; } - compute(inputs, landmarks) { - if (landmarks === undefined) { - landmarks = inputs; + set(rowIndex, columnIndex, value) { + this[rowIndex][columnIndex] = value; + return this; + } + + get(rowIndex, columnIndex) { + return this[rowIndex][columnIndex]; + } + + /** + * Creates an exact and independent copy of the matrix + * @return {Matrix} + */ + clone() { + var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns); + for (var row = 0; row < this.rows; row++) { + for (var column = 0; column < this.columns; column++) { + newMatrix.set(row, column, this.get(row, column)); + } } + return newMatrix; + } - if (this.kernelType === 'linear') { - var matrix = new Matrix(inputs); - return matrix.mmul(new Matrix(landmarks).transpose()); + /** + * Removes a row from the given index + * @param {number} index - Row index + * @return {Matrix} this + */ + removeRow(index) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["a" /* checkRowIndex */])(this, index); + if (this.rows === 1) { + throw new RangeError('A matrix cannot have less than one row'); } + this.splice(index, 1); + this.rows -= 1; + return this; + } - const kernelMatrix = new Matrix(inputs.length, landmarks.length); - var i, j; - if (inputs === landmarks) { // fast path, matrix is symmetric - for (i = 0; i < inputs.length; i++) { - for (j = i; j < inputs.length; j++) { - kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]); - } - } - } else { - for (i = 0; i < inputs.length; i++) { - for (j = 0; j < landmarks.length; j++) { - kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]); - } - } + /** + * Adds a row at the given index + * @param {number} [index = this.rows] - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + addRow(index, array) { + if (array === undefined) { + array = index; + index = this.rows; } - return kernelMatrix; + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["a" /* checkRowIndex */])(this, index, true); + array = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["b" /* checkRowVector */])(this, array, true); + this.splice(index, 0, array); + this.rows += 1; + return this; + } + + /** + * Removes a column from the given index + * @param {number} index - Column index + * @return {Matrix} this + */ + removeColumn(index) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["c" /* checkColumnIndex */])(this, index); + if (this.columns === 1) { + throw new RangeError('A matrix cannot have less than one column'); + } + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 1); + } + this.columns -= 1; + return this; + } + + /** + * Adds a column at the given index + * @param {number} [index = this.columns] - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + addColumn(index, array) { + if (typeof array === 'undefined') { + array = index; + index = this.columns; + } + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["c" /* checkColumnIndex */])(this, index, true); + array = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__util__["d" /* checkColumnVector */])(this, array); + for (var i = 0; i < this.rows; i++) { + this[i].splice(index, 0, array[i]); + } + this.columns += 1; + return this; } } +/* harmony export (immutable) */ __webpack_exports__["a"] = Matrix; -module.exports = Kernel; /***/ }), -/* 9 */ -/***/ (function(module, exports, __webpack_require__) { +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__abstractMatrix__ = __webpack_require__(23); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__matrix__ = __webpack_require__(3); -var hasOwn = Object.prototype.hasOwnProperty; -var toStr = Object.prototype.toString; -var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } +class BaseView extends __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__abstractMatrix__["a" /* default */])() { + constructor(matrix, rows, columns) { + super(); + this.matrix = matrix; + this.rows = rows; + this.columns = columns; + } - return toStr.call(arr) === '[object Array]'; -}; + static get [Symbol.species]() { + return __WEBPACK_IMPORTED_MODULE_1__matrix__["a" /* default */]; + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = BaseView; -var isPlainObject = function isPlainObject(obj) { - if (!obj || toStr.call(obj) !== '[object Object]') { - return false; - } - - var hasOwnConstructor = hasOwn.call(obj, 'constructor'); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); - // Not own constructor property must be Object - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - var key; - for (key in obj) {/**/} - - return typeof key === 'undefined' || hasOwn.call(obj, key); -}; -module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0], - i = 1, - length = arguments.length, - deep = false; - // Handle a deep copy situation - if (typeof target === 'boolean') { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) { - target = {}; - } +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { - for (; i < length; ++i) { - options = arguments[i]; - // Only deal with non-null/undefined values - if (options != null) { - // Extend the base object - for (name in options) { - src = target[name]; - copy = options[name]; +"use strict"; - // Prevent never-ending loop - if (target !== copy) { - // Recurse if we're merging plain objects or arrays - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } else { - clone = src && isPlainObject(src) ? src : {}; - } - // Never move original objects, clone them - target[name] = extend(deep, clone, copy); +var abstractMatrix = __webpack_require__(62); +var Matrix = __webpack_require__(4); - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - target[name] = copy; - } - } - } - } - } +class BaseView extends abstractMatrix() { + constructor(matrix, rows, columns) { + super(); + this.matrix = matrix; + this.rows = rows; + this.columns = columns; + } - // Return the modified object - return target; -}; + static get [Symbol.species]() { + return Matrix.Matrix; + } +} +module.exports = BaseView; /***/ }), /* 10 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__abstractMatrix__ = __webpack_require__(28); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__matrix__ = __webpack_require__(5); -const Heap = __webpack_require__(63); - -function Cluster () { - this.children = []; - this.distance = -1; - this.index = []; -} -/** - * Creates an array of values where maximum distance smaller than the threshold - * @param {number} threshold - * @return {Array } - */ -Cluster.prototype.cut = function (threshold) { - if (threshold < 0) throw new RangeError('Threshold too small'); - var root = new Cluster(); - root.children = this.children; - root.distance = this.distance; - root.index = this.index; - var list = [root]; - var ans = []; - while (list.length > 0) { - var aux = list.shift(); - if (threshold >= aux.distance) - ans.push(aux); - else - list = list.concat(aux.children); +class BaseView extends __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__abstractMatrix__["a" /* default */])() { + constructor(matrix, rows, columns) { + super(); + this.matrix = matrix; + this.rows = rows; + this.columns = columns; } - return ans; -}; - -/** - * Merge the leaves in the minimum way to have 'minGroups' number of clusters - * @param {number} minGroups - * @return {Cluster} - */ -Cluster.prototype.group = function (minGroups) { - if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer'); - const heap = new Heap(function (a, b) { - return b.distance - a.distance; - }); - - heap.push(this); - - while (heap.size() < minGroups) { - var first = heap.pop(); - if (first.children.length === 0) { - break; - } - first.children.forEach(child => heap.push(child)); + static get [Symbol.species]() { + return __WEBPACK_IMPORTED_MODULE_1__matrix__["a" /* default */]; } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = BaseView; - var root = new Cluster(); - root.children = heap.toArray(); - root.distance = this.distance; - - return root; -}; - -module.exports = Cluster; /***/ }), /* 11 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__abstractMatrix__ = __webpack_require__(31); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__matrix__ = __webpack_require__(6); -exports.hypotenuse = function hypotenuse(a, b) { - var r; - if (Math.abs(a) > Math.abs(b)) { - r = b / a; - return Math.abs(a) * Math.sqrt(1 + r * r); - } - if (b !== 0) { - r = a / b; - return Math.abs(b) * Math.sqrt(1 + r * r); - } - return 0; -}; -// For use in the decomposition algorithms. With big matrices, access time is -// too long on elements from array subclass -// todo check when it is fixed in v8 -// http://jsperf.com/access-and-write-array-subclass -exports.getEmpty2DArray = function (rows, columns) { - var array = new Array(rows); - for (var i = 0; i < rows; i++) { - array[i] = new Array(columns); +class BaseView extends __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__abstractMatrix__["a" /* default */])() { + constructor(matrix, rows, columns) { + super(); + this.matrix = matrix; + this.rows = rows; + this.columns = columns; } - return array; -}; -exports.getFilled2DArray = function (rows, columns, value) { - var array = new Array(rows); - for (var i = 0; i < rows; i++) { - array[i] = new Array(columns); - for (var j = 0; j < columns; j++) { - array[i][j] = value; - } + static get [Symbol.species]() { + return __WEBPACK_IMPORTED_MODULE_1__matrix__["a" /* default */]; } - return array; -}; +} +/* harmony export (immutable) */ __webpack_exports__["a"] = BaseView; + /***/ }), /* 12 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__abstractMatrix__ = __webpack_require__(35); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__matrix__ = __webpack_require__(7); -const Matrix = __webpack_require__(0); -const Stat = __webpack_require__(2); - -/** - * Function that given vector, returns his norm - * @param {Vector} X - * @returns {number} Norm of the vector - */ -function norm(X) { - return Math.sqrt(X.clone().apply(pow2array).sum()); -} -/** - * Function that pow 2 each element of a Matrix or a Vector, - * used in the apply method of the Matrix object - * @param i - index i. - * @param j - index j. - * @return The Matrix object modified at the index i, j. - * */ -function pow2array(i, j) { - this[i][j] = this[i][j] * this[i][j]; - return this; -} +class BaseView extends __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__abstractMatrix__["a" /* default */])() { + constructor(matrix, rows, columns) { + super(); + this.matrix = matrix; + this.rows = rows; + this.columns = columns; + } -/** - * Function that normalize the dataset and return the means and - * standard deviation of each feature. - * @param dataset - * @returns {{result: Matrix, means: (*|number), std: Matrix}} dataset normalized, means - * and standard deviations - */ -function featureNormalize(dataset) { - var means = Stat.matrix.mean(dataset); - var std = Stat.matrix.standardDeviation(dataset, means, true); - var result = Matrix.checkMatrix(dataset).subRowVector(means); - return {result: result.divRowVector(std), means: means, std: std}; + static get [Symbol.species]() { + return __WEBPACK_IMPORTED_MODULE_1__matrix__["a" /* default */]; + } } +/* harmony export (immutable) */ __webpack_exports__["a"] = BaseView; -module.exports = { - norm: norm, - pow2array: pow2array, - featureNormalize: featureNormalize -}; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - +module.exports = exports = __webpack_require__(100); -var maybeToPrecision = __webpack_require__(6).maybeToPrecision; -const BaseRegression = __webpack_require__(4); +exports.getEquallySpacedData = __webpack_require__(101).getEquallySpacedData; +exports.SNV = __webpack_require__(102).SNV; -class SimpleLinearRegression extends BaseRegression { - constructor(x, y, options) { - options = options || {}; - super(); - if (x === true) { - this.slope = y.slope; - this.intercept = y.intercept; - this.quality = y.quality || {}; - if (y.quality.r) { - this.quality.r = y.quality.r; - this.quality.r2 = y.quality.r2; - } - if (y.quality.chi2) { - this.quality.chi2 = y.quality.chi2; - } - } else { - var n = x.length; - if (n !== y.length) { - throw new RangeError('input and output array have a different length'); - } - - var xSum = 0; - var ySum = 0; +/***/ }), +/* 14 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var xSquared = 0; - var xY = 0; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__maybeToPrecision__ = __webpack_require__(201); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __WEBPACK_IMPORTED_MODULE_0__maybeToPrecision__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__checkArrayLength__ = __webpack_require__(200); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __WEBPACK_IMPORTED_MODULE_1__checkArrayLength__["a"]; }); - for (var i = 0; i < n; i++) { - xSum += x[i]; - ySum += y[i]; - xSquared += x[i] * x[i]; - xY += x[i] * y[i]; - } - var numerator = (n * xY - xSum * ySum); +class BaseRegression { + constructor() { + if (new.target === BaseRegression) { + throw new Error('BaseRegression must be subclassed'); + } + } - this.slope = numerator / (n * xSquared - xSum * xSum); - this.intercept = (1 / n) * ySum - this.slope * (1 / n) * xSum; - this.coefficients = [this.intercept, this.slope]; - if (options.computeQuality) { - this.quality = this.modelQuality(x, y); - } + predict(x) { + if (typeof x === 'number') { + return this._predict(x); + } else if (Array.isArray(x)) { + const y = new Array(x.length); + for (let i = 0; i < x.length; i++) { + y[i] = this._predict(x[i]); + } + return y; + } else { + throw new TypeError('x must be a number or array'); } + } + _predict() { + throw new Error('_predict must be implemented'); } - toJSON() { - var out = { - name: 'simpleLinearRegression', - slope: this.slope, - intercept: this.intercept - }; - if (this.quality) { - out.quality = this.quality; - } - - return out; + train() { + //Do nothing for this package } - _predict(input) { - return this.slope * input + this.intercept; + toString() { + return ''; } - computeX(input) { - return (input - this.intercept) / this.slope; + toLaTeX() { + return ''; } - toString(precision) { - var result = 'f(x) = '; - if (this.slope) { - var xFactor = maybeToPrecision(this.slope, precision); - result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x'; - if (this.intercept) { - var absIntercept = Math.abs(this.intercept); - var operator = absIntercept === this.intercept ? '+' : '-'; - result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision); - } - } else { - result += maybeToPrecision(this.intercept, precision); + /** + * Return the correlation coefficient of determination (r) and chi-square. + * @param {Array} x + * @param {Array} y + * @return {object} + */ + score(x, y) { + if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) { + throw new Error('x and y must be arrays of the same length'); } - return result; - } - toLaTeX(precision) { - return this.toString(precision); - } + const n = x.length; + const y2 = new Array(n); + for (let i = 0; i < n; i++) { + y2[i] = this._predict(x[i]); + } - static load(json) { - if (json.name !== 'simpleLinearRegression') { - throw new TypeError('not a SLR 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]; + if (y[i] !== 0) { + chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i]; + } + rmsd = (y[i] - y2[i]) * (y[i] - y2[i]); } - return new SimpleLinearRegression(true, json); + + const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum)); + + return { + r: r, + r2: r * r, + chi2: chi2, + rmsd: rmsd * rmsd / n + }; } } +/* harmony export (immutable) */ __webpack_exports__["a"] = BaseRegression; -module.exports = SimpleLinearRegression; /***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { +/* 15 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = checkRowIndex; +/* harmony export (immutable) */ __webpack_exports__["c"] = checkColumnIndex; +/* harmony export (immutable) */ __webpack_exports__["b"] = checkRowVector; +/* harmony export (immutable) */ __webpack_exports__["d"] = checkColumnVector; +/* harmony export (immutable) */ __webpack_exports__["i"] = checkIndices; +/* harmony export (immutable) */ __webpack_exports__["h"] = checkRange; +/* unused harmony export getRange */ +/* harmony export (immutable) */ __webpack_exports__["e"] = sumByRow; +/* harmony export (immutable) */ __webpack_exports__["f"] = sumByColumn; +/* harmony export (immutable) */ __webpack_exports__["g"] = sumAll; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(3); -function compareNumbers(a, b) { - return a - b; -} - /** - * Computes the sum of the given values - * @param {Array} values - * @returns {number} + * @private + * Check that a row index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] */ -exports.sum = function sum(values) { - var sum = 0; - for (var i = 0; i < values.length; i++) { - sum += values[i]; +function checkRowIndex(matrix, index, outer) { + var max = outer ? matrix.rows : matrix.rows - 1; + if (index < 0 || index > max) { + throw new RangeError('Row index out of range'); } - return sum; -}; +} /** - * Computes the maximum of the given values - * @param {Array} values - * @returns {number} + * @private + * Check that a column index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] */ -exports.max = function max(values) { - var max = values[0]; - var l = values.length; - for (var i = 1; i < l; i++) { - if (values[i] > max) max = values[i]; +function checkColumnIndex(matrix, index, outer) { + var max = outer ? matrix.columns : matrix.columns - 1; + if (index < 0 || index > max) { + throw new RangeError('Column index out of range'); } - return max; -}; +} /** - * Computes the minimum of the given values - * @param {Array} values - * @returns {number} + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} */ -exports.min = function min(values) { - var min = values[0]; - var l = values.length; - for (var i = 1; i < l; i++) { - if (values[i] < min) min = values[i]; +function checkRowVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); } - return min; -}; - -/** - * Computes the min and max of the given values - * @param {Array} values - * @returns {{min: number, max: number}} - */ -exports.minMax = function minMax(values) { - var min = values[0]; - var max = values[0]; - var l = values.length; - for (var i = 1; i < l; i++) { - if (values[i] < min) min = values[i]; - if (values[i] > max) max = values[i]; + if (vector.length !== matrix.columns) { + throw new RangeError('vector size must be the same as the number of columns'); } - return { - min: min, - max: max - }; -}; + return vector; +} /** - * Computes the arithmetic mean of the given values - * @param {Array} values - * @returns {number} + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} */ -exports.arithmeticMean = function arithmeticMean(values) { - var sum = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - sum += values[i]; +function checkColumnVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); } - return sum / l; -}; + if (vector.length !== matrix.rows) { + throw new RangeError('vector size must be the same as the number of rows'); + } + return vector; +} -/** - * {@link arithmeticMean} - */ -exports.mean = exports.arithmeticMean; +function checkIndices(matrix, rowIndices, columnIndices) { + var rowOut = rowIndices.some(r => { + return r < 0 || r >= matrix.rows; -/** - * Computes the geometric mean of the given values - * @param {Array} values - * @returns {number} - */ -exports.geometricMean = function geometricMean(values) { - var mul = 1; - var l = values.length; - for (var i = 0; i < l; i++) { - mul *= values[i]; + }); + + var columnOut = columnIndices.some(c => { + return c < 0 || c >= matrix.columns; + }); + + if (rowOut || columnOut) { + throw new RangeError('Indices are out of range'); } - return Math.pow(mul, 1 / l); -}; -/** - * Computes the mean of the log of the given values - * If the return value is exponentiated, it gives the same result as the - * geometric mean. - * @param {Array} values - * @returns {number} - */ -exports.logMean = function logMean(values) { - var lnsum = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - lnsum += Math.log(values[i]); + if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') { + throw new TypeError('Unexpected type for row/column indices'); } - return lnsum / l; -}; + if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); + if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices); -/** - * Computes the weighted grand mean for a list of means and sample sizes - * @param {Array} means - Mean values for each set of samples - * @param {Array} samples - Number of original values for each set of samples - * @returns {number} - */ -exports.grandMean = function grandMean(means, samples) { - var sum = 0; - var n = 0; - var l = means.length; - for (var i = 0; i < l; i++) { - sum += samples[i] * means[i]; - n += samples[i]; + return { + row: rowIndices, + column: columnIndices + }; +} + +function checkRange(matrix, startRow, endRow, startColumn, endColumn) { + if (arguments.length !== 5) throw new TypeError('Invalid argument type'); + var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) { + return typeof arg !== 'number'; + }); + if (notAllNumbers) throw new TypeError('Invalid argument type'); + 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'); } - return sum / n; -}; +} -/** - * Computes the truncated mean of the given values using a given percentage - * @param {Array} values - * @param {number} percent - The percentage of values to keep (range: [0,1]) - * @param {boolean} [alreadySorted=false] - * @returns {number} - */ -exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) { - if (alreadySorted === undefined) alreadySorted = false; - if (!alreadySorted) { - values = [].concat(values).sort(compareNumbers); +function getRange(from, to) { + var arr = new Array(to - from + 1); + for (var i = 0; i < arr.length; i++) { + arr[i] = from + i; } - var l = values.length; - var k = Math.floor(l * percent); - var sum = 0; - for (var i = k; i < (l - k); i++) { - sum += values[i]; + return arr; +} + +function sumByRow(matrix) { + var sum = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(matrix.rows, 1); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j)); + } } - return sum / (l - 2 * k); -}; + return sum; +} -/** - * Computes the harmonic mean of the given values - * @param {Array} values - * @returns {number} - */ -exports.harmonicMean = function harmonicMean(values) { - var sum = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - if (values[i] === 0) { - throw new RangeError('value at index ' + i + 'is zero'); +function sumByColumn(matrix) { + var sum = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(1, matrix.columns); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(0, j, sum.get(0, j) + matrix.get(i, j)); } - sum += 1 / values[i]; } - return l / sum; -}; + return sum; +} + +function sumAll(matrix) { + var v = 0; + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + v += matrix.get(i, j); + } + } + return v; +} + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Matrix = __webpack_require__(4); /** - * Computes the contraharmonic mean of the given values - * @param {Array} values - * @returns {number} + * @private + * Check that a row index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] */ -exports.contraHarmonicMean = function contraHarmonicMean(values) { - var r1 = 0; - var r2 = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - r1 += values[i] * values[i]; - r2 += values[i]; - } - if (r2 < 0) { - throw new RangeError('sum of values is negative'); +exports.checkRowIndex = function checkRowIndex(matrix, index, outer) { + var max = outer ? matrix.rows : matrix.rows - 1; + if (index < 0 || index > max) { + throw new RangeError('Row index out of range'); } - return r1 / r2; }; /** - * Computes the median of the given values - * @param {Array} values - * @param {boolean} [alreadySorted=false] - * @returns {number} + * @private + * Check that a column index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] */ -exports.median = function median(values, alreadySorted) { - if (alreadySorted === undefined) alreadySorted = false; - if (!alreadySorted) { - values = [].concat(values).sort(compareNumbers); - } - var l = values.length; - var half = Math.floor(l / 2); - if (l % 2 === 0) { - return (values[half - 1] + values[half]) * 0.5; - } else { - return values[half]; +exports.checkColumnIndex = function checkColumnIndex(matrix, index, outer) { + var max = outer ? matrix.columns : matrix.columns - 1; + if (index < 0 || index > max) { + throw new RangeError('Column index out of range'); } }; /** - * Computes the variance of the given values - * @param {Array} values - * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. - * @returns {number} + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} */ -exports.variance = function variance(values, unbiased) { - if (unbiased === undefined) unbiased = true; - var theMean = exports.mean(values); - var theVariance = 0; - var l = values.length; - - for (var i = 0; i < l; i++) { - var x = values[i] - theMean; - theVariance += x * x; +exports.checkRowVector = function checkRowVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); } - - if (unbiased) { - return theVariance / (l - 1); - } else { - return theVariance / l; + if (vector.length !== matrix.columns) { + throw new RangeError('vector size must be the same as the number of columns'); } + return vector; }; /** - * Computes the standard deviation of the given values - * @param {Array} values - * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. - * @returns {number} + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} */ -exports.standardDeviation = function standardDeviation(values, unbiased) { - return Math.sqrt(exports.variance(values, unbiased)); +exports.checkColumnVector = function checkColumnVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + if (vector.length !== matrix.rows) { + throw new RangeError('vector size must be the same as the number of rows'); + } + return vector; }; -exports.standardError = function standardError(values) { - return exports.standardDeviation(values) / Math.sqrt(values.length); -}; +exports.checkIndices = function checkIndices(matrix, rowIndices, columnIndices) { + var rowOut = rowIndices.some(r => { + return r < 0 || r >= matrix.rows; -/** - * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76- - * Calculate the standard deviation via the Median of the absolute deviation - * The formula for the standard deviation only holds for Gaussian random variables. - * @returns {{mean: number, stdev: number}} - */ -exports.robustMeanAndStdev = function robustMeanAndStdev(y) { - var mean = 0, stdev = 0; - var length = y.length, i = 0; - for (i = 0; i < length; i++) { - mean += y[i]; + }); + + var columnOut = columnIndices.some(c => { + return c < 0 || c >= matrix.columns; + }); + + if (rowOut || columnOut) { + throw new RangeError('Indices are out of range'); } - mean /= length; - var averageDeviations = new Array(length); - for (i = 0; i < length; i++) - averageDeviations[i] = Math.abs(y[i] - mean); - averageDeviations.sort(compareNumbers); - if (length % 2 === 1) { - stdev = averageDeviations[(length - 1) / 2] / 0.6745; - } else { - stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745; + + if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') { + throw new TypeError('Unexpected type for row/column indices'); } + if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); + if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices); return { - mean: mean, - stdev: stdev + row: rowIndices, + column: columnIndices }; }; -exports.quartiles = function quartiles(values, alreadySorted) { - if (typeof (alreadySorted) === 'undefined') alreadySorted = false; - if (!alreadySorted) { - values = [].concat(values).sort(compareNumbers); +exports.checkRange = function checkRange(matrix, startRow, endRow, startColumn, endColumn) { + if (arguments.length !== 5) throw new TypeError('Invalid argument type'); + var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) { + return typeof arg !== 'number'; + }); + if (notAllNumbers) throw new TypeError('Invalid argument type'); + 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'); } - - var quart = values.length / 4; - var q1 = values[Math.ceil(quart) - 1]; - var q2 = exports.median(values, true); - var q3 = values[Math.ceil(quart * 3) - 1]; - - return {q1: q1, q2: q2, q3: q3}; }; -exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) { - return Math.sqrt(exports.pooledVariance(samples, unbiased)); +exports.getRange = function getRange(from, to) { + var arr = new Array(to - from + 1); + for (var i = 0; i < arr.length; i++) { + arr[i] = from + i; + } + return arr; }; -exports.pooledVariance = function pooledVariance(samples, unbiased) { - if (typeof (unbiased) === 'undefined') unbiased = true; - var sum = 0; - var length = 0, l = samples.length; - for (var i = 0; i < l; i++) { - var values = samples[i]; - var vari = exports.variance(values); - - sum += (values.length - 1) * vari; - - if (unbiased) - length += values.length - 1; - else - length += values.length; +exports.sumByRow = function sumByRow(matrix) { + var sum = Matrix.Matrix.zeros(matrix.rows, 1); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j)); + } } - return sum / length; + return sum; }; -exports.mode = function mode(values) { - var l = values.length, - itemCount = new Array(l), - i; - for (i = 0; i < l; i++) { - itemCount[i] = 0; - } - var itemArray = new Array(l); - var count = 0; - - for (i = 0; i < l; i++) { - var index = itemArray.indexOf(values[i]); - if (index >= 0) - itemCount[index]++; - else { - itemArray[count] = values[i]; - itemCount[count] = 1; - count++; - } +exports.sumByColumn = function sumByColumn(matrix) { + var sum = Matrix.Matrix.zeros(1, matrix.columns); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(0, j, sum.get(0, j) + matrix.get(i, j)); + } } + return sum; +}; - var maxValue = 0, maxIndex = 0; - for (i = 0; i < count; i++) { - if (itemCount[i] > maxValue) { - maxValue = itemCount[i]; - maxIndex = i; +exports.sumAll = function sumAll(matrix) { + var v = 0; + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + v += matrix.get(i, j); } } - - return itemArray[maxIndex]; + return v; }; -exports.covariance = function covariance(vector1, vector2, unbiased) { - if (typeof (unbiased) === 'undefined') unbiased = true; - var mean1 = exports.mean(vector1); - var mean2 = exports.mean(vector2); - - if (vector1.length !== vector2.length) - throw 'Vectors do not have the same dimensions'; - var cov = 0, l = vector1.length; - for (var i = 0; i < l; i++) { - var x = vector1[i] - mean1; - var y = vector2[i] - mean2; - cov += x * y; - } +/***/ }), +/* 17 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - if (unbiased) - return cov / (l - 1); - else - return cov / l; -}; +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = checkRowIndex; +/* harmony export (immutable) */ __webpack_exports__["c"] = checkColumnIndex; +/* harmony export (immutable) */ __webpack_exports__["b"] = checkRowVector; +/* harmony export (immutable) */ __webpack_exports__["d"] = checkColumnVector; +/* harmony export (immutable) */ __webpack_exports__["i"] = checkIndices; +/* harmony export (immutable) */ __webpack_exports__["h"] = checkRange; +/* unused harmony export getRange */ +/* harmony export (immutable) */ __webpack_exports__["e"] = sumByRow; +/* harmony export (immutable) */ __webpack_exports__["f"] = sumByColumn; +/* harmony export (immutable) */ __webpack_exports__["g"] = sumAll; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(5); -exports.skewness = function skewness(values, unbiased) { - if (typeof (unbiased) === 'undefined') unbiased = true; - var theMean = exports.mean(values); - var s2 = 0, s3 = 0, l = values.length; - for (var i = 0; i < l; i++) { - var dev = values[i] - theMean; - s2 += dev * dev; - s3 += dev * dev * dev; +/** + * @private + * Check that a row index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ +function checkRowIndex(matrix, index, outer) { + var max = outer ? matrix.rows : matrix.rows - 1; + if (index < 0 || index > max) { + throw new RangeError('Row index out of range'); } - var m2 = s2 / l; - var m3 = s3 / l; +} - var g = m3 / (Math.pow(m2, 3 / 2.0)); - if (unbiased) { - var a = Math.sqrt(l * (l - 1)); - var b = l - 2; - return (a / b) * g; - } else { - return g; +/** + * @private + * Check that a column index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ +function checkColumnIndex(matrix, index, outer) { + var max = outer ? matrix.columns : matrix.columns - 1; + if (index < 0 || index > max) { + throw new RangeError('Column index out of range'); } -}; - -exports.kurtosis = function kurtosis(values, unbiased) { - if (typeof (unbiased) === 'undefined') unbiased = true; - var theMean = exports.mean(values); - var n = values.length, s2 = 0, s4 = 0; +} - for (var i = 0; i < n; i++) { - var dev = values[i] - theMean; - s2 += dev * dev; - s4 += dev * dev * dev * dev; +/** + * @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(); } - var m2 = s2 / n; - var m4 = s4 / n; - - if (unbiased) { - var v = s2 / (n - 1); - var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3)); - var b = s4 / (v * v); - var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3)); - - return a * b - 3 * c; - } else { - return m4 / (m2 * m2) - 3; + if (vector.length !== matrix.columns) { + throw new RangeError('vector size must be the same as the number of columns'); } -}; + return vector; +} -exports.entropy = function entropy(values, eps) { - if (typeof (eps) === 'undefined') eps = 0; - var sum = 0, l = values.length; - for (var i = 0; i < l; i++) - sum += values[i] * Math.log(values[i] + eps); - return -sum; -}; +/** + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} + */ +function checkColumnVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + if (vector.length !== matrix.rows) { + throw new RangeError('vector size must be the same as the number of rows'); + } + return vector; +} -exports.weightedMean = function weightedMean(values, weights) { - var sum = 0, l = values.length; - for (var i = 0; i < l; i++) - sum += values[i] * weights[i]; - return sum; -}; +function checkIndices(matrix, rowIndices, columnIndices) { + var rowOut = rowIndices.some(r => { + return r < 0 || r >= matrix.rows; -exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) { - return Math.sqrt(exports.weightedVariance(values, weights)); -}; + }); -exports.weightedVariance = function weightedVariance(values, weights) { - var theMean = exports.weightedMean(values, weights); - var vari = 0, l = values.length; - var a = 0, b = 0; + var columnOut = columnIndices.some(c => { + return c < 0 || c >= matrix.columns; + }); - for (var i = 0; i < l; i++) { - var z = values[i] - theMean; - var w = weights[i]; + if (rowOut || columnOut) { + throw new RangeError('Indices are out of range'); + } - vari += w * (z * z); - b += w; - a += w * w; + if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') { + throw new TypeError('Unexpected type for row/column indices'); } + if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); + if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices); - return vari * (b / (b * b - a)); -}; + return { + row: rowIndices, + column: columnIndices + }; +} -exports.center = function center(values, inPlace) { - if (typeof (inPlace) === 'undefined') inPlace = false; +function checkRange(matrix, startRow, endRow, startColumn, endColumn) { + if (arguments.length !== 5) throw new TypeError('Invalid argument type'); + var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) { + return typeof arg !== 'number'; + }); + if (notAllNumbers) throw new TypeError('Invalid argument type'); + 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'); + } +} - var result = values; - if (!inPlace) - result = [].concat(values); +function getRange(from, to) { + var arr = new Array(to - from + 1); + for (var i = 0; i < arr.length; i++) { + arr[i] = from + i; + } + return arr; +} - var theMean = exports.mean(result), l = result.length; - for (var i = 0; i < l; i++) - result[i] -= theMean; -}; +function sumByRow(matrix) { + var sum = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(matrix.rows, 1); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j)); + } + } + return sum; +} -exports.standardize = function standardize(values, standardDev, inPlace) { - if (typeof (standardDev) === 'undefined') standardDev = exports.standardDeviation(values); - if (typeof (inPlace) === 'undefined') inPlace = false; - var l = values.length; - var result = inPlace ? values : new Array(l); - for (var i = 0; i < l; i++) - result[i] = values[i] / standardDev; - return result; -}; +function sumByColumn(matrix) { + var sum = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(1, matrix.columns); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(0, j, sum.get(0, j) + matrix.get(i, j)); + } + } + return sum; +} -exports.cumulativeSum = function cumulativeSum(array) { - var l = array.length; - var result = new Array(l); - result[0] = array[0]; - for (var i = 1; i < l; i++) - result[i] = result[i - 1] + array[i]; - return result; -}; +function sumAll(matrix) { + var v = 0; + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + v += matrix.get(i, j); + } + } + return v; +} /***/ }), -/* 15 */ -/***/ (function(module, exports) { +/* 18 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -module.exports = function(haystack, needle, comparator, low, high) { - var mid, cmp; +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = checkRowIndex; +/* harmony export (immutable) */ __webpack_exports__["c"] = checkColumnIndex; +/* harmony export (immutable) */ __webpack_exports__["b"] = checkRowVector; +/* harmony export (immutable) */ __webpack_exports__["d"] = checkColumnVector; +/* harmony export (immutable) */ __webpack_exports__["i"] = checkIndices; +/* harmony export (immutable) */ __webpack_exports__["h"] = checkRange; +/* unused harmony export getRange */ +/* harmony export (immutable) */ __webpack_exports__["e"] = sumByRow; +/* harmony export (immutable) */ __webpack_exports__["f"] = sumByColumn; +/* harmony export (immutable) */ __webpack_exports__["g"] = sumAll; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(6); - if(low === undefined) - low = 0; - else { - low = low|0; - if(low < 0 || low >= haystack.length) - throw new RangeError("invalid lower bound"); - } +/** + * @private + * Check that a row index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ +function checkRowIndex(matrix, index, outer) { + var max = outer ? matrix.rows : matrix.rows - 1; + if (index < 0 || index > max) { + throw new RangeError('Row index out of range'); + } +} - if(high === undefined) - high = haystack.length - 1; +/** + * @private + * Check that a column index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ +function checkColumnIndex(matrix, index, outer) { + var max = outer ? matrix.columns : matrix.columns - 1; + if (index < 0 || index > max) { + throw new RangeError('Column index out of range'); + } +} - else { - high = high|0; - if(high < low || high >= haystack.length) - throw new RangeError("invalid upper bound"); - } +/** + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} + */ +function checkRowVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + if (vector.length !== matrix.columns) { + throw new RangeError('vector size must be the same as the number of columns'); + } + return vector; +} - while(low <= high) { - /* Note that "(low + high) >>> 1" may overflow, and results in a typecast - * to double (which gives the wrong results). */ - mid = low + (high - low >> 1); - cmp = +comparator(haystack[mid], needle, mid, haystack); +/** + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} + */ +function checkColumnVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + if (vector.length !== matrix.rows) { + throw new RangeError('vector size must be the same as the number of rows'); + } + return vector; +} - /* Too low. */ - if(cmp < 0.0) - low = mid + 1; +function checkIndices(matrix, rowIndices, columnIndices) { + var rowOut = rowIndices.some(r => { + return r < 0 || r >= matrix.rows; - /* Too high. */ - else if(cmp > 0.0) - high = mid - 1; + }); - /* Key found. */ - else - return mid; - } + var columnOut = columnIndices.some(c => { + return c < 0 || c >= matrix.columns; + }); - /* Key not found. */ - return ~low; + if (rowOut || columnOut) { + throw new RangeError('Indices are out of range'); + } + + if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') { + throw new TypeError('Unexpected type for row/column indices'); + } + if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); + if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices); + + return { + row: rowIndices, + column: columnIndices + }; } +function checkRange(matrix, startRow, endRow, startColumn, endColumn) { + if (arguments.length !== 5) throw new TypeError('Invalid argument type'); + var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) { + return typeof arg !== 'number'; + }); + if (notAllNumbers) throw new TypeError('Invalid argument type'); + 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'); + } +} -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { +function getRange(from, to) { + var arr = new Array(to - from + 1); + for (var i = 0; i < arr.length; i++) { + arr[i] = from + i; + } + return arr; +} -module.exports = exports = __webpack_require__(65); +function sumByRow(matrix) { + var sum = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(matrix.rows, 1); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j)); + } + } + return sum; +} +function sumByColumn(matrix) { + var sum = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(1, matrix.columns); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(0, j, sum.get(0, j) + matrix.get(i, j)); + } + } + return sum; +} -exports.getEquallySpacedData = __webpack_require__(66).getEquallySpacedData; -exports.SNV = __webpack_require__(67).SNV; +function sumAll(matrix) { + var v = 0; + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + v += matrix.get(i, j); + } + } + return v; +} /***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { +/* 19 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = checkRowIndex; +/* harmony export (immutable) */ __webpack_exports__["c"] = checkColumnIndex; +/* harmony export (immutable) */ __webpack_exports__["b"] = checkRowVector; +/* harmony export (immutable) */ __webpack_exports__["d"] = checkColumnVector; +/* harmony export (immutable) */ __webpack_exports__["i"] = checkIndices; +/* harmony export (immutable) */ __webpack_exports__["h"] = checkRange; +/* unused harmony export getRange */ +/* harmony export (immutable) */ __webpack_exports__["e"] = sumByRow; +/* harmony export (immutable) */ __webpack_exports__["f"] = sumByColumn; +/* harmony export (immutable) */ __webpack_exports__["g"] = sumAll; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(7); -module.exports = __webpack_require__(71); -module.exports.Matrix = __webpack_require__(0); -module.exports.Matrix.algebra = __webpack_require__(22); - +/** + * @private + * Check that a row index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ +function checkRowIndex(matrix, index, outer) { + var max = outer ? matrix.rows : matrix.rows - 1; + if (index < 0 || index > max) { + throw new RangeError('Row index out of range'); + } +} -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * @private + * Check that a column index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ +function checkColumnIndex(matrix, index, outer) { + var max = outer ? matrix.columns : matrix.columns - 1; + if (index < 0 || index > max) { + throw new RangeError('Column index out of range'); + } +} -"use strict"; +/** + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} + */ +function checkRowVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + if (vector.length !== matrix.columns) { + throw new RangeError('vector size must be the same as the number of columns'); + } + return vector; +} +/** + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} + */ +function checkColumnVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + if (vector.length !== matrix.rows) { + throw new RangeError('vector size must be the same as the number of rows'); + } + return vector; +} -exports.distance = __webpack_require__(72); -exports.similarity = __webpack_require__(108); +function checkIndices(matrix, rowIndices, columnIndices) { + var rowOut = rowIndices.some(r => { + return r < 0 || r >= matrix.rows; -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { + }); -"use strict"; + var columnOut = columnIndices.some(c => { + return c < 0 || c >= matrix.columns; + }); + if (rowOut || columnOut) { + throw new RangeError('Indices are out of range'); + } -const newArray = __webpack_require__(162); + if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') { + throw new TypeError('Unexpected type for row/column indices'); + } + if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); + if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices); -const primeFinder = __webpack_require__(117); -const nextPrime = primeFinder.nextPrime; -const largestPrime = primeFinder.largestPrime; + return { + row: rowIndices, + column: columnIndices + }; +} -const FREE = 0; -const FULL = 1; -const REMOVED = 2; +function checkRange(matrix, startRow, endRow, startColumn, endColumn) { + if (arguments.length !== 5) throw new TypeError('Invalid argument type'); + var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) { + return typeof arg !== 'number'; + }); + if (notAllNumbers) throw new TypeError('Invalid argument type'); + 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'); + } +} -const defaultInitialCapacity = 150; -const defaultMinLoadFactor = 1 / 6; -const defaultMaxLoadFactor = 2 / 3; +function getRange(from, to) { + var arr = new Array(to - from + 1); + for (var i = 0; i < arr.length; i++) { + arr[i] = from + i; + } + return arr; +} -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; +function sumByRow(matrix) { + var sum = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(matrix.rows, 1); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j)); } + } + return sum; +} - const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity; - if (initialCapacity < 0) { - throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`); +function sumByColumn(matrix) { + var sum = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(1, matrix.columns); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum.set(0, j, sum.get(0, j) + matrix.get(i, j)); } + } + return sum; +} - const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor; - const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor; - if (minLoadFactor < 0 || minLoadFactor >= 1) { - throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`); - } - if (maxLoadFactor <= 0 || maxLoadFactor >= 1) { - throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`); - } - if (minLoadFactor >= maxLoadFactor) { - throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`); +function sumAll(matrix) { + var v = 0; + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + v += matrix.get(i, j); } + } + return v; +} - let capacity = initialCapacity; - // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to - // avoid the need to rehash before this capacity is reached. - // actualCapacity * maxLoadFactor >= capacity - capacity = (capacity / maxLoadFactor) | 0; - capacity = nextPrime(capacity); - if (capacity === 0) capacity = 1; - this.table = newArray(capacity, 0); - this.values = newArray(capacity, 0); - this.state = newArray(capacity, 0); +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { - this.minLoadFactor = minLoadFactor; - if (capacity === largestPrime) { - this.maxLoadFactor = 1; - } else { - this.maxLoadFactor = maxLoadFactor; - } +"use strict"; - this.distinct = 0; - this.freeEntries = capacity; - this.lowWaterMark = 0; - this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor); - } +const Matrix = __webpack_require__(162).Matrix; - clone() { - return new HashTable(this); - } +const GaussianKernel = __webpack_require__(156); +const PolynomialKernel = __webpack_require__(157); +const ANOVAKernel = __webpack_require__(171); +const CauchyKernel = __webpack_require__(172); +const ExponentialKernel = __webpack_require__(173); +const HistogramKernel = __webpack_require__(174); +const LaplacianKernel = __webpack_require__(175); +const MultiquadraticKernel = __webpack_require__(176); +const RationalKernel = __webpack_require__(177); +const SigmoidKernel = __webpack_require__(158); - get size() { - return this.distinct; - } +const kernelType = { + gaussian: GaussianKernel, + rbf: GaussianKernel, + polynomial: PolynomialKernel, + poly: PolynomialKernel, + anova: ANOVAKernel, + cauchy: CauchyKernel, + exponential: ExponentialKernel, + histogram: HistogramKernel, + min: HistogramKernel, + laplacian: LaplacianKernel, + multiquadratic: MultiquadraticKernel, + rational: RationalKernel, + sigmoid: SigmoidKernel, + mlp: SigmoidKernel +}; - get(key) { - const i = this.indexOfKey(key); - if (i < 0) return 0; - return this.values[i]; - } +class Kernel { + constructor(type, options) { + this.kernelType = type; + if (type === 'linear') return; - set(key, value) { - let i = this.indexOfInsertion(key); - if (i < 0) { - i = -i - 1; - this.values[i] = value; - return false; - } + if (typeof type === 'string') { + type = type.toLowerCase(); - if (this.distinct > this.highWaterMark) { - const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); - this.rehash(newCapacity); - return this.set(key, value); + var KernelConstructor = kernelType[type]; + if (KernelConstructor) { + this.kernelFunction = new KernelConstructor(options); + } else { + throw new Error('unsupported kernel type: ' + type); + } + } else if (typeof type === 'object' && typeof type.compute === 'function') { + this.kernelFunction = type; + } else { + throw new TypeError('first argument must be a valid kernel type or instance'); } + } - this.table[i] = key; - this.values[i] = value; - if (this.state[i] === FREE) this.freeEntries--; - this.state[i] = FULL; - this.distinct++; + compute(inputs, landmarks) { + if (landmarks === undefined) { + landmarks = inputs; + } - if (this.freeEntries < 1) { - const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); - this.rehash(newCapacity); + if (this.kernelType === 'linear') { + var matrix = new Matrix(inputs); + return matrix.mmul(new Matrix(landmarks).transposeView()); } - return true; + const kernelMatrix = new Matrix(inputs.length, landmarks.length); + var i, j; + if (inputs === landmarks) { // fast path, matrix is symmetric + for (i = 0; i < inputs.length; i++) { + for (j = i; j < inputs.length; j++) { + kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]); + } + } + } else { + for (i = 0; i < inputs.length; i++) { + for (j = 0; j < landmarks.length; j++) { + kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]); + } + } + } + return kernelMatrix; } - - remove(key, noRehash) { - const i = this.indexOfKey(key); - if (i < 0) return false; - - this.state[i] = REMOVED; - this.distinct--; +} - if (!noRehash) this.maybeShrinkCapacity(); +module.exports = Kernel; - return true; - } - delete(key, noRehash) { - const i = this.indexOfKey(key); - if (i < 0) return false; +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { - this.state[i] = FREE; - this.distinct--; +"use strict"; - if (!noRehash) this.maybeShrinkCapacity(); - return true; - } +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; - maybeShrinkCapacity() { - if (this.distinct < this.lowWaterMark) { - const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor); - this.rehash(newCapacity); - } - } +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } - containsKey(key) { - return this.indexOfKey(key) >= 0; - } + return toStr.call(arr) === '[object Array]'; +}; - indexOfKey(key) { - const table = this.table; - const state = this.state; - const length = this.table.length; +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } - const hash = key & 0x7fffffff; - let i = hash % length; - let decrement = hash % (length - 2); - if (decrement === 0) decrement = 1; + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } - while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { - i -= decrement; - if (i < 0) i += length; - } + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } - if (state[i] === FREE) return -1; - return i; - } + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; - containsValue(value) { - return this.indexOfValue(value) >= 0; - } +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; - indexOfValue(value) { - const values = this.values; - const state = this.state; + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } - for (var i = 0; i < state.length; i++) { - if (state[i] === FULL && values[i] === value) { - return i; - } - } + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = target[name]; + copy = options[name]; - return -1; - } - - indexOfInsertion(key) { - const table = this.table; - const state = this.state; - const length = table.length; + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } + // Never move original objects, clone them + target[name] = extend(deep, clone, copy); - const hash = key & 0x7fffffff; - let i = hash % length; - let decrement = hash % (length - 2); - if (decrement === 0) decrement = 1; + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + target[name] = copy; + } + } + } + } + } - while (state[i] === FULL && table[i] !== key) { - i -= decrement; - if (i < 0) i += length; - } + // Return the modified object + return target; +}; - if (state[i] === REMOVED) { - const j = i; - while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { - i -= decrement; - if (i < 0) i += length; - } - if (state[i] === FREE) i = j; - } - if (state[i] === FULL) { - return -i - 1; - } +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { - return i; - } +"use strict"; - ensureCapacity(minCapacity) { - if (this.table.length < minCapacity) { - const newCapacity = nextPrime(minCapacity); - this.rehash(newCapacity); - } - } - rehash(newCapacity) { - const oldCapacity = this.table.length; +const Heap = __webpack_require__(98); - if (newCapacity <= this.distinct) throw new Error('Unexpected'); +function Cluster() { + this.children = []; + this.distance = -1; + this.index = []; +} - const oldTable = this.table; - const oldValues = this.values; - const oldState = this.state; +/** + * Creates an array of values where maximum distance smaller than the threshold + * @param {number} threshold + * @return {Array } + */ +Cluster.prototype.cut = function (threshold) { + if (threshold < 0) throw new RangeError('Threshold too small'); + var root = new Cluster(); + root.children = this.children; + root.distance = this.distance; + root.index = this.index; + var list = [root]; + var ans = []; + while (list.length > 0) { + var aux = list.shift(); + if (threshold >= aux.distance) { + ans.push(aux); + } else { + list = list.concat(aux.children); + } + } + return ans; +}; - const newTable = newArray(newCapacity, 0); - const newValues = newArray(newCapacity, 0); - const newState = newArray(newCapacity, 0); +/** + * Merge the leaves in the minimum way to have 'minGroups' number of clusters + * @param {number} minGroups - Them minimum number of children the first level of the tree should have + * @return {Cluster} + */ +Cluster.prototype.group = function (minGroups) { + if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer'); - this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor); - this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor); + const heap = new Heap(function (a, b) { + return b.distance - a.distance; + }); - this.table = newTable; - this.values = newValues; - this.state = newState; - this.freeEntries = newCapacity - this.distinct; + heap.push(this); - 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; - } + while (heap.size() < minGroups) { + var first = heap.pop(); + if (first.children.length === 0) { + break; } + first.children.forEach(child => heap.push(child)); } - forEachKey(callback) { - for (var i = 0; i < this.state.length; i++) { - if (this.state[i] === FULL) { - if (!callback(this.table[i])) return false; - } - } - return true; - } + var root = new Cluster(); + root.children = heap.toArray(); + root.distance = this.distance; - 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; - } + return root; +}; - 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; +/** + * Traverses the tree depth-first and provide callback to be called on each individual node + * @param {function} cb - The callback to be called on each node encounter + * @type {Cluster} + */ +Cluster.prototype.traverse = function (cb) { + function visit(root, callback) { + callback(root); + if (root.children) { + for (var i = root.children.length - 1; i >= 0; i--) { + visit(root.children[i], callback); } } - return true; } -} + visit(this, cb); +}; -module.exports = HashTable; +module.exports = Cluster; -function chooseLowWaterMark(capacity, minLoad) { - return (capacity * minLoad) | 0; -} -function chooseHighWaterMark(capacity, maxLoad) { - return Math.min(capacity - 2, (capacity * maxLoad) | 0); -} +/***/ }), +/* 23 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -function chooseGrowCapacity(size, minLoad, maxLoad) { - return nextPrime(Math.max(size + 1, (4 * size / (3 * minLoad + maxLoad)) | 0)); -} +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = AbstractMatrix; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__dc_lu__ = __webpack_require__(24); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__dc_svd__ = __webpack_require__(60); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ml_array_utils__ = __webpack_require__(13); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ml_array_utils___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(15); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__views_transpose__ = __webpack_require__(170); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__views_row__ = __webpack_require__(167); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__views_sub__ = __webpack_require__(169); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__views_selection__ = __webpack_require__(168); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__views_column__ = __webpack_require__(164); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__views_flipRow__ = __webpack_require__(166); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__views_flipColumn__ = __webpack_require__(165); -function chooseShrinkCapacity(size, minLoad, maxLoad) { - return nextPrime(Math.max(size + 1, (4 * size / (minLoad + 3 * maxLoad)) | 0)); -} -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; -var extend = __webpack_require__(9); -var defaultOptions = { - size: 1, - value: 0 -}; -/** - * Case when the entry is an array - * @param data - * @param options - * @returns {Array} - */ -function arrayCase(data, options) { - var len = data.length; - if (typeof options.size === 'number') - options.size = [options.size, options.size]; - var cond = len + options.size[0] + options.size[1]; - var output; - if (options.output) { - if (options.output.length !== cond) - throw new RangeError('Wrong output size'); - output = options.output; - } - else - output = new Array(cond); - var i; - // circular option - if (options.value === 'circular') { - for (i = 0; i < cond; i++) { - if (i < options.size[0]) - output[i] = data[((len - (options.size[0] % len)) + i) % len]; - else if (i < (options.size[0] + len)) - output[i] = data[i - options.size[0]]; - else - output[i] = data[(i - options.size[0]) % len]; +function AbstractMatrix(superCtor) { + if (superCtor === undefined) superCtor = Object; + + /** + * Real matrix + * @class Matrix + * @param {number|Array|Matrix} nRows - Number of rows of the new matrix, + * 2D array containing the data or Matrix instance to clone + * @param {number} [nColumns] - Number of columns of the new matrix + */ + class Matrix extends superCtor { + static get [Symbol.species]() { + return this; } - } - // replicate option - else if (options.value === 'replicate') { - for (i = 0; i < cond; i++) { - if (i < options.size[0]) - output[i] = data[0]; - else if (i < (options.size[0] + len)) - output[i] = data[i - options.size[0]]; - else - output[i] = data[len - 1]; + /** + * Constructs a Matrix with the chosen dimensions from a 1D array + * @param {number} newRows - Number of rows + * @param {number} newColumns - Number of columns + * @param {Array} newData - A 1D array containing data for the matrix + * @return {Matrix} - The new matrix + */ + static from1DArray(newRows, newColumns, newData) { + var length = newRows * newColumns; + if (length !== newData.length) { + throw new RangeError('Data length does not match given dimensions'); + } + var newMatrix = new this(newRows, newColumns); + for (var row = 0; row < newRows; row++) { + for (var column = 0; column < newColumns; column++) { + newMatrix.set(row, column, newData[row * newColumns + column]); + } + } + return newMatrix; } - } - // symmetric option - else if (options.value === 'symmetric') { - if ((options.size[0] > len) || (options.size[1] > len)) - throw new RangeError('expanded value should not be bigger than the data length'); - for (i = 0; i < cond; i++) { - if (i < options.size[0]) - output[i] = data[options.size[0] - 1 - i]; - else if (i < (options.size[0] + len)) - output[i] = data[i - options.size[0]]; - else - output[i] = data[2*len + options.size[0] - i - 1]; + /** + * Creates a row vector, a matrix with only one row. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static rowVector(newData) { + var vector = new this(1, newData.length); + for (var i = 0; i < newData.length; i++) { + vector.set(0, i, newData[i]); + } + return vector; } - } - // default option - else { - for (i = 0; i < cond; i++) { - if (i < options.size[0]) - output[i] = options.value; - else if (i < (options.size[0] + len)) - output[i] = data[i - options.size[0]]; - else - output[i] = options.value; + /** + * Creates a column vector, a matrix with only one column. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static columnVector(newData) { + var vector = new this(newData.length, 1); + for (var i = 0; i < newData.length; i++) { + vector.set(i, 0, newData[i]); + } + return vector; } - } - - return output; -} - -/** - * Case when the entry is a matrix - * @param data - * @param options - * @returns {Array} - */ -function matrixCase(data, options) { - var row = data.length; - var col = data[0].length; - if (options.size[0] === undefined) - options.size = [options.size, options.size, options.size, options.size]; - throw new Error('matrix not supported yet, sorry'); -} -/** - * Pads and array - * @param {Array } data - * @param {object} options - */ -function padArray (data, options) { - options = extend({}, defaultOptions, options); + /** + * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns). + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static empty(rows, columns) { + return new this(rows, columns); + } - 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'); -} + /** + * Creates a matrix with the given dimensions. Values will be set to zero. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static zeros(rows, columns) { + return this.empty(rows, columns).fill(0); + } -module.exports = padArray; + /** + * Creates a matrix with the given dimensions. Values will be set to one. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static ones(rows, columns) { + return this.empty(rows, columns).fill(1); + } + /** + * Creates a matrix with the given dimensions. Values will be randomly set. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static rand(rows, columns, rng) { + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + matrix.set(i, j, rng()); + } + } + return matrix; + } -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Creates a matrix with the given dimensions. Values will be random integers. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {number} [maxValue=1000] - Maximum value + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static randInt(rows, columns, maxValue, rng) { + if (maxValue === undefined) maxValue = 1000; + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + var value = Math.floor(rng() * maxValue); + matrix.set(i, j, value); + } + } + return matrix; + } -"use strict"; + /** + * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0. + * @param {number} rows - Number of rows + * @param {number} [columns=rows] - Number of columns + * @param {number} [value=1] - Value to fill the diagonal with + * @return {Matrix} - The new identity matrix + */ + static eye(rows, columns, value) { + if (columns === undefined) columns = rows; + if (value === undefined) value = 1; + var min = Math.min(rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, value); + } + return matrix; + } -var numberIsNan = __webpack_require__(163); + /** + * Creates a diagonal matrix based on the given array. + * @param {Array} data - Array containing the data for the diagonal + * @param {number} [rows] - Number of rows (Default: data.length) + * @param {number} [columns] - Number of columns (Default: rows) + * @return {Matrix} - The new diagonal matrix + */ + static diag(data, rows, columns) { + var l = data.length; + if (rows === undefined) rows = l; + if (columns === undefined) columns = rows; + var min = Math.min(l, rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, data[i]); + } + return matrix; + } -function assertNum(x) { - if (typeof x !== 'number' || numberIsNan(x)) { - throw new TypeError('Expected a number'); - } -} + /** + * Returns a matrix whose elements are the minimum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static min(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } -exports.asc = function (a, b) { - assertNum(a); - assertNum(b); - return a - b; -}; + /** + * Returns a matrix whose elements are the maximum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static max(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } -exports.desc = function (a, b) { - assertNum(a); - assertNum(b); - return b - a; -}; + /** + * Check that the provided value is a Matrix and tries to instantiate one if not + * @param {*} value - The value to check + * @return {Matrix} + */ + static checkMatrix(value) { + return Matrix.isMatrix(value) ? value : new this(value); + } + /** + * Returns true if the argument is a Matrix, false otherwise + * @param {*} value - The value to check + * @return {boolean} + */ + static isMatrix(value) { + return (value != null) && (value.klass === 'Matrix'); + } -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * @prop {number} size - The number of elements in the matrix. + */ + get size() { + return this.rows * this.columns; + } -"use strict"; -/** - * Created by acastillo on 8/24/15. - */ -/** - * Non in-place function definitions, compatible with mathjs code * - */ - - - -var Matrix = __webpack_require__(0); - -function matrix(A,B){ - return new Matrix(A,B); -} - -function ones(rows, cols){ - return Matrix.ones(rows,cols); -} - -function eye(rows, cols){ - return Matrix.eye(rows, cols); -} - -function zeros(rows, cols){ - return Matrix.zeros(rows, cols); -} - -function random(rows, cols){ - return Matrix.rand(rows,cols); -} - -function transpose(A){ - if(typeof A == 'number') - return A; - var result = A.clone(); - return result.transpose(); -} - -function add(A, B){ - if(typeof A == 'number'&&typeof B === 'number') - return A+B; - if(typeof A == 'number') - return this.add(B,A); - - var result = A.clone(); - return result.add(B); - -} - -function subtract(A, B){ - if(typeof A == 'number'&&typeof B === 'number') - return A-B; - if(typeof A == 'number') - return this.subtract(B,A); - var result = A.clone(); - return result.sub(B); -} - -function multiply(A, B){ - if(typeof A == 'number'&&typeof B === 'number') - return A*B; - if(typeof A == 'number') - return this.multiply(B,A); - - var result = A.clone(); - - if(typeof B === 'number') - result.mul(B); - else - result = result.mmul(B); - - if(result.rows==1&&result.columns==1) - return result[0][0]; - else - return result; - -} - -function dotMultiply(A, B){ - var result = A.clone(); - return result.mul(B); -} - -function dotDivide(A, B){ - var result = A.clone(); - return result.div(B); -} - -function diag(A){ - var diag = null; - var rows = A.rows, cols = A.columns, j, r; - //It is an array - if(typeof cols === "undefined" && (typeof A)=='object'){ - if(A[0]&&A[0].length){ - rows = A.length; - cols = A[0].length; - r = Math.min(rows,cols); - diag = Matrix.zeros(cols, cols); - for (j = 0; j < cols; j++) { - diag[j][j]=A[j][j]; + /** + * Applies a callback for each element of the matrix. The function is called in the matrix (this) context. + * @param {function} callback - Function that will be called with two parameters : i (row) and j (column) + * @return {Matrix} this + */ + apply(callback) { + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); } - } - else{ - cols = A.length; - diag = Matrix.zeros(cols, cols); - for (j = 0; j < cols; j++) { - diag[j][j]=A[j]; + var ii = this.rows; + var jj = this.columns; + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + callback.call(this, i, j); + } } + return this; } - } - if(rows == 1){ - diag = Matrix.zeros(cols, cols); - for (j = 0; j < cols; j++) { - diag[j][j]=A[0][j]; - } - } - else{ - if(rows>0 && cols > 0){ - r = Math.min(rows,cols); - diag = new Array(r); - for (j = 0; j < r; j++) { - diag[j] = A[j][j]; + /** + * Returns a new 1D array filled row by row with the matrix values + * @return {Array} + */ + to1DArray() { + var array = new Array(this.size); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + array[i * this.columns + j] = this.get(i, j); + } } + return array; } - } - return diag; -} -function min(A, B){ - if(typeof A==='number' && typeof B ==='number') - return Math.min(A,B); - var ii = A.rows, jj = A.columns; - var result = new Matrix(ii,jj); - for (var i = 0; i < ii; i++) { - for (var j = 0; j < jj; j++) { - if (A[i][j] < B[i][j]) { - result[i][j] = A[i][j]; - } - else{ - result[i][j] = B[i][j]; + /** + * Returns a 2D array containing a copy of the data + * @return {Array} + */ + to2DArray() { + var copy = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + copy[i] = new Array(this.columns); + for (var j = 0; j < this.columns; j++) { + copy[i][j] = this.get(i, j); + } } + return copy; } - } - return result; -} -function max(A, B){ - if(typeof A==='number' && typeof B ==='number') - return Math.max(A,B); - var ii = A.rows, jj = A.columns; - var result = new Matrix(ii,jj); - for (var i = 0; i < ii; i++) { - for (var j = 0; j < jj; j++) { - if (A[i][j] > B[i][j]) { - result[i][j] = A[i][j]; - } - else{ - result[i][j] = B[i][j]; - } + /** + * @return {boolean} true if the matrix has one row + */ + isRowVector() { + return this.rows === 1; } - } - return result; -} - -function sqrt(A){ - if(typeof A==='number' ) - return Math.sqrt(A); - var ii = A.rows, jj = A.columns; - var result = new Matrix(ii,jj); - for (var i = 0; i < ii; i++) { - for (var j = 0; j < jj; j++) { - result[i][j] = Math.sqrt(A[i][j]); + /** + * @return {boolean} true if the matrix has one column + */ + isColumnVector() { + return this.columns === 1; } - } - return result; -} - -function abs(A){ - if(typeof A==='number' ) - return Math.abs(A); - var ii = A.rows, jj = A.columns; - var result = new Matrix(ii,jj); - for (var i = 0; i < ii; i++) { - for (var j = 0; j < jj; j++) { - result[i][j] = Math.abs(A[i][j]); + /** + * @return {boolean} true if the matrix has one row or one column + */ + isVector() { + return (this.rows === 1) || (this.columns === 1); } - } - return result; -} -function exp(A){ - if(typeof A==='number' ) - return Math.sqrt(A); - var ii = A.rows, jj = A.columns; - var result = new Matrix(ii,jj); - for (var i = 0; i < ii; i++) { - for (var j = 0; j < jj; j++) { - result[i][j] = Math.exp(A[i][j]); + /** + * @return {boolean} true if the matrix has the same number of rows and columns + */ + isSquare() { + return this.rows === this.columns; } - } - return result; -} -function dotPow(A, b){ - if(typeof A==='number' ) - return Math.pow(A,b); - //console.log(A); - var ii = A.rows, jj = A.columns; - var result = new Matrix(ii,jj); - for (var i = 0; i < ii; i++) { - for (var j = 0; j < jj; j++) { - result[i][j] = Math.pow(A[i][j],b); - } - } + /** + * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal + */ + isSymmetric() { + if (this.isSquare()) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j <= i; j++) { + if (this.get(i, j) !== this.get(j, i)) { + return false; + } + } + } + return true; + } + return false; + } + + /** + * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1 + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @param {number} value - The new value for the element + * @return {Matrix} this + */ + set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars + throw new Error('set method is unimplemented'); + } + + /** + * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4] + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @return {number} + */ + get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars + throw new Error('get method is unimplemented'); + } + + /** + * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of + * rows of the matrix, and colRep times the number of columns of the matrix + * @param {number} rowRep - Number of times the rows should be repeated + * @param {number} colRep - Number of times the columns should be re + * @return {Matrix} + * @example + * var matrix = new Matrix([[1,2]]); + * matrix.repeat(2); // [[1,2],[1,2]] + */ + repeat(rowRep, colRep) { + rowRep = rowRep || 1; + colRep = colRep || 1; + var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep); + for (var i = 0; i < rowRep; i++) { + for (var j = 0; j < colRep; j++) { + matrix.setSubMatrix(this, this.rows * i, this.columns * j); + } + } + return matrix; + } + + /** + * Fills the matrix with a given value. All elements will be set to this value. + * @param {number} value - New value + * @return {Matrix} this + */ + fill(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, value); + } + } + return this; + } + + /** + * Negates the matrix. All elements will be multiplied by (-1) + * @return {Matrix} this + */ + neg() { + return this.mulS(-1); + } + + /** + * Returns a new array from the given row index + * @param {number} index - Row index + * @return {Array} + */ + getRow(index) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + var row = new Array(this.columns); + for (var i = 0; i < this.columns; i++) { + row[i] = this.get(index, i); + } + return row; + } + + /** + * Returns a new row vector from the given row index + * @param {number} index - Row index + * @return {Matrix} + */ + getRowVector(index) { + return this.constructor.rowVector(this.getRow(index)); + } + + /** + * Sets a row at the given index + * @param {number} index - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setRow(index, array) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + array = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, array); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, array[i]); + } + return this; + } + + /** + * Swaps two rows + * @param {number} row1 - First row index + * @param {number} row2 - Second row index + * @return {Matrix} this + */ + swapRows(row1, row2) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row1); + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row2); + for (var i = 0; i < this.columns; i++) { + var temp = this.get(row1, i); + this.set(row1, i, this.get(row2, i)); + this.set(row2, i, temp); + } + return this; + } + + /** + * Returns a new array from the given column index + * @param {number} index - Column index + * @return {Array} + */ + getColumn(index) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + var column = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + column[i] = this.get(i, index); + } + return column; + } + + /** + * Returns a new column vector from the given column index + * @param {number} index - Column index + * @return {Matrix} + */ + getColumnVector(index) { + return this.constructor.columnVector(this.getColumn(index)); + } + + /** + * Sets a column at the given index + * @param {number} index - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setColumn(index, array) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + array = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, array); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, array[i]); + } + return this; + } + + /** + * Swaps two columns + * @param {number} column1 - First column index + * @param {number} column2 - Second column index + * @return {Matrix} this + */ + swapColumns(column1, column2) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column1); + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column2); + for (var i = 0; i < this.rows; i++) { + var temp = this.get(i, column1); + this.set(i, column1, this.get(i, column2)); + this.set(i, column2, temp); + } + return this; + } + + /** + * Adds the values of a vector to each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[j]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[j]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[j]); + } + } + return this; + } + + /** + * Divides the values of each row by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[j]); + } + } + return this; + } + + /** + * Adds the values of a vector to each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[i]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[i]); + } + } + return this; + } + + /** + * Divides the values of each column by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a row with a scalar + * @param {number} index - Row index + * @param {number} value + * @return {Matrix} this + */ + mulRow(index, value) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, this.get(index, i) * value); + } + return this; + } + + /** + * Multiplies the values of a column with a scalar + * @param {number} index - Column index + * @param {number} value + * @return {Matrix} this + */ + mulColumn(index, value) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, this.get(i, index) * value); + } + return this; + } + + /** + * Returns the maximum value of the matrix + * @return {number} + */ + max() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the maximum value + * @return {Array} + */ + maxIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the minimum value of the matrix + * @return {number} + */ + min() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the minimum value + * @return {Array} + */ + minIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the maximum value of one row + * @param {number} row - Row index + * @return {number} + */ + maxRow(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + maxRowIndex(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one row + * @param {number} row - Row index + * @return {number} + */ + minRow(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + minRowIndex(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the maximum value of one column + * @param {number} column - Column index + * @return {number} + */ + maxColumn(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one column + * @param {number} column - Column index + * @return {Array} + */ + maxColumnIndex(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one column + * @param {number} column - Column index + * @return {number} + */ + minColumn(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the minimum value of one column + * @param {number} column - Column index + * @return {Array} + */ + minColumnIndex(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns an array containing the diagonal values of the matrix + * @return {Array} + */ + diag() { + var min = Math.min(this.rows, this.columns); + var diag = new Array(min); + for (var i = 0; i < min; i++) { + diag[i] = this.get(i, i); + } + return diag; + } + + /** + * Returns the sum by the argument given, if no argument given, + * it returns the sum of all elements of the matrix. + * @param {string} by - sum by 'row' or 'column'. + * @return {Matrix|number} + */ + sum(by) { + switch (by) { + case 'row': + return __WEBPACK_IMPORTED_MODULE_3__util__["e" /* sumByRow */](this); + case 'column': + return __WEBPACK_IMPORTED_MODULE_3__util__["f" /* sumByColumn */](this); + default: + return __WEBPACK_IMPORTED_MODULE_3__util__["g" /* sumAll */](this); + } + } + + /** + * Returns the mean of all elements of the matrix + * @return {number} + */ + mean() { + return this.sum() / this.size; + } + + /** + * Returns the product of all elements of the matrix + * @return {number} + */ + prod() { + var prod = 1; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + prod *= this.get(i, j); + } + } + return prod; + } + + /** + * Computes the cumulative sum of the matrix elements (in place, row by row) + * @return {Matrix} this + */ + cumulativeSum() { + var sum = 0; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + sum += this.get(i, j); + this.set(i, j, sum); + } + } + return this; + } + + /** + * Computes the dot (scalar) product between the matrix and another + * @param {Matrix} vector2 vector + * @return {number} + */ + dot(vector2) { + if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); + var vector1 = this.to1DArray(); + if (vector1.length !== vector2.length) { + throw new RangeError('vectors do not have the same size'); + } + var dot = 0; + for (var i = 0; i < vector1.length; i++) { + dot += vector1[i] * vector2[i]; + } + return dot; + } + + /** + * Returns the matrix product between this and other + * @param {Matrix} other + * @return {Matrix} + */ + mmul(other) { + other = this.constructor.checkMatrix(other); + if (this.columns !== other.rows) { + // eslint-disable-next-line no-console + console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); + } + + var m = this.rows; + var n = this.columns; + var p = other.columns; + + var result = new this.constructor[Symbol.species](m, p); + + var Bcolj = new Array(n); + for (var j = 0; j < p; j++) { + for (var k = 0; k < n; k++) { + Bcolj[k] = other.get(k, j); + } + + for (var i = 0; i < m; i++) { + var s = 0; + for (k = 0; k < n; k++) { + s += this.get(i, k) * Bcolj[k]; + } + + result.set(i, j, s); + } + } + return result; + } + + strassen2x2(other) { + var result = new this.constructor[Symbol.species](2, 2); + const a11 = this.get(0, 0); + const b11 = other.get(0, 0); + const a12 = this.get(0, 1); + const b12 = other.get(0, 1); + const a21 = this.get(1, 0); + const b21 = other.get(1, 0); + const a22 = this.get(1, 1); + const b22 = other.get(1, 1); + + // Compute intermediate values. + const m1 = (a11 + a22) * (b11 + b22); + const m2 = (a21 + a22) * b11; + const m3 = a11 * (b12 - b22); + const m4 = a22 * (b21 - b11); + const m5 = (a11 + a12) * b22; + const m6 = (a21 - a11) * (b11 + b12); + const m7 = (a12 - a22) * (b21 + b22); + + // Combine intermediate values into the output. + const c00 = m1 + m4 - m5 + m7; + const c01 = m3 + m5; + const c10 = m2 + m4; + const c11 = m1 - m2 + m3 + m6; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(1, 0, c10); + result.set(1, 1, c11); + return result; + } + + strassen3x3(other) { + var result = new this.constructor[Symbol.species](3, 3); + + const a00 = this.get(0, 0); + const a01 = this.get(0, 1); + const a02 = this.get(0, 2); + const a10 = this.get(1, 0); + const a11 = this.get(1, 1); + const a12 = this.get(1, 2); + const a20 = this.get(2, 0); + const a21 = this.get(2, 1); + const a22 = this.get(2, 2); + + const b00 = other.get(0, 0); + const b01 = other.get(0, 1); + const b02 = other.get(0, 2); + const b10 = other.get(1, 0); + const b11 = other.get(1, 1); + const b12 = other.get(1, 2); + const b20 = other.get(2, 0); + const b21 = other.get(2, 1); + const b22 = other.get(2, 2); + + const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11; + const m2 = (a00 - a10) * (-b01 + b11); + const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22); + const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11); + const m5 = (a10 + a11) * (-b00 + b01); + const m6 = a00 * b00; + const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12); + const m8 = (-a00 + a20) * (b02 - b12); + const m9 = (a20 + a21) * (-b00 + b02); + const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12; + const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21); + const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21); + const m13 = (a02 - a22) * (b11 - b21); + const m14 = a02 * b20; + const m15 = (a21 + a22) * (-b20 + b21); + const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22); + const m17 = (a02 - a12) * (b12 - b22); + const m18 = (a11 + a12) * (-b20 + b22); + const m19 = a01 * b10; + const m20 = a12 * b21; + const m21 = a10 * b02; + const m22 = a20 * b01; + const m23 = a22 * b22; + + const c00 = m6 + m14 + m19; + const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15; + const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18; + const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17; + const c11 = m2 + m4 + m5 + m6 + m20; + const c12 = m14 + m16 + m17 + m18 + m21; + const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14; + const c21 = m12 + m13 + m14 + m15 + m22; + const c22 = m6 + m7 + m8 + m9 + m23; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(0, 2, c02); + result.set(1, 0, c10); + result.set(1, 1, c11); + result.set(1, 2, c12); + result.set(2, 0, c20); + result.set(2, 1, c21); + result.set(2, 2, c22); + return result; + } + + /** + * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000. + * @param {Matrix} y + * @return {Matrix} + */ + mmulStrassen(y) { + var x = this.clone(); + var r1 = x.rows; + var c1 = x.columns; + var r2 = y.rows; + var c2 = y.columns; + if (c1 !== r2) { + // eslint-disable-next-line no-console + console.warn(`Multiplying ${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. + function embed(mat, rows, cols) { + var r = mat.rows; + var c = mat.columns; + if ((r === rows) && (c === cols)) { + return mat; + } else { + var resultat = Matrix.zeros(rows, cols); + resultat = resultat.setSubMatrix(mat, 0, 0); + return resultat; + } + } + + + // Make sure both matrices are the same size. + // This is exclusively for simplicity: + // this algorithm can be implemented with matrices of different sizes. + + var r = Math.max(r1, r2); + var c = Math.max(c1, c2); + x = embed(x, r, c); + y = embed(y, r, c); + + // Our recursive multiplication function. + function blockMult(a, b, rows, cols) { + // For small matrices, resort to naive multiplication. + if (rows <= 512 || cols <= 512) { + return a.mmul(b); // a is equivalent to this + } + + // Apply dynamic padding. + if ((rows % 2 === 1) && (cols % 2 === 1)) { + a = embed(a, rows + 1, cols + 1); + b = embed(b, rows + 1, cols + 1); + } else if (rows % 2 === 1) { + a = embed(a, rows + 1, cols); + b = embed(b, rows + 1, cols); + } else if (cols % 2 === 1) { + a = embed(a, rows, cols + 1); + b = embed(b, rows, cols + 1); + } + + var halfRows = parseInt(a.rows / 2); + var halfCols = parseInt(a.columns / 2); + // Subdivide input matrices. + var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); + var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); + + var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); + var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); + + var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); + var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); + + var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); + var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); + + // Compute intermediate values. + var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols); + var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols); + var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols); + var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols); + var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols); + var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols); + var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); + + // Combine intermediate values into the output. + var c11 = Matrix.add(m1, m4); + c11.sub(m5); + c11.add(m7); + var c12 = Matrix.add(m3, m5); + var c21 = Matrix.add(m2, m4); + var c22 = Matrix.sub(m1, m2); + c22.add(m3); + c22.add(m6); + + //Crop output to the desired size (undo dynamic padding). + var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns); + resultat = resultat.setSubMatrix(c11, 0, 0); + resultat = resultat.setSubMatrix(c12, c11.rows, 0); + resultat = resultat.setSubMatrix(c21, 0, c11.columns); + resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns); + return resultat.subMatrix(0, rows - 1, 0, cols - 1); + } + return blockMult(x, y, r, c); + } + + /** + * Returns a row-by-row scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The scaled matrix + */ + scaleRows(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.rows; i++) { + var scaled = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__["scale"])(this.getRow(i), {min, max}); + newMatrix.setRow(i, scaled); + } + return newMatrix; + } + + /** + * Returns a new column-by-column scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The new scaled matrix + * @example + * var matrix = new Matrix([[1,2],[-1,0]]); + * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]] + */ + scaleColumns(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.columns; i++) { + var scaled = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__["scale"])(this.getColumn(i), { + min: min, + max: max + }); + newMatrix.setColumn(i, scaled); + } + return newMatrix; + } + + + /** + * Returns the Kronecker product (also known as tensor product) between this and other + * See https://en.wikipedia.org/wiki/Kronecker_product + * @param {Matrix} other + * @return {Matrix} + */ + kroneckerProduct(other) { + other = this.constructor.checkMatrix(other); + + var m = this.rows; + var n = this.columns; + var p = other.rows; + var q = other.columns; + + var result = new this.constructor[Symbol.species](m * p, n * q); + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + for (var k = 0; k < p; k++) { + for (var l = 0; l < q; l++) { + result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l); + } + } + } + } + return result; + } + + /** + * Transposes the matrix and returns a new one containing the result + * @return {Matrix} + */ + transpose() { + var result = new this.constructor[Symbol.species](this.columns, this.rows); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + result.set(j, i, this.get(i, j)); + } + } + return result; + } + + /** + * Sorts the rows (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortRows(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.rows; i++) { + this.setRow(i, this.getRow(i).sort(compareFunction)); + } + return this; + } + + /** + * Sorts the columns (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortColumns(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.columns; i++) { + this.setColumn(i, this.getColumn(i).sort(compareFunction)); + } + return this; + } + + /** + * Returns a subset of the matrix + * @param {number} startRow - First row index + * @param {number} endRow - Last row index + * @param {number} startColumn - First column index + * @param {number} endColumn - Last column index + * @return {Matrix} + */ + subMatrix(startRow, endRow, startColumn, endColumn) { + __WEBPACK_IMPORTED_MODULE_3__util__["h" /* checkRange */](this, startRow, endRow, startColumn, endColumn); + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1); + for (var i = startRow; i <= endRow; i++) { + for (var j = startColumn; j <= endColumn; j++) { + newMatrix[i - startRow][j - startColumn] = this.get(i, j); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of row indices + * @param {Array} indices - Array containing the row indices + * @param {number} [startColumn = 0] - First column index + * @param {number} [endColumn = this.columns-1] - Last column index + * @return {Matrix} + */ + subMatrixRow(indices, startColumn, endColumn) { + if (startColumn === undefined) startColumn = 0; + if (endColumn === undefined) endColumn = this.columns - 1; + if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1); + for (var i = 0; i < indices.length; i++) { + for (var j = startColumn; j <= endColumn; j++) { + if (indices[i] < 0 || indices[i] >= this.rows) { + throw new RangeError('Row index out of range: ' + indices[i]); + } + newMatrix.set(i, j - startColumn, this.get(indices[i], j)); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of column indices + * @param {Array} indices - Array containing the column indices + * @param {number} [startRow = 0] - First row index + * @param {number} [endRow = this.rows-1] - Last row index + * @return {Matrix} + */ + subMatrixColumn(indices, startRow, endRow) { + if (startRow === undefined) startRow = 0; + if (endRow === undefined) endRow = this.rows - 1; + if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length); + for (var i = 0; i < indices.length; i++) { + for (var j = startRow; j <= endRow; j++) { + if (indices[i] < 0 || indices[i] >= this.columns) { + throw new RangeError('Column index out of range: ' + indices[i]); + } + newMatrix.set(j - startRow, i, this.get(j, indices[i])); + } + } + return newMatrix; + } + + /** + * Set a part of the matrix to the given sub-matrix + * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values. + * @param {number} startRow - The index of the first row to set + * @param {number} startColumn - The index of the first column to set + * @return {Matrix} + */ + setSubMatrix(matrix, startRow, startColumn) { + matrix = this.constructor.checkMatrix(matrix); + var endRow = startRow + matrix.rows - 1; + var endColumn = startColumn + matrix.columns - 1; + __WEBPACK_IMPORTED_MODULE_3__util__["h" /* checkRange */](this, startRow, endRow, startColumn, endColumn); + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + this[startRow + i][startColumn + j] = matrix.get(i, j); + } + } + return this; + } + + /** + * Return a new matrix based on a selection of rows and columns + * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once. + * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once. + * @return {Matrix} The new matrix + */ + selection(rowIndices, columnIndices) { + var indices = __WEBPACK_IMPORTED_MODULE_3__util__["i" /* checkIndices */](this, rowIndices, columnIndices); + var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length); + for (var i = 0; i < indices.row.length; i++) { + var rowIndex = indices.row[i]; + for (var j = 0; j < indices.column.length; j++) { + var columnIndex = indices.column[j]; + newMatrix[i][j] = this.get(rowIndex, columnIndex); + } + } + return newMatrix; + } + + /** + * Returns the trace of the matrix (sum of the diagonal elements) + * @return {number} + */ + trace() { + var min = Math.min(this.rows, this.columns); + var trace = 0; + for (var i = 0; i < min; i++) { + trace += this.get(i, i); + } + return trace; + } + + /* + Matrix views + */ + + /** + * Returns a view of the transposition of the matrix + * @return {MatrixTransposeView} + */ + transposeView() { + return new __WEBPACK_IMPORTED_MODULE_4__views_transpose__["a" /* default */](this); + } + + /** + * Returns a view of the row vector with the given index + * @param {number} row - row index of the vector + * @return {MatrixRowView} + */ + rowView(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + return new __WEBPACK_IMPORTED_MODULE_5__views_row__["a" /* default */](this, row); + } + + /** + * Returns a view of the column vector with the given index + * @param {number} column - column index of the vector + * @return {MatrixColumnView} + */ + columnView(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + return new __WEBPACK_IMPORTED_MODULE_8__views_column__["a" /* default */](this, column); + } + + /** + * Returns a view of the matrix flipped in the row axis + * @return {MatrixFlipRowView} + */ + flipRowView() { + return new __WEBPACK_IMPORTED_MODULE_9__views_flipRow__["a" /* default */](this); + } + + /** + * Returns a view of the matrix flipped in the column axis + * @return {MatrixFlipColumnView} + */ + flipColumnView() { + return new __WEBPACK_IMPORTED_MODULE_10__views_flipColumn__["a" /* default */](this); + } + + /** + * Returns a view of a submatrix giving the index boundaries + * @param {number} startRow - first row index of the submatrix + * @param {number} endRow - last row index of the submatrix + * @param {number} startColumn - first column index of the submatrix + * @param {number} endColumn - last column index of the submatrix + * @return {MatrixSubView} + */ + subMatrixView(startRow, endRow, startColumn, endColumn) { + return new __WEBPACK_IMPORTED_MODULE_6__views_sub__["a" /* default */](this, startRow, endRow, startColumn, endColumn); + } + + /** + * Returns a view of the cross of the row indices and the column indices + * @example + * // resulting vector is [[2], [2]] + * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1]) + * @param {Array} rowIndices + * @param {Array} columnIndices + * @return {MatrixSelectionView} + */ + selectionView(rowIndices, columnIndices) { + return new __WEBPACK_IMPORTED_MODULE_7__views_selection__["a" /* default */](this, rowIndices, columnIndices); + } + + + /** + * Calculates and returns the determinant of a matrix as a Number + * @example + * new Matrix([[1,2,3], [4,5,6]]).det() + * @return {number} + */ + det() { + if (this.isSquare()) { + var a, b, c, d; + if (this.columns === 2) { + // 2 x 2 matrix + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(1, 0); + d = this.get(1, 1); + + return a * d - (b * c); + } else if (this.columns === 3) { + // 3 x 3 matrix + var subMatrix0, subMatrix1, subMatrix2; + subMatrix0 = this.selectionView([1, 2], [1, 2]); + subMatrix1 = this.selectionView([1, 2], [0, 2]); + subMatrix2 = this.selectionView([1, 2], [0, 1]); + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(0, 2); + + return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det(); + } else { + // general purpose determinant using the LU decomposition + return new __WEBPACK_IMPORTED_MODULE_0__dc_lu__["a" /* default */](this).determinant; + } + + } else { + throw Error('Determinant can only be calculated for a square matrix.'); + } + } + + /** + * Returns inverse of a matrix if it exists or the pseudoinverse + * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15) + * @return {Matrix} the (pseudo)inverted matrix. + */ + pseudoInverse(threshold) { + if (threshold === undefined) threshold = Number.EPSILON; + var svdSolution = new __WEBPACK_IMPORTED_MODULE_1__dc_svd__["a" /* default */](this, {autoTranspose: true}); + + var U = svdSolution.leftSingularVectors; + var V = svdSolution.rightSingularVectors; + var s = svdSolution.diagonal; + + for (var i = 0; i < s.length; i++) { + if (Math.abs(s[i]) > threshold) { + s[i] = 1.0 / s[i]; + } else { + s[i] = 0.0; + } + } + + // convert list to diagonal + s = this.constructor[Symbol.species].diag(s); + return V.mmul(s.mmul(U.transposeView())); + } + } + + Matrix.prototype.klass = 'Matrix'; + + function compareNumbers(a, b) { + return a - b; + } + + /* + Synonyms + */ + + Matrix.random = Matrix.rand; + Matrix.diagonal = Matrix.diag; + Matrix.prototype.diagonal = Matrix.prototype.diag; + Matrix.identity = Matrix.eye; + Matrix.prototype.negate = Matrix.prototype.neg; + Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct; + Matrix.prototype.determinant = Matrix.prototype.det; + + /* + Add dynamically instance and static methods for mathematical operations + */ + + var inplaceOperator = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var inplaceOperatorScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% value); + } + } + return this; +}) +`; + + var inplaceOperatorMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); + } + } + return this; +}) +`; + + var staticOperator = ` +(function %name%(matrix, value) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(value); +}) +`; + + var inplaceMethod = ` +(function %name%() { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j))); + } + } + return this; +}) +`; + + var staticMethod = ` +(function %name%(matrix) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(); +}) +`; + + var inplaceMethodWithArgs = ` +(function %name%(%args%) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), %args%)); + } + } + return this; +}) +`; + + var staticMethodWithArgs = ` +(function %name%(matrix, %args%) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(%args%); +}) +`; + + + var inplaceMethodWithOneArgScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), value)); + } + } + return this; +}) +`; + var inplaceMethodWithOneArgMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); + } + } + return this; +}) +`; + + var inplaceMethodWithOneArg = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var staticMethodWithOneArg = staticMethodWithArgs; + + var operators = [ + // Arithmetic operators + ['+', 'add'], + ['-', 'sub', 'subtract'], + ['*', 'mul', 'multiply'], + ['/', 'div', 'divide'], + ['%', 'mod', 'modulus'], + // Bitwise operators + ['&', 'and'], + ['|', 'or'], + ['^', 'xor'], + ['<<', 'leftShift'], + ['>>', 'signPropagatingRightShift'], + ['>>>', 'rightShift', 'zeroFillRightShift'] + ]; + + var i; + var eval2 = eval; + for (var operator of operators) { + var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]})); + var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]})); + var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]})); + var staticOp = eval2(fillTemplateFunction(staticOperator, {name: operator[1]})); + for (i = 1; i < operator.length; i++) { + Matrix.prototype[operator[i]] = inplaceOp; + Matrix.prototype[operator[i] + 'S'] = inplaceOpS; + Matrix.prototype[operator[i] + 'M'] = inplaceOpM; + Matrix[operator[i]] = staticOp; + } + } + + 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]); + }); + + for (var method of methods) { + var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]})); + var staticMeth = eval2(fillTemplateFunction(staticMethod, {name: method[1]})); + for (i = 1; i < method.length; i++) { + Matrix.prototype[method[i]] = inplaceMeth; + Matrix[method[i]] = staticMeth; + } + } + + var methodsWithArgs = [ + ['Math.pow', 1, 'pow'] + ]; + + for (var methodWithArg of methodsWithArgs) { + var args = 'arg0'; + for (i = 1; i < methodWithArg[1]; i++) { + args += `, arg${i}`; + } + if (methodWithArg[1] !== 1) { + var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, { + name: methodWithArg[2], + method: methodWithArg[0], + args: args + })); + var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args})); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs; + Matrix[methodWithArg[i]] = staticMethWithArgs; + } + } else { + var tmplVar = { + name: methodWithArg[2], + args: args, + method: methodWithArg[0] + }; + var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar)); + var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar)); + var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar)); + var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar)); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethod2; + Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM; + Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS; + Matrix[methodWithArg[i]] = staticMethod2; + } + } + } + + function fillTemplateFunction(template, values) { + for (var value in values) { + template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]); + } + return template; + } + + return Matrix; +} + + +/***/ }), +/* 24 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(3); + + +// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs +function LuDecomposition(matrix) { + if (!(this instanceof LuDecomposition)) { + return new LuDecomposition(matrix); + } + + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + + var lu = matrix.clone(), + rows = lu.rows, + columns = lu.columns, + pivotVector = new Array(rows), + pivotSign = 1, + i, j, k, p, s, t, v, + LUrowi, LUcolj, kmax; + + for (i = 0; i < rows; i++) { + pivotVector[i] = i; + } + + LUcolj = new Array(rows); + + for (j = 0; j < columns; j++) { + + for (i = 0; i < rows; i++) { + LUcolj[i] = lu[i][j]; + } + + for (i = 0; i < rows; i++) { + LUrowi = lu[i]; + kmax = Math.min(i, j); + s = 0; + for (k = 0; k < kmax; k++) { + s += LUrowi[k] * LUcolj[k]; + } + LUrowi[j] = LUcolj[i] -= s; + } + + 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[p][k]; + lu[p][k] = lu[j][k]; + lu[j][k] = t; + } + + v = pivotVector[p]; + pivotVector[p] = pivotVector[j]; + pivotVector[j] = v; + + pivotSign = -pivotSign; + } + + if (j < rows && lu[j][j] !== 0) { + for (i = j + 1; i < rows; i++) { + lu[i][j] /= lu[j][j]; + } + } + } + + this.LU = lu; + this.pivotVector = pivotVector; + this.pivotSign = pivotSign; +} + +LuDecomposition.prototype = { + isSingular: function () { + var data = this.LU, + col = data.columns; + for (var j = 0; j < col; j++) { + if (data[j][j] === 0) { + return true; + } + } + return false; + }, + get determinant() { + var data = this.LU; + if (!data.isSquare()) { + throw new Error('Matrix must be square'); + } + var determinant = this.pivotSign, col = data.columns; + for (var j = 0; j < col; j++) { + determinant *= data[j][j]; + } + return determinant; + }, + get lowerTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i > j) { + X[i][j] = data[i][j]; + } else if (i === j) { + X[i][j] = 1; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get upperTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i <= j) { + X[i][j] = data[i][j]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get pivotPermutationVector() { + return this.pivotVector.slice(); + }, + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var lu = this.LU, + rows = lu.rows; + + if (rows !== value.rows) { + throw new Error('Invalid matrix dimensions'); + } + if (this.isSingular()) { + throw new Error('LU matrix is singular'); + } + + var count = value.columns; + var X = value.subMatrixRow(this.pivotVector, 0, count - 1); + var columns = lu.columns; + var i, j, k; + + for (k = 0; k < columns; k++) { + for (i = k + 1; i < columns; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + for (k = columns - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= lu[k][k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + return X; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (LuDecomposition); + + +/***/ }), +/* 25 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = hypotenuse; +/* unused harmony export getEmpty2DArray */ +/* harmony export (immutable) */ __webpack_exports__["b"] = getFilled2DArray; +function hypotenuse(a, b) { + var r; + if (Math.abs(a) > Math.abs(b)) { + r = b / a; + return Math.abs(a) * Math.sqrt(1 + r * r); + } + if (b !== 0) { + r = a / b; + return Math.abs(b) * Math.sqrt(1 + r * r); + } + return 0; +} + +// For use in the decomposition algorithms. With big matrices, access time is +// too long on elements from array subclass +// todo check when it is fixed in v8 +// http://jsperf.com/access-and-write-array-subclass +function getEmpty2DArray(rows, columns) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + } + return array; +} + +function getFilled2DArray(rows, columns, value) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + for (var j = 0; j < columns; j++) { + array[i][j] = value; + } + } + return array; +} + + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.hypotenuse = function hypotenuse(a, b) { + var r; + if (Math.abs(a) > Math.abs(b)) { + r = b / a; + return Math.abs(a) * Math.sqrt(1 + r * r); + } + if (b !== 0) { + r = a / b; + return Math.abs(b) * Math.sqrt(1 + r * r); + } + return 0; +}; + +// For use in the decomposition algorithms. With big matrices, access time is +// too long on elements from array subclass +// todo check when it is fixed in v8 +// http://jsperf.com/access-and-write-array-subclass +exports.getEmpty2DArray = function (rows, columns) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + } + return array; +}; + +exports.getFilled2DArray = function (rows, columns, value) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + for (var j = 0; j < columns; j++) { + array[i][j] = value; + } + } + return array; +}; + + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const Matrix = __webpack_require__(0); +const Stat = __webpack_require__(2); + +/** + * Function that given vector, returns his norm + * @param {Vector} X + * @returns {number} Norm of the vector + */ +function norm(X) { + return Math.sqrt(X.clone().apply(pow2array).sum()); +} + +/** + * Function that pow 2 each element of a Matrix or a Vector, + * used in the apply method of the Matrix object + * @param i - index i. + * @param j - index j. + * @return The Matrix object modified at the index i, j. + * */ +function pow2array(i, j) { + this[i][j] = this[i][j] * this[i][j]; + return this; +} + +/** + * Function that normalize the dataset and return the means and + * standard deviation of each feature. + * @param dataset + * @returns {{result: Matrix, means: (*|number), std: Matrix}} dataset normalized, means + * and standard deviations + */ +function featureNormalize(dataset) { + var means = Stat.matrix.mean(dataset); + var std = Stat.matrix.standardDeviation(dataset, means, true); + var result = Matrix.checkMatrix(dataset).subRowVector(means); + return {result: result.divRowVector(std), means: means, std: std}; +} + +module.exports = { + norm: norm, + pow2array: pow2array, + featureNormalize: featureNormalize +}; + + +/***/ }), +/* 28 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = AbstractMatrix; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__dc_lu__ = __webpack_require__(29); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__dc_svd__ = __webpack_require__(67); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ml_array_utils__ = __webpack_require__(13); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ml_array_utils___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(17); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__views_transpose__ = __webpack_require__(214); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__views_row__ = __webpack_require__(211); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__views_sub__ = __webpack_require__(213); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__views_selection__ = __webpack_require__(212); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__views_column__ = __webpack_require__(208); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__views_flipRow__ = __webpack_require__(210); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__views_flipColumn__ = __webpack_require__(209); + + + + + + + + + + + + +function AbstractMatrix(superCtor) { + if (superCtor === undefined) superCtor = Object; + + /** + * Real matrix + * @class Matrix + * @param {number|Array|Matrix} nRows - Number of rows of the new matrix, + * 2D array containing the data or Matrix instance to clone + * @param {number} [nColumns] - Number of columns of the new matrix + */ + class Matrix extends superCtor { + static get [Symbol.species]() { + return this; + } + + /** + * Constructs a Matrix with the chosen dimensions from a 1D array + * @param {number} newRows - Number of rows + * @param {number} newColumns - Number of columns + * @param {Array} newData - A 1D array containing data for the matrix + * @return {Matrix} - The new matrix + */ + static from1DArray(newRows, newColumns, newData) { + var length = newRows * newColumns; + if (length !== newData.length) { + throw new RangeError('Data length does not match given dimensions'); + } + var newMatrix = new this(newRows, newColumns); + for (var row = 0; row < newRows; row++) { + for (var column = 0; column < newColumns; column++) { + newMatrix.set(row, column, newData[row * newColumns + column]); + } + } + return newMatrix; + } + + /** + * Creates a row vector, a matrix with only one row. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static rowVector(newData) { + var vector = new this(1, newData.length); + for (var i = 0; i < newData.length; i++) { + vector.set(0, i, newData[i]); + } + return vector; + } + + /** + * Creates a column vector, a matrix with only one column. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static columnVector(newData) { + var vector = new this(newData.length, 1); + for (var i = 0; i < newData.length; i++) { + vector.set(i, 0, newData[i]); + } + return vector; + } + + /** + * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns). + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static empty(rows, columns) { + return new this(rows, columns); + } + + /** + * Creates a matrix with the given dimensions. Values will be set to zero. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static zeros(rows, columns) { + return this.empty(rows, columns).fill(0); + } + + /** + * Creates a matrix with the given dimensions. Values will be set to one. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static ones(rows, columns) { + return this.empty(rows, columns).fill(1); + } + + /** + * Creates a matrix with the given dimensions. Values will be randomly set. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static rand(rows, columns, rng) { + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + matrix.set(i, j, rng()); + } + } + return matrix; + } + + /** + * Creates a matrix with the given dimensions. Values will be random integers. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {number} [maxValue=1000] - Maximum value + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static randInt(rows, columns, maxValue, rng) { + if (maxValue === undefined) maxValue = 1000; + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + var value = Math.floor(rng() * maxValue); + matrix.set(i, j, value); + } + } + return matrix; + } + + /** + * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0. + * @param {number} rows - Number of rows + * @param {number} [columns=rows] - Number of columns + * @param {number} [value=1] - Value to fill the diagonal with + * @return {Matrix} - The new identity matrix + */ + static eye(rows, columns, value) { + if (columns === undefined) columns = rows; + if (value === undefined) value = 1; + var min = Math.min(rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, value); + } + return matrix; + } + + /** + * Creates a diagonal matrix based on the given array. + * @param {Array} data - Array containing the data for the diagonal + * @param {number} [rows] - Number of rows (Default: data.length) + * @param {number} [columns] - Number of columns (Default: rows) + * @return {Matrix} - The new diagonal matrix + */ + static diag(data, rows, columns) { + var l = data.length; + if (rows === undefined) rows = l; + if (columns === undefined) columns = rows; + var min = Math.min(l, rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, data[i]); + } + return matrix; + } + + /** + * Returns a matrix whose elements are the minimum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static min(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } + + /** + * Returns a matrix whose elements are the maximum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static max(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } + + /** + * Check that the provided value is a Matrix and tries to instantiate one if not + * @param {*} value - The value to check + * @return {Matrix} + */ + static checkMatrix(value) { + return Matrix.isMatrix(value) ? value : new this(value); + } + + /** + * Returns true if the argument is a Matrix, false otherwise + * @param {*} value - The value to check + * @return {boolean} + */ + static isMatrix(value) { + return (value != null) && (value.klass === 'Matrix'); + } + + /** + * @prop {number} size - The number of elements in the matrix. + */ + get size() { + return this.rows * this.columns; + } + + /** + * Applies a callback for each element of the matrix. The function is called in the matrix (this) context. + * @param {function} callback - Function that will be called with two parameters : i (row) and j (column) + * @return {Matrix} this + */ + apply(callback) { + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); + } + var ii = this.rows; + var jj = this.columns; + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + callback.call(this, i, j); + } + } + return this; + } + + /** + * Returns a new 1D array filled row by row with the matrix values + * @return {Array} + */ + to1DArray() { + var array = new Array(this.size); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + array[i * this.columns + j] = this.get(i, j); + } + } + return array; + } + + /** + * Returns a 2D array containing a copy of the data + * @return {Array} + */ + to2DArray() { + var copy = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + copy[i] = new Array(this.columns); + for (var j = 0; j < this.columns; j++) { + copy[i][j] = this.get(i, j); + } + } + return copy; + } + + /** + * @return {boolean} true if the matrix has one row + */ + isRowVector() { + return this.rows === 1; + } + + /** + * @return {boolean} true if the matrix has one column + */ + isColumnVector() { + return this.columns === 1; + } + + /** + * @return {boolean} true if the matrix has one row or one column + */ + isVector() { + return (this.rows === 1) || (this.columns === 1); + } + + /** + * @return {boolean} true if the matrix has the same number of rows and columns + */ + isSquare() { + return this.rows === this.columns; + } + + /** + * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal + */ + isSymmetric() { + if (this.isSquare()) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j <= i; j++) { + if (this.get(i, j) !== this.get(j, i)) { + return false; + } + } + } + return true; + } + return false; + } + + /** + * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1 + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @param {number} value - The new value for the element + * @return {Matrix} this + */ + set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars + throw new Error('set method is unimplemented'); + } + + /** + * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4] + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @return {number} + */ + get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars + throw new Error('get method is unimplemented'); + } + + /** + * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of + * rows of the matrix, and colRep times the number of columns of the matrix + * @param {number} rowRep - Number of times the rows should be repeated + * @param {number} colRep - Number of times the columns should be re + * @return {Matrix} + * @example + * var matrix = new Matrix([[1,2]]); + * matrix.repeat(2); // [[1,2],[1,2]] + */ + repeat(rowRep, colRep) { + rowRep = rowRep || 1; + colRep = colRep || 1; + var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep); + for (var i = 0; i < rowRep; i++) { + for (var j = 0; j < colRep; j++) { + matrix.setSubMatrix(this, this.rows * i, this.columns * j); + } + } + return matrix; + } + + /** + * Fills the matrix with a given value. All elements will be set to this value. + * @param {number} value - New value + * @return {Matrix} this + */ + fill(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, value); + } + } + return this; + } + + /** + * Negates the matrix. All elements will be multiplied by (-1) + * @return {Matrix} this + */ + neg() { + return this.mulS(-1); + } + + /** + * Returns a new array from the given row index + * @param {number} index - Row index + * @return {Array} + */ + getRow(index) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + var row = new Array(this.columns); + for (var i = 0; i < this.columns; i++) { + row[i] = this.get(index, i); + } + return row; + } + + /** + * Returns a new row vector from the given row index + * @param {number} index - Row index + * @return {Matrix} + */ + getRowVector(index) { + return this.constructor.rowVector(this.getRow(index)); + } + + /** + * Sets a row at the given index + * @param {number} index - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setRow(index, array) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + array = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, array); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, array[i]); + } + return this; + } + + /** + * Swaps two rows + * @param {number} row1 - First row index + * @param {number} row2 - Second row index + * @return {Matrix} this + */ + swapRows(row1, row2) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row1); + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row2); + for (var i = 0; i < this.columns; i++) { + var temp = this.get(row1, i); + this.set(row1, i, this.get(row2, i)); + this.set(row2, i, temp); + } + return this; + } + + /** + * Returns a new array from the given column index + * @param {number} index - Column index + * @return {Array} + */ + getColumn(index) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + var column = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + column[i] = this.get(i, index); + } + return column; + } + + /** + * Returns a new column vector from the given column index + * @param {number} index - Column index + * @return {Matrix} + */ + getColumnVector(index) { + return this.constructor.columnVector(this.getColumn(index)); + } + + /** + * Sets a column at the given index + * @param {number} index - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setColumn(index, array) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + array = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, array); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, array[i]); + } + return this; + } + + /** + * Swaps two columns + * @param {number} column1 - First column index + * @param {number} column2 - Second column index + * @return {Matrix} this + */ + swapColumns(column1, column2) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column1); + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column2); + for (var i = 0; i < this.rows; i++) { + var temp = this.get(i, column1); + this.set(i, column1, this.get(i, column2)); + this.set(i, column2, temp); + } + return this; + } + + /** + * Adds the values of a vector to each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[j]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[j]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[j]); + } + } + return this; + } + + /** + * Divides the values of each row by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[j]); + } + } + return this; + } + + /** + * Adds the values of a vector to each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[i]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[i]); + } + } + return this; + } + + /** + * Divides the values of each column by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a row with a scalar + * @param {number} index - Row index + * @param {number} value + * @return {Matrix} this + */ + mulRow(index, value) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, this.get(index, i) * value); + } + return this; + } + + /** + * Multiplies the values of a column with a scalar + * @param {number} index - Column index + * @param {number} value + * @return {Matrix} this + */ + mulColumn(index, value) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, this.get(i, index) * value); + } + return this; + } + + /** + * Returns the maximum value of the matrix + * @return {number} + */ + max() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the maximum value + * @return {Array} + */ + maxIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the minimum value of the matrix + * @return {number} + */ + min() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the minimum value + * @return {Array} + */ + minIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the maximum value of one row + * @param {number} row - Row index + * @return {number} + */ + maxRow(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + maxRowIndex(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one row + * @param {number} row - Row index + * @return {number} + */ + minRow(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + minRowIndex(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the maximum value of one column + * @param {number} column - Column index + * @return {number} + */ + maxColumn(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one column + * @param {number} column - Column index + * @return {Array} + */ + maxColumnIndex(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one column + * @param {number} column - Column index + * @return {number} + */ + minColumn(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the minimum value of one column + * @param {number} column - Column index + * @return {Array} + */ + minColumnIndex(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns an array containing the diagonal values of the matrix + * @return {Array} + */ + diag() { + var min = Math.min(this.rows, this.columns); + var diag = new Array(min); + for (var i = 0; i < min; i++) { + diag[i] = this.get(i, i); + } + return diag; + } + + /** + * Returns the sum by the argument given, if no argument given, + * it returns the sum of all elements of the matrix. + * @param {string} by - sum by 'row' or 'column'. + * @return {Matrix|number} + */ + sum(by) { + switch (by) { + case 'row': + return __WEBPACK_IMPORTED_MODULE_3__util__["e" /* sumByRow */](this); + case 'column': + return __WEBPACK_IMPORTED_MODULE_3__util__["f" /* sumByColumn */](this); + default: + return __WEBPACK_IMPORTED_MODULE_3__util__["g" /* sumAll */](this); + } + } + + /** + * Returns the mean of all elements of the matrix + * @return {number} + */ + mean() { + return this.sum() / this.size; + } + + /** + * Returns the product of all elements of the matrix + * @return {number} + */ + prod() { + var prod = 1; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + prod *= this.get(i, j); + } + } + return prod; + } + + /** + * Computes the cumulative sum of the matrix elements (in place, row by row) + * @return {Matrix} this + */ + cumulativeSum() { + var sum = 0; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + sum += this.get(i, j); + this.set(i, j, sum); + } + } + return this; + } + + /** + * Computes the dot (scalar) product between the matrix and another + * @param {Matrix} vector2 vector + * @return {number} + */ + dot(vector2) { + if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); + var vector1 = this.to1DArray(); + if (vector1.length !== vector2.length) { + throw new RangeError('vectors do not have the same size'); + } + var dot = 0; + for (var i = 0; i < vector1.length; i++) { + dot += vector1[i] * vector2[i]; + } + return dot; + } + + /** + * Returns the matrix product between this and other + * @param {Matrix} other + * @return {Matrix} + */ + mmul(other) { + other = this.constructor.checkMatrix(other); + if (this.columns !== other.rows) { + // eslint-disable-next-line no-console + console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); + } + + var m = this.rows; + var n = this.columns; + var p = other.columns; + + var result = new this.constructor[Symbol.species](m, p); + + var Bcolj = new Array(n); + for (var j = 0; j < p; j++) { + for (var k = 0; k < n; k++) { + Bcolj[k] = other.get(k, j); + } + + for (var i = 0; i < m; i++) { + var s = 0; + for (k = 0; k < n; k++) { + s += this.get(i, k) * Bcolj[k]; + } + + result.set(i, j, s); + } + } + return result; + } + + strassen2x2(other) { + var result = new this.constructor[Symbol.species](2, 2); + const a11 = this.get(0, 0); + const b11 = other.get(0, 0); + const a12 = this.get(0, 1); + const b12 = other.get(0, 1); + const a21 = this.get(1, 0); + const b21 = other.get(1, 0); + const a22 = this.get(1, 1); + const b22 = other.get(1, 1); + + // Compute intermediate values. + const m1 = (a11 + a22) * (b11 + b22); + const m2 = (a21 + a22) * b11; + const m3 = a11 * (b12 - b22); + const m4 = a22 * (b21 - b11); + const m5 = (a11 + a12) * b22; + const m6 = (a21 - a11) * (b11 + b12); + const m7 = (a12 - a22) * (b21 + b22); + + // Combine intermediate values into the output. + const c00 = m1 + m4 - m5 + m7; + const c01 = m3 + m5; + const c10 = m2 + m4; + const c11 = m1 - m2 + m3 + m6; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(1, 0, c10); + result.set(1, 1, c11); + return result; + } + + strassen3x3(other) { + var result = new this.constructor[Symbol.species](3, 3); + + const a00 = this.get(0, 0); + const a01 = this.get(0, 1); + const a02 = this.get(0, 2); + const a10 = this.get(1, 0); + const a11 = this.get(1, 1); + const a12 = this.get(1, 2); + const a20 = this.get(2, 0); + const a21 = this.get(2, 1); + const a22 = this.get(2, 2); + + const b00 = other.get(0, 0); + const b01 = other.get(0, 1); + const b02 = other.get(0, 2); + const b10 = other.get(1, 0); + const b11 = other.get(1, 1); + const b12 = other.get(1, 2); + const b20 = other.get(2, 0); + const b21 = other.get(2, 1); + const b22 = other.get(2, 2); + + const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11; + const m2 = (a00 - a10) * (-b01 + b11); + const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22); + const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11); + const m5 = (a10 + a11) * (-b00 + b01); + const m6 = a00 * b00; + const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12); + const m8 = (-a00 + a20) * (b02 - b12); + const m9 = (a20 + a21) * (-b00 + b02); + const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12; + const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21); + const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21); + const m13 = (a02 - a22) * (b11 - b21); + const m14 = a02 * b20; + const m15 = (a21 + a22) * (-b20 + b21); + const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22); + const m17 = (a02 - a12) * (b12 - b22); + const m18 = (a11 + a12) * (-b20 + b22); + const m19 = a01 * b10; + const m20 = a12 * b21; + const m21 = a10 * b02; + const m22 = a20 * b01; + const m23 = a22 * b22; + + const c00 = m6 + m14 + m19; + const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15; + const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18; + const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17; + const c11 = m2 + m4 + m5 + m6 + m20; + const c12 = m14 + m16 + m17 + m18 + m21; + const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14; + const c21 = m12 + m13 + m14 + m15 + m22; + const c22 = m6 + m7 + m8 + m9 + m23; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(0, 2, c02); + result.set(1, 0, c10); + result.set(1, 1, c11); + result.set(1, 2, c12); + result.set(2, 0, c20); + result.set(2, 1, c21); + result.set(2, 2, c22); + return result; + } + + /** + * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000. + * @param {Matrix} y + * @return {Matrix} + */ + mmulStrassen(y) { + var x = this.clone(); + var r1 = x.rows; + var c1 = x.columns; + var r2 = y.rows; + var c2 = y.columns; + if (c1 !== r2) { + // eslint-disable-next-line no-console + console.warn(`Multiplying ${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. + function embed(mat, rows, cols) { + var r = mat.rows; + var c = mat.columns; + if ((r === rows) && (c === cols)) { + return mat; + } else { + var resultat = Matrix.zeros(rows, cols); + resultat = resultat.setSubMatrix(mat, 0, 0); + return resultat; + } + } + + + // Make sure both matrices are the same size. + // This is exclusively for simplicity: + // this algorithm can be implemented with matrices of different sizes. + + var r = Math.max(r1, r2); + var c = Math.max(c1, c2); + x = embed(x, r, c); + y = embed(y, r, c); + + // Our recursive multiplication function. + function blockMult(a, b, rows, cols) { + // For small matrices, resort to naive multiplication. + if (rows <= 512 || cols <= 512) { + return a.mmul(b); // a is equivalent to this + } + + // Apply dynamic padding. + if ((rows % 2 === 1) && (cols % 2 === 1)) { + a = embed(a, rows + 1, cols + 1); + b = embed(b, rows + 1, cols + 1); + } else if (rows % 2 === 1) { + a = embed(a, rows + 1, cols); + b = embed(b, rows + 1, cols); + } else if (cols % 2 === 1) { + a = embed(a, rows, cols + 1); + b = embed(b, rows, cols + 1); + } + + var halfRows = parseInt(a.rows / 2); + var halfCols = parseInt(a.columns / 2); + // Subdivide input matrices. + var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); + var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); + + var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); + var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); + + var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); + var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); + + var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); + var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); + + // Compute intermediate values. + var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols); + var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols); + var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols); + var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols); + var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols); + var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols); + var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); + + // Combine intermediate values into the output. + var c11 = Matrix.add(m1, m4); + c11.sub(m5); + c11.add(m7); + var c12 = Matrix.add(m3, m5); + var c21 = Matrix.add(m2, m4); + var c22 = Matrix.sub(m1, m2); + c22.add(m3); + c22.add(m6); + + //Crop output to the desired size (undo dynamic padding). + var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns); + resultat = resultat.setSubMatrix(c11, 0, 0); + resultat = resultat.setSubMatrix(c12, c11.rows, 0); + resultat = resultat.setSubMatrix(c21, 0, c11.columns); + resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns); + return resultat.subMatrix(0, rows - 1, 0, cols - 1); + } + return blockMult(x, y, r, c); + } + + /** + * Returns a row-by-row scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The scaled matrix + */ + scaleRows(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.rows; i++) { + var scaled = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__["scale"])(this.getRow(i), {min, max}); + newMatrix.setRow(i, scaled); + } + return newMatrix; + } + + /** + * Returns a new column-by-column scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The new scaled matrix + * @example + * var matrix = new Matrix([[1,2],[-1,0]]); + * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]] + */ + scaleColumns(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.columns; i++) { + var scaled = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__["scale"])(this.getColumn(i), { + min: min, + max: max + }); + newMatrix.setColumn(i, scaled); + } + return newMatrix; + } + + + /** + * Returns the Kronecker product (also known as tensor product) between this and other + * See https://en.wikipedia.org/wiki/Kronecker_product + * @param {Matrix} other + * @return {Matrix} + */ + kroneckerProduct(other) { + other = this.constructor.checkMatrix(other); + + var m = this.rows; + var n = this.columns; + var p = other.rows; + var q = other.columns; + + var result = new this.constructor[Symbol.species](m * p, n * q); + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + for (var k = 0; k < p; k++) { + for (var l = 0; l < q; l++) { + result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l); + } + } + } + } + return result; + } + + /** + * Transposes the matrix and returns a new one containing the result + * @return {Matrix} + */ + transpose() { + var result = new this.constructor[Symbol.species](this.columns, this.rows); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + result.set(j, i, this.get(i, j)); + } + } + return result; + } + + /** + * Sorts the rows (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortRows(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.rows; i++) { + this.setRow(i, this.getRow(i).sort(compareFunction)); + } + return this; + } + + /** + * Sorts the columns (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortColumns(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.columns; i++) { + this.setColumn(i, this.getColumn(i).sort(compareFunction)); + } + return this; + } + + /** + * Returns a subset of the matrix + * @param {number} startRow - First row index + * @param {number} endRow - Last row index + * @param {number} startColumn - First column index + * @param {number} endColumn - Last column index + * @return {Matrix} + */ + subMatrix(startRow, endRow, startColumn, endColumn) { + __WEBPACK_IMPORTED_MODULE_3__util__["h" /* checkRange */](this, startRow, endRow, startColumn, endColumn); + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1); + for (var i = startRow; i <= endRow; i++) { + for (var j = startColumn; j <= endColumn; j++) { + newMatrix[i - startRow][j - startColumn] = this.get(i, j); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of row indices + * @param {Array} indices - Array containing the row indices + * @param {number} [startColumn = 0] - First column index + * @param {number} [endColumn = this.columns-1] - Last column index + * @return {Matrix} + */ + subMatrixRow(indices, startColumn, endColumn) { + if (startColumn === undefined) startColumn = 0; + if (endColumn === undefined) endColumn = this.columns - 1; + if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1); + for (var i = 0; i < indices.length; i++) { + for (var j = startColumn; j <= endColumn; j++) { + if (indices[i] < 0 || indices[i] >= this.rows) { + throw new RangeError('Row index out of range: ' + indices[i]); + } + newMatrix.set(i, j - startColumn, this.get(indices[i], j)); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of column indices + * @param {Array} indices - Array containing the column indices + * @param {number} [startRow = 0] - First row index + * @param {number} [endRow = this.rows-1] - Last row index + * @return {Matrix} + */ + subMatrixColumn(indices, startRow, endRow) { + if (startRow === undefined) startRow = 0; + if (endRow === undefined) endRow = this.rows - 1; + if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length); + for (var i = 0; i < indices.length; i++) { + for (var j = startRow; j <= endRow; j++) { + if (indices[i] < 0 || indices[i] >= this.columns) { + throw new RangeError('Column index out of range: ' + indices[i]); + } + newMatrix.set(j - startRow, i, this.get(j, indices[i])); + } + } + return newMatrix; + } + + /** + * Set a part of the matrix to the given sub-matrix + * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values. + * @param {number} startRow - The index of the first row to set + * @param {number} startColumn - The index of the first column to set + * @return {Matrix} + */ + setSubMatrix(matrix, startRow, startColumn) { + matrix = this.constructor.checkMatrix(matrix); + var endRow = startRow + matrix.rows - 1; + var endColumn = startColumn + matrix.columns - 1; + __WEBPACK_IMPORTED_MODULE_3__util__["h" /* checkRange */](this, startRow, endRow, startColumn, endColumn); + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + this[startRow + i][startColumn + j] = matrix.get(i, j); + } + } + return this; + } + + /** + * Return a new matrix based on a selection of rows and columns + * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once. + * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once. + * @return {Matrix} The new matrix + */ + selection(rowIndices, columnIndices) { + var indices = __WEBPACK_IMPORTED_MODULE_3__util__["i" /* checkIndices */](this, rowIndices, columnIndices); + var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length); + for (var i = 0; i < indices.row.length; i++) { + var rowIndex = indices.row[i]; + for (var j = 0; j < indices.column.length; j++) { + var columnIndex = indices.column[j]; + newMatrix[i][j] = this.get(rowIndex, columnIndex); + } + } + return newMatrix; + } + + /** + * Returns the trace of the matrix (sum of the diagonal elements) + * @return {number} + */ + trace() { + var min = Math.min(this.rows, this.columns); + var trace = 0; + for (var i = 0; i < min; i++) { + trace += this.get(i, i); + } + return trace; + } + + /* + Matrix views + */ + + /** + * Returns a view of the transposition of the matrix + * @return {MatrixTransposeView} + */ + transposeView() { + return new __WEBPACK_IMPORTED_MODULE_4__views_transpose__["a" /* default */](this); + } + + /** + * Returns a view of the row vector with the given index + * @param {number} row - row index of the vector + * @return {MatrixRowView} + */ + rowView(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + return new __WEBPACK_IMPORTED_MODULE_5__views_row__["a" /* default */](this, row); + } + + /** + * Returns a view of the column vector with the given index + * @param {number} column - column index of the vector + * @return {MatrixColumnView} + */ + columnView(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + return new __WEBPACK_IMPORTED_MODULE_8__views_column__["a" /* default */](this, column); + } + + /** + * Returns a view of the matrix flipped in the row axis + * @return {MatrixFlipRowView} + */ + flipRowView() { + return new __WEBPACK_IMPORTED_MODULE_9__views_flipRow__["a" /* default */](this); + } + + /** + * Returns a view of the matrix flipped in the column axis + * @return {MatrixFlipColumnView} + */ + flipColumnView() { + return new __WEBPACK_IMPORTED_MODULE_10__views_flipColumn__["a" /* default */](this); + } + + /** + * Returns a view of a submatrix giving the index boundaries + * @param {number} startRow - first row index of the submatrix + * @param {number} endRow - last row index of the submatrix + * @param {number} startColumn - first column index of the submatrix + * @param {number} endColumn - last column index of the submatrix + * @return {MatrixSubView} + */ + subMatrixView(startRow, endRow, startColumn, endColumn) { + return new __WEBPACK_IMPORTED_MODULE_6__views_sub__["a" /* default */](this, startRow, endRow, startColumn, endColumn); + } + + /** + * Returns a view of the cross of the row indices and the column indices + * @example + * // resulting vector is [[2], [2]] + * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1]) + * @param {Array} rowIndices + * @param {Array} columnIndices + * @return {MatrixSelectionView} + */ + selectionView(rowIndices, columnIndices) { + return new __WEBPACK_IMPORTED_MODULE_7__views_selection__["a" /* default */](this, rowIndices, columnIndices); + } + + + /** + * Calculates and returns the determinant of a matrix as a Number + * @example + * new Matrix([[1,2,3], [4,5,6]]).det() + * @return {number} + */ + det() { + if (this.isSquare()) { + var a, b, c, d; + if (this.columns === 2) { + // 2 x 2 matrix + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(1, 0); + d = this.get(1, 1); + + return a * d - (b * c); + } else if (this.columns === 3) { + // 3 x 3 matrix + var subMatrix0, subMatrix1, subMatrix2; + subMatrix0 = this.selectionView([1, 2], [1, 2]); + subMatrix1 = this.selectionView([1, 2], [0, 2]); + subMatrix2 = this.selectionView([1, 2], [0, 1]); + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(0, 2); + + return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det(); + } else { + // general purpose determinant using the LU decomposition + return new __WEBPACK_IMPORTED_MODULE_0__dc_lu__["a" /* default */](this).determinant; + } + + } else { + throw Error('Determinant can only be calculated for a square matrix.'); + } + } + + /** + * Returns inverse of a matrix if it exists or the pseudoinverse + * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15) + * @return {Matrix} the (pseudo)inverted matrix. + */ + pseudoInverse(threshold) { + if (threshold === undefined) threshold = Number.EPSILON; + var svdSolution = new __WEBPACK_IMPORTED_MODULE_1__dc_svd__["a" /* default */](this, {autoTranspose: true}); + + var U = svdSolution.leftSingularVectors; + var V = svdSolution.rightSingularVectors; + var s = svdSolution.diagonal; + + for (var i = 0; i < s.length; i++) { + if (Math.abs(s[i]) > threshold) { + s[i] = 1.0 / s[i]; + } else { + s[i] = 0.0; + } + } + + // convert list to diagonal + s = this.constructor[Symbol.species].diag(s); + return V.mmul(s.mmul(U.transposeView())); + } + } + + Matrix.prototype.klass = 'Matrix'; + + function compareNumbers(a, b) { + return a - b; + } + + /* + Synonyms + */ + + Matrix.random = Matrix.rand; + Matrix.diagonal = Matrix.diag; + Matrix.prototype.diagonal = Matrix.prototype.diag; + Matrix.identity = Matrix.eye; + Matrix.prototype.negate = Matrix.prototype.neg; + Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct; + Matrix.prototype.determinant = Matrix.prototype.det; + + /* + Add dynamically instance and static methods for mathematical operations + */ + + var inplaceOperator = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var inplaceOperatorScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% value); + } + } + return this; +}) +`; + + var inplaceOperatorMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); + } + } + return this; +}) +`; + + var staticOperator = ` +(function %name%(matrix, value) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(value); +}) +`; + + var inplaceMethod = ` +(function %name%() { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j))); + } + } + return this; +}) +`; + + var staticMethod = ` +(function %name%(matrix) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(); +}) +`; + + var inplaceMethodWithArgs = ` +(function %name%(%args%) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), %args%)); + } + } + return this; +}) +`; + + var staticMethodWithArgs = ` +(function %name%(matrix, %args%) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(%args%); +}) +`; + + + var inplaceMethodWithOneArgScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), value)); + } + } + return this; +}) +`; + var inplaceMethodWithOneArgMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); + } + } + return this; +}) +`; + + var inplaceMethodWithOneArg = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var staticMethodWithOneArg = staticMethodWithArgs; + + var operators = [ + // Arithmetic operators + ['+', 'add'], + ['-', 'sub', 'subtract'], + ['*', 'mul', 'multiply'], + ['/', 'div', 'divide'], + ['%', 'mod', 'modulus'], + // Bitwise operators + ['&', 'and'], + ['|', 'or'], + ['^', 'xor'], + ['<<', 'leftShift'], + ['>>', 'signPropagatingRightShift'], + ['>>>', 'rightShift', 'zeroFillRightShift'] + ]; + + var i; + var eval2 = eval; + for (var operator of operators) { + var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]})); + var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]})); + var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]})); + var staticOp = eval2(fillTemplateFunction(staticOperator, {name: operator[1]})); + for (i = 1; i < operator.length; i++) { + Matrix.prototype[operator[i]] = inplaceOp; + Matrix.prototype[operator[i] + 'S'] = inplaceOpS; + Matrix.prototype[operator[i] + 'M'] = inplaceOpM; + Matrix[operator[i]] = staticOp; + } + } + + 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]); + }); + + for (var method of methods) { + var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]})); + var staticMeth = eval2(fillTemplateFunction(staticMethod, {name: method[1]})); + for (i = 1; i < method.length; i++) { + Matrix.prototype[method[i]] = inplaceMeth; + Matrix[method[i]] = staticMeth; + } + } + + var methodsWithArgs = [ + ['Math.pow', 1, 'pow'] + ]; + + for (var methodWithArg of methodsWithArgs) { + var args = 'arg0'; + for (i = 1; i < methodWithArg[1]; i++) { + args += `, arg${i}`; + } + if (methodWithArg[1] !== 1) { + var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, { + name: methodWithArg[2], + method: methodWithArg[0], + args: args + })); + var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args})); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs; + Matrix[methodWithArg[i]] = staticMethWithArgs; + } + } else { + var tmplVar = { + name: methodWithArg[2], + args: args, + method: methodWithArg[0] + }; + var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar)); + var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar)); + var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar)); + var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar)); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethod2; + Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM; + Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS; + Matrix[methodWithArg[i]] = staticMethod2; + } + } + } + + function fillTemplateFunction(template, values) { + for (var value in values) { + template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]); + } + return template; + } + + return Matrix; +} + + +/***/ }), +/* 29 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(5); + + +// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs +function LuDecomposition(matrix) { + if (!(this instanceof LuDecomposition)) { + return new LuDecomposition(matrix); + } + + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + + var lu = matrix.clone(), + rows = lu.rows, + columns = lu.columns, + pivotVector = new Array(rows), + pivotSign = 1, + i, j, k, p, s, t, v, + LUrowi, LUcolj, kmax; + + for (i = 0; i < rows; i++) { + pivotVector[i] = i; + } + + LUcolj = new Array(rows); + + for (j = 0; j < columns; j++) { + + for (i = 0; i < rows; i++) { + LUcolj[i] = lu[i][j]; + } + + for (i = 0; i < rows; i++) { + LUrowi = lu[i]; + kmax = Math.min(i, j); + s = 0; + for (k = 0; k < kmax; k++) { + s += LUrowi[k] * LUcolj[k]; + } + LUrowi[j] = LUcolj[i] -= s; + } + + 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[p][k]; + lu[p][k] = lu[j][k]; + lu[j][k] = t; + } + + v = pivotVector[p]; + pivotVector[p] = pivotVector[j]; + pivotVector[j] = v; + + pivotSign = -pivotSign; + } + + if (j < rows && lu[j][j] !== 0) { + for (i = j + 1; i < rows; i++) { + lu[i][j] /= lu[j][j]; + } + } + } + + this.LU = lu; + this.pivotVector = pivotVector; + this.pivotSign = pivotSign; +} + +LuDecomposition.prototype = { + isSingular: function () { + var data = this.LU, + col = data.columns; + for (var j = 0; j < col; j++) { + if (data[j][j] === 0) { + return true; + } + } + return false; + }, + get determinant() { + var data = this.LU; + if (!data.isSquare()) { + throw new Error('Matrix must be square'); + } + var determinant = this.pivotSign, col = data.columns; + for (var j = 0; j < col; j++) { + determinant *= data[j][j]; + } + return determinant; + }, + get lowerTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i > j) { + X[i][j] = data[i][j]; + } else if (i === j) { + X[i][j] = 1; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get upperTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i <= j) { + X[i][j] = data[i][j]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get pivotPermutationVector() { + return this.pivotVector.slice(); + }, + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var lu = this.LU, + rows = lu.rows; + + if (rows !== value.rows) { + throw new Error('Invalid matrix dimensions'); + } + if (this.isSingular()) { + throw new Error('LU matrix is singular'); + } + + var count = value.columns; + var X = value.subMatrixRow(this.pivotVector, 0, count - 1); + var columns = lu.columns; + var i, j, k; + + for (k = 0; k < columns; k++) { + for (i = k + 1; i < columns; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + for (k = columns - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= lu[k][k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + return X; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (LuDecomposition); + + +/***/ }), +/* 30 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = hypotenuse; +/* unused harmony export getEmpty2DArray */ +/* harmony export (immutable) */ __webpack_exports__["b"] = getFilled2DArray; +function hypotenuse(a, b) { + var r; + if (Math.abs(a) > Math.abs(b)) { + r = b / a; + return Math.abs(a) * Math.sqrt(1 + r * r); + } + if (b !== 0) { + r = a / b; + return Math.abs(b) * Math.sqrt(1 + r * r); + } + return 0; +} + +// For use in the decomposition algorithms. With big matrices, access time is +// too long on elements from array subclass +// todo check when it is fixed in v8 +// http://jsperf.com/access-and-write-array-subclass +function getEmpty2DArray(rows, columns) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + } + return array; +} + +function getFilled2DArray(rows, columns, value) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + for (var j = 0; j < columns; j++) { + array[i][j] = value; + } + } + return array; +} + + +/***/ }), +/* 31 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = AbstractMatrix; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__dc_lu__ = __webpack_require__(32); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__dc_svd__ = __webpack_require__(70); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ml_array_utils__ = __webpack_require__(13); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ml_array_utils___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__views_transpose__ = __webpack_require__(227); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__views_row__ = __webpack_require__(224); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__views_sub__ = __webpack_require__(226); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__views_selection__ = __webpack_require__(225); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__views_column__ = __webpack_require__(221); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__views_flipRow__ = __webpack_require__(223); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__views_flipColumn__ = __webpack_require__(222); + + + + + + + + + + + + +function AbstractMatrix(superCtor) { + if (superCtor === undefined) superCtor = Object; + + /** + * Real matrix + * @class Matrix + * @param {number|Array|Matrix} nRows - Number of rows of the new matrix, + * 2D array containing the data or Matrix instance to clone + * @param {number} [nColumns] - Number of columns of the new matrix + */ + class Matrix extends superCtor { + static get [Symbol.species]() { + return this; + } + + /** + * Constructs a Matrix with the chosen dimensions from a 1D array + * @param {number} newRows - Number of rows + * @param {number} newColumns - Number of columns + * @param {Array} newData - A 1D array containing data for the matrix + * @return {Matrix} - The new matrix + */ + static from1DArray(newRows, newColumns, newData) { + var length = newRows * newColumns; + if (length !== newData.length) { + throw new RangeError('Data length does not match given dimensions'); + } + var newMatrix = new this(newRows, newColumns); + for (var row = 0; row < newRows; row++) { + for (var column = 0; column < newColumns; column++) { + newMatrix.set(row, column, newData[row * newColumns + column]); + } + } + return newMatrix; + } + + /** + * Creates a row vector, a matrix with only one row. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static rowVector(newData) { + var vector = new this(1, newData.length); + for (var i = 0; i < newData.length; i++) { + vector.set(0, i, newData[i]); + } + return vector; + } + + /** + * Creates a column vector, a matrix with only one column. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static columnVector(newData) { + var vector = new this(newData.length, 1); + for (var i = 0; i < newData.length; i++) { + vector.set(i, 0, newData[i]); + } + return vector; + } + + /** + * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns). + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static empty(rows, columns) { + return new this(rows, columns); + } + + /** + * Creates a matrix with the given dimensions. Values will be set to zero. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static zeros(rows, columns) { + return this.empty(rows, columns).fill(0); + } + + /** + * Creates a matrix with the given dimensions. Values will be set to one. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static ones(rows, columns) { + return this.empty(rows, columns).fill(1); + } + + /** + * Creates a matrix with the given dimensions. Values will be randomly set. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static rand(rows, columns, rng) { + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + matrix.set(i, j, rng()); + } + } + return matrix; + } + + /** + * Creates a matrix with the given dimensions. Values will be random integers. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {number} [maxValue=1000] - Maximum value + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static randInt(rows, columns, maxValue, rng) { + if (maxValue === undefined) maxValue = 1000; + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + var value = Math.floor(rng() * maxValue); + matrix.set(i, j, value); + } + } + return matrix; + } + + /** + * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0. + * @param {number} rows - Number of rows + * @param {number} [columns=rows] - Number of columns + * @param {number} [value=1] - Value to fill the diagonal with + * @return {Matrix} - The new identity matrix + */ + static eye(rows, columns, value) { + if (columns === undefined) columns = rows; + if (value === undefined) value = 1; + var min = Math.min(rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, value); + } + return matrix; + } + + /** + * Creates a diagonal matrix based on the given array. + * @param {Array} data - Array containing the data for the diagonal + * @param {number} [rows] - Number of rows (Default: data.length) + * @param {number} [columns] - Number of columns (Default: rows) + * @return {Matrix} - The new diagonal matrix + */ + static diag(data, rows, columns) { + var l = data.length; + if (rows === undefined) rows = l; + if (columns === undefined) columns = rows; + var min = Math.min(l, rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, data[i]); + } + return matrix; + } + + /** + * Returns a matrix whose elements are the minimum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static min(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } + + /** + * Returns a matrix whose elements are the maximum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static max(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } + + /** + * Check that the provided value is a Matrix and tries to instantiate one if not + * @param {*} value - The value to check + * @return {Matrix} + */ + static checkMatrix(value) { + return Matrix.isMatrix(value) ? value : new this(value); + } + + /** + * Returns true if the argument is a Matrix, false otherwise + * @param {*} value - The value to check + * @return {boolean} + */ + static isMatrix(value) { + return (value != null) && (value.klass === 'Matrix'); + } + + /** + * @prop {number} size - The number of elements in the matrix. + */ + get size() { + return this.rows * this.columns; + } + + /** + * Applies a callback for each element of the matrix. The function is called in the matrix (this) context. + * @param {function} callback - Function that will be called with two parameters : i (row) and j (column) + * @return {Matrix} this + */ + apply(callback) { + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); + } + var ii = this.rows; + var jj = this.columns; + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + callback.call(this, i, j); + } + } + return this; + } + + /** + * Returns a new 1D array filled row by row with the matrix values + * @return {Array} + */ + to1DArray() { + var array = new Array(this.size); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + array[i * this.columns + j] = this.get(i, j); + } + } + return array; + } + + /** + * Returns a 2D array containing a copy of the data + * @return {Array} + */ + to2DArray() { + var copy = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + copy[i] = new Array(this.columns); + for (var j = 0; j < this.columns; j++) { + copy[i][j] = this.get(i, j); + } + } + return copy; + } + + /** + * @return {boolean} true if the matrix has one row + */ + isRowVector() { + return this.rows === 1; + } + + /** + * @return {boolean} true if the matrix has one column + */ + isColumnVector() { + return this.columns === 1; + } + + /** + * @return {boolean} true if the matrix has one row or one column + */ + isVector() { + return (this.rows === 1) || (this.columns === 1); + } + + /** + * @return {boolean} true if the matrix has the same number of rows and columns + */ + isSquare() { + return this.rows === this.columns; + } + + /** + * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal + */ + isSymmetric() { + if (this.isSquare()) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j <= i; j++) { + if (this.get(i, j) !== this.get(j, i)) { + return false; + } + } + } + return true; + } + return false; + } + + /** + * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1 + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @param {number} value - The new value for the element + * @return {Matrix} this + */ + set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars + throw new Error('set method is unimplemented'); + } + + /** + * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4] + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @return {number} + */ + get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars + throw new Error('get method is unimplemented'); + } + + /** + * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of + * rows of the matrix, and colRep times the number of columns of the matrix + * @param {number} rowRep - Number of times the rows should be repeated + * @param {number} colRep - Number of times the columns should be re + * @return {Matrix} + * @example + * var matrix = new Matrix([[1,2]]); + * matrix.repeat(2); // [[1,2],[1,2]] + */ + repeat(rowRep, colRep) { + rowRep = rowRep || 1; + colRep = colRep || 1; + var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep); + for (var i = 0; i < rowRep; i++) { + for (var j = 0; j < colRep; j++) { + matrix.setSubMatrix(this, this.rows * i, this.columns * j); + } + } + return matrix; + } + + /** + * Fills the matrix with a given value. All elements will be set to this value. + * @param {number} value - New value + * @return {Matrix} this + */ + fill(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, value); + } + } + return this; + } + + /** + * Negates the matrix. All elements will be multiplied by (-1) + * @return {Matrix} this + */ + neg() { + return this.mulS(-1); + } + + /** + * Returns a new array from the given row index + * @param {number} index - Row index + * @return {Array} + */ + getRow(index) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + var row = new Array(this.columns); + for (var i = 0; i < this.columns; i++) { + row[i] = this.get(index, i); + } + return row; + } + + /** + * Returns a new row vector from the given row index + * @param {number} index - Row index + * @return {Matrix} + */ + getRowVector(index) { + return this.constructor.rowVector(this.getRow(index)); + } + + /** + * Sets a row at the given index + * @param {number} index - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setRow(index, array) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + array = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, array); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, array[i]); + } + return this; + } + + /** + * Swaps two rows + * @param {number} row1 - First row index + * @param {number} row2 - Second row index + * @return {Matrix} this + */ + swapRows(row1, row2) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row1); + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row2); + for (var i = 0; i < this.columns; i++) { + var temp = this.get(row1, i); + this.set(row1, i, this.get(row2, i)); + this.set(row2, i, temp); + } + return this; + } + + /** + * Returns a new array from the given column index + * @param {number} index - Column index + * @return {Array} + */ + getColumn(index) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + var column = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + column[i] = this.get(i, index); + } + return column; + } + + /** + * Returns a new column vector from the given column index + * @param {number} index - Column index + * @return {Matrix} + */ + getColumnVector(index) { + return this.constructor.columnVector(this.getColumn(index)); + } + + /** + * Sets a column at the given index + * @param {number} index - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setColumn(index, array) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + array = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, array); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, array[i]); + } + return this; + } + + /** + * Swaps two columns + * @param {number} column1 - First column index + * @param {number} column2 - Second column index + * @return {Matrix} this + */ + swapColumns(column1, column2) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column1); + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column2); + for (var i = 0; i < this.rows; i++) { + var temp = this.get(i, column1); + this.set(i, column1, this.get(i, column2)); + this.set(i, column2, temp); + } + return this; + } + + /** + * Adds the values of a vector to each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[j]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[j]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[j]); + } + } + return this; + } + + /** + * Divides the values of each row by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[j]); + } + } + return this; + } + + /** + * Adds the values of a vector to each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[i]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[i]); + } + } + return this; + } + + /** + * Divides the values of each column by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a row with a scalar + * @param {number} index - Row index + * @param {number} value + * @return {Matrix} this + */ + mulRow(index, value) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, this.get(index, i) * value); + } + return this; + } + + /** + * Multiplies the values of a column with a scalar + * @param {number} index - Column index + * @param {number} value + * @return {Matrix} this + */ + mulColumn(index, value) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, this.get(i, index) * value); + } + return this; + } + + /** + * Returns the maximum value of the matrix + * @return {number} + */ + max() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the maximum value + * @return {Array} + */ + maxIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the minimum value of the matrix + * @return {number} + */ + min() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the minimum value + * @return {Array} + */ + minIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the maximum value of one row + * @param {number} row - Row index + * @return {number} + */ + maxRow(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + maxRowIndex(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one row + * @param {number} row - Row index + * @return {number} + */ + minRow(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + minRowIndex(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the maximum value of one column + * @param {number} column - Column index + * @return {number} + */ + maxColumn(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one column + * @param {number} column - Column index + * @return {Array} + */ + maxColumnIndex(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one column + * @param {number} column - Column index + * @return {number} + */ + minColumn(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the minimum value of one column + * @param {number} column - Column index + * @return {Array} + */ + minColumnIndex(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns an array containing the diagonal values of the matrix + * @return {Array} + */ + diag() { + var min = Math.min(this.rows, this.columns); + var diag = new Array(min); + for (var i = 0; i < min; i++) { + diag[i] = this.get(i, i); + } + return diag; + } + + /** + * Returns the sum by the argument given, if no argument given, + * it returns the sum of all elements of the matrix. + * @param {string} by - sum by 'row' or 'column'. + * @return {Matrix|number} + */ + sum(by) { + switch (by) { + case 'row': + return __WEBPACK_IMPORTED_MODULE_3__util__["e" /* sumByRow */](this); + case 'column': + return __WEBPACK_IMPORTED_MODULE_3__util__["f" /* sumByColumn */](this); + default: + return __WEBPACK_IMPORTED_MODULE_3__util__["g" /* sumAll */](this); + } + } + + /** + * Returns the mean of all elements of the matrix + * @return {number} + */ + mean() { + return this.sum() / this.size; + } + + /** + * Returns the product of all elements of the matrix + * @return {number} + */ + prod() { + var prod = 1; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + prod *= this.get(i, j); + } + } + return prod; + } + + /** + * Computes the cumulative sum of the matrix elements (in place, row by row) + * @return {Matrix} this + */ + cumulativeSum() { + var sum = 0; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + sum += this.get(i, j); + this.set(i, j, sum); + } + } + return this; + } + + /** + * Computes the dot (scalar) product between the matrix and another + * @param {Matrix} vector2 vector + * @return {number} + */ + dot(vector2) { + if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); + var vector1 = this.to1DArray(); + if (vector1.length !== vector2.length) { + throw new RangeError('vectors do not have the same size'); + } + var dot = 0; + for (var i = 0; i < vector1.length; i++) { + dot += vector1[i] * vector2[i]; + } + return dot; + } + + /** + * Returns the matrix product between this and other + * @param {Matrix} other + * @return {Matrix} + */ + mmul(other) { + other = this.constructor.checkMatrix(other); + if (this.columns !== other.rows) { + // eslint-disable-next-line no-console + console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); + } + + var m = this.rows; + var n = this.columns; + var p = other.columns; + + var result = new this.constructor[Symbol.species](m, p); + + var Bcolj = new Array(n); + for (var j = 0; j < p; j++) { + for (var k = 0; k < n; k++) { + Bcolj[k] = other.get(k, j); + } + + for (var i = 0; i < m; i++) { + var s = 0; + for (k = 0; k < n; k++) { + s += this.get(i, k) * Bcolj[k]; + } + + result.set(i, j, s); + } + } + return result; + } + + strassen2x2(other) { + var result = new this.constructor[Symbol.species](2, 2); + const a11 = this.get(0, 0); + const b11 = other.get(0, 0); + const a12 = this.get(0, 1); + const b12 = other.get(0, 1); + const a21 = this.get(1, 0); + const b21 = other.get(1, 0); + const a22 = this.get(1, 1); + const b22 = other.get(1, 1); + + // Compute intermediate values. + const m1 = (a11 + a22) * (b11 + b22); + const m2 = (a21 + a22) * b11; + const m3 = a11 * (b12 - b22); + const m4 = a22 * (b21 - b11); + const m5 = (a11 + a12) * b22; + const m6 = (a21 - a11) * (b11 + b12); + const m7 = (a12 - a22) * (b21 + b22); + + // Combine intermediate values into the output. + const c00 = m1 + m4 - m5 + m7; + const c01 = m3 + m5; + const c10 = m2 + m4; + const c11 = m1 - m2 + m3 + m6; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(1, 0, c10); + result.set(1, 1, c11); + return result; + } + + strassen3x3(other) { + var result = new this.constructor[Symbol.species](3, 3); + + const a00 = this.get(0, 0); + const a01 = this.get(0, 1); + const a02 = this.get(0, 2); + const a10 = this.get(1, 0); + const a11 = this.get(1, 1); + const a12 = this.get(1, 2); + const a20 = this.get(2, 0); + const a21 = this.get(2, 1); + const a22 = this.get(2, 2); + + const b00 = other.get(0, 0); + const b01 = other.get(0, 1); + const b02 = other.get(0, 2); + const b10 = other.get(1, 0); + const b11 = other.get(1, 1); + const b12 = other.get(1, 2); + const b20 = other.get(2, 0); + const b21 = other.get(2, 1); + const b22 = other.get(2, 2); + + const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11; + const m2 = (a00 - a10) * (-b01 + b11); + const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22); + const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11); + const m5 = (a10 + a11) * (-b00 + b01); + const m6 = a00 * b00; + const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12); + const m8 = (-a00 + a20) * (b02 - b12); + const m9 = (a20 + a21) * (-b00 + b02); + const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12; + const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21); + const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21); + const m13 = (a02 - a22) * (b11 - b21); + const m14 = a02 * b20; + const m15 = (a21 + a22) * (-b20 + b21); + const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22); + const m17 = (a02 - a12) * (b12 - b22); + const m18 = (a11 + a12) * (-b20 + b22); + const m19 = a01 * b10; + const m20 = a12 * b21; + const m21 = a10 * b02; + const m22 = a20 * b01; + const m23 = a22 * b22; + + const c00 = m6 + m14 + m19; + const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15; + const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18; + const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17; + const c11 = m2 + m4 + m5 + m6 + m20; + const c12 = m14 + m16 + m17 + m18 + m21; + const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14; + const c21 = m12 + m13 + m14 + m15 + m22; + const c22 = m6 + m7 + m8 + m9 + m23; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(0, 2, c02); + result.set(1, 0, c10); + result.set(1, 1, c11); + result.set(1, 2, c12); + result.set(2, 0, c20); + result.set(2, 1, c21); + result.set(2, 2, c22); + return result; + } + + /** + * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000. + * @param {Matrix} y + * @return {Matrix} + */ + mmulStrassen(y) { + var x = this.clone(); + var r1 = x.rows; + var c1 = x.columns; + var r2 = y.rows; + var c2 = y.columns; + if (c1 !== r2) { + // eslint-disable-next-line no-console + console.warn(`Multiplying ${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. + function embed(mat, rows, cols) { + var r = mat.rows; + var c = mat.columns; + if ((r === rows) && (c === cols)) { + return mat; + } else { + var resultat = Matrix.zeros(rows, cols); + resultat = resultat.setSubMatrix(mat, 0, 0); + return resultat; + } + } + + + // Make sure both matrices are the same size. + // This is exclusively for simplicity: + // this algorithm can be implemented with matrices of different sizes. + + var r = Math.max(r1, r2); + var c = Math.max(c1, c2); + x = embed(x, r, c); + y = embed(y, r, c); + + // Our recursive multiplication function. + function blockMult(a, b, rows, cols) { + // For small matrices, resort to naive multiplication. + if (rows <= 512 || cols <= 512) { + return a.mmul(b); // a is equivalent to this + } + + // Apply dynamic padding. + if ((rows % 2 === 1) && (cols % 2 === 1)) { + a = embed(a, rows + 1, cols + 1); + b = embed(b, rows + 1, cols + 1); + } else if (rows % 2 === 1) { + a = embed(a, rows + 1, cols); + b = embed(b, rows + 1, cols); + } else if (cols % 2 === 1) { + a = embed(a, rows, cols + 1); + b = embed(b, rows, cols + 1); + } + + var halfRows = parseInt(a.rows / 2); + var halfCols = parseInt(a.columns / 2); + // Subdivide input matrices. + var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); + var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); + + var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); + var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); + + var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); + var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); + + var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); + var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); + + // Compute intermediate values. + var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols); + var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols); + var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols); + var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols); + var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols); + var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols); + var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); + + // Combine intermediate values into the output. + var c11 = Matrix.add(m1, m4); + c11.sub(m5); + c11.add(m7); + var c12 = Matrix.add(m3, m5); + var c21 = Matrix.add(m2, m4); + var c22 = Matrix.sub(m1, m2); + c22.add(m3); + c22.add(m6); + + //Crop output to the desired size (undo dynamic padding). + var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns); + resultat = resultat.setSubMatrix(c11, 0, 0); + resultat = resultat.setSubMatrix(c12, c11.rows, 0); + resultat = resultat.setSubMatrix(c21, 0, c11.columns); + resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns); + return resultat.subMatrix(0, rows - 1, 0, cols - 1); + } + return blockMult(x, y, r, c); + } + + /** + * Returns a row-by-row scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The scaled matrix + */ + scaleRows(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.rows; i++) { + var scaled = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__["scale"])(this.getRow(i), {min, max}); + newMatrix.setRow(i, scaled); + } + return newMatrix; + } + + /** + * Returns a new column-by-column scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The new scaled matrix + * @example + * var matrix = new Matrix([[1,2],[-1,0]]); + * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]] + */ + scaleColumns(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.columns; i++) { + var scaled = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__["scale"])(this.getColumn(i), { + min: min, + max: max + }); + newMatrix.setColumn(i, scaled); + } + return newMatrix; + } + + + /** + * Returns the Kronecker product (also known as tensor product) between this and other + * See https://en.wikipedia.org/wiki/Kronecker_product + * @param {Matrix} other + * @return {Matrix} + */ + kroneckerProduct(other) { + other = this.constructor.checkMatrix(other); + + var m = this.rows; + var n = this.columns; + var p = other.rows; + var q = other.columns; + + var result = new this.constructor[Symbol.species](m * p, n * q); + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + for (var k = 0; k < p; k++) { + for (var l = 0; l < q; l++) { + result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l); + } + } + } + } + return result; + } + + /** + * Transposes the matrix and returns a new one containing the result + * @return {Matrix} + */ + transpose() { + var result = new this.constructor[Symbol.species](this.columns, this.rows); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + result.set(j, i, this.get(i, j)); + } + } + return result; + } + + /** + * Sorts the rows (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortRows(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.rows; i++) { + this.setRow(i, this.getRow(i).sort(compareFunction)); + } + return this; + } + + /** + * Sorts the columns (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortColumns(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.columns; i++) { + this.setColumn(i, this.getColumn(i).sort(compareFunction)); + } + return this; + } + + /** + * Returns a subset of the matrix + * @param {number} startRow - First row index + * @param {number} endRow - Last row index + * @param {number} startColumn - First column index + * @param {number} endColumn - Last column index + * @return {Matrix} + */ + subMatrix(startRow, endRow, startColumn, endColumn) { + __WEBPACK_IMPORTED_MODULE_3__util__["h" /* checkRange */](this, startRow, endRow, startColumn, endColumn); + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1); + for (var i = startRow; i <= endRow; i++) { + for (var j = startColumn; j <= endColumn; j++) { + newMatrix[i - startRow][j - startColumn] = this.get(i, j); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of row indices + * @param {Array} indices - Array containing the row indices + * @param {number} [startColumn = 0] - First column index + * @param {number} [endColumn = this.columns-1] - Last column index + * @return {Matrix} + */ + subMatrixRow(indices, startColumn, endColumn) { + if (startColumn === undefined) startColumn = 0; + if (endColumn === undefined) endColumn = this.columns - 1; + if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1); + for (var i = 0; i < indices.length; i++) { + for (var j = startColumn; j <= endColumn; j++) { + if (indices[i] < 0 || indices[i] >= this.rows) { + throw new RangeError('Row index out of range: ' + indices[i]); + } + newMatrix.set(i, j - startColumn, this.get(indices[i], j)); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of column indices + * @param {Array} indices - Array containing the column indices + * @param {number} [startRow = 0] - First row index + * @param {number} [endRow = this.rows-1] - Last row index + * @return {Matrix} + */ + subMatrixColumn(indices, startRow, endRow) { + if (startRow === undefined) startRow = 0; + if (endRow === undefined) endRow = this.rows - 1; + if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length); + for (var i = 0; i < indices.length; i++) { + for (var j = startRow; j <= endRow; j++) { + if (indices[i] < 0 || indices[i] >= this.columns) { + throw new RangeError('Column index out of range: ' + indices[i]); + } + newMatrix.set(j - startRow, i, this.get(j, indices[i])); + } + } + return newMatrix; + } + + /** + * Set a part of the matrix to the given sub-matrix + * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values. + * @param {number} startRow - The index of the first row to set + * @param {number} startColumn - The index of the first column to set + * @return {Matrix} + */ + setSubMatrix(matrix, startRow, startColumn) { + matrix = this.constructor.checkMatrix(matrix); + var endRow = startRow + matrix.rows - 1; + var endColumn = startColumn + matrix.columns - 1; + __WEBPACK_IMPORTED_MODULE_3__util__["h" /* checkRange */](this, startRow, endRow, startColumn, endColumn); + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + this[startRow + i][startColumn + j] = matrix.get(i, j); + } + } + return this; + } + + /** + * Return a new matrix based on a selection of rows and columns + * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once. + * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once. + * @return {Matrix} The new matrix + */ + selection(rowIndices, columnIndices) { + var indices = __WEBPACK_IMPORTED_MODULE_3__util__["i" /* checkIndices */](this, rowIndices, columnIndices); + var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length); + for (var i = 0; i < indices.row.length; i++) { + var rowIndex = indices.row[i]; + for (var j = 0; j < indices.column.length; j++) { + var columnIndex = indices.column[j]; + newMatrix[i][j] = this.get(rowIndex, columnIndex); + } + } + return newMatrix; + } + + /** + * Returns the trace of the matrix (sum of the diagonal elements) + * @return {number} + */ + trace() { + var min = Math.min(this.rows, this.columns); + var trace = 0; + for (var i = 0; i < min; i++) { + trace += this.get(i, i); + } + return trace; + } + + /* + Matrix views + */ + + /** + * Returns a view of the transposition of the matrix + * @return {MatrixTransposeView} + */ + transposeView() { + return new __WEBPACK_IMPORTED_MODULE_4__views_transpose__["a" /* default */](this); + } + + /** + * Returns a view of the row vector with the given index + * @param {number} row - row index of the vector + * @return {MatrixRowView} + */ + rowView(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + return new __WEBPACK_IMPORTED_MODULE_5__views_row__["a" /* default */](this, row); + } + + /** + * Returns a view of the column vector with the given index + * @param {number} column - column index of the vector + * @return {MatrixColumnView} + */ + columnView(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + return new __WEBPACK_IMPORTED_MODULE_8__views_column__["a" /* default */](this, column); + } + + /** + * Returns a view of the matrix flipped in the row axis + * @return {MatrixFlipRowView} + */ + flipRowView() { + return new __WEBPACK_IMPORTED_MODULE_9__views_flipRow__["a" /* default */](this); + } + + /** + * Returns a view of the matrix flipped in the column axis + * @return {MatrixFlipColumnView} + */ + flipColumnView() { + return new __WEBPACK_IMPORTED_MODULE_10__views_flipColumn__["a" /* default */](this); + } + + /** + * Returns a view of a submatrix giving the index boundaries + * @param {number} startRow - first row index of the submatrix + * @param {number} endRow - last row index of the submatrix + * @param {number} startColumn - first column index of the submatrix + * @param {number} endColumn - last column index of the submatrix + * @return {MatrixSubView} + */ + subMatrixView(startRow, endRow, startColumn, endColumn) { + return new __WEBPACK_IMPORTED_MODULE_6__views_sub__["a" /* default */](this, startRow, endRow, startColumn, endColumn); + } + + /** + * Returns a view of the cross of the row indices and the column indices + * @example + * // resulting vector is [[2], [2]] + * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1]) + * @param {Array} rowIndices + * @param {Array} columnIndices + * @return {MatrixSelectionView} + */ + selectionView(rowIndices, columnIndices) { + return new __WEBPACK_IMPORTED_MODULE_7__views_selection__["a" /* default */](this, rowIndices, columnIndices); + } + + + /** + * Calculates and returns the determinant of a matrix as a Number + * @example + * new Matrix([[1,2,3], [4,5,6]]).det() + * @return {number} + */ + det() { + if (this.isSquare()) { + var a, b, c, d; + if (this.columns === 2) { + // 2 x 2 matrix + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(1, 0); + d = this.get(1, 1); + + return a * d - (b * c); + } else if (this.columns === 3) { + // 3 x 3 matrix + var subMatrix0, subMatrix1, subMatrix2; + subMatrix0 = this.selectionView([1, 2], [1, 2]); + subMatrix1 = this.selectionView([1, 2], [0, 2]); + subMatrix2 = this.selectionView([1, 2], [0, 1]); + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(0, 2); + + return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det(); + } else { + // general purpose determinant using the LU decomposition + return new __WEBPACK_IMPORTED_MODULE_0__dc_lu__["a" /* default */](this).determinant; + } + + } else { + throw Error('Determinant can only be calculated for a square matrix.'); + } + } + + /** + * Returns inverse of a matrix if it exists or the pseudoinverse + * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15) + * @return {Matrix} the (pseudo)inverted matrix. + */ + pseudoInverse(threshold) { + if (threshold === undefined) threshold = Number.EPSILON; + var svdSolution = new __WEBPACK_IMPORTED_MODULE_1__dc_svd__["a" /* default */](this, {autoTranspose: true}); + + var U = svdSolution.leftSingularVectors; + var V = svdSolution.rightSingularVectors; + var s = svdSolution.diagonal; + + for (var i = 0; i < s.length; i++) { + if (Math.abs(s[i]) > threshold) { + s[i] = 1.0 / s[i]; + } else { + s[i] = 0.0; + } + } + + // convert list to diagonal + s = this.constructor[Symbol.species].diag(s); + return V.mmul(s.mmul(U.transposeView())); + } + } + + Matrix.prototype.klass = 'Matrix'; + + function compareNumbers(a, b) { + return a - b; + } + + /* + Synonyms + */ + + Matrix.random = Matrix.rand; + Matrix.diagonal = Matrix.diag; + Matrix.prototype.diagonal = Matrix.prototype.diag; + Matrix.identity = Matrix.eye; + Matrix.prototype.negate = Matrix.prototype.neg; + Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct; + Matrix.prototype.determinant = Matrix.prototype.det; + + /* + Add dynamically instance and static methods for mathematical operations + */ + + var inplaceOperator = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var inplaceOperatorScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% value); + } + } + return this; +}) +`; + + var inplaceOperatorMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); + } + } + return this; +}) +`; + + var staticOperator = ` +(function %name%(matrix, value) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(value); +}) +`; + + var inplaceMethod = ` +(function %name%() { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j))); + } + } + return this; +}) +`; + + var staticMethod = ` +(function %name%(matrix) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(); +}) +`; + + var inplaceMethodWithArgs = ` +(function %name%(%args%) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), %args%)); + } + } + return this; +}) +`; + + var staticMethodWithArgs = ` +(function %name%(matrix, %args%) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(%args%); +}) +`; + + + var inplaceMethodWithOneArgScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), value)); + } + } + return this; +}) +`; + var inplaceMethodWithOneArgMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); + } + } + return this; +}) +`; + + var inplaceMethodWithOneArg = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var staticMethodWithOneArg = staticMethodWithArgs; + + var operators = [ + // Arithmetic operators + ['+', 'add'], + ['-', 'sub', 'subtract'], + ['*', 'mul', 'multiply'], + ['/', 'div', 'divide'], + ['%', 'mod', 'modulus'], + // Bitwise operators + ['&', 'and'], + ['|', 'or'], + ['^', 'xor'], + ['<<', 'leftShift'], + ['>>', 'signPropagatingRightShift'], + ['>>>', 'rightShift', 'zeroFillRightShift'] + ]; + + var i; + var eval2 = eval; + for (var operator of operators) { + var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]})); + var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]})); + var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]})); + var staticOp = eval2(fillTemplateFunction(staticOperator, {name: operator[1]})); + for (i = 1; i < operator.length; i++) { + Matrix.prototype[operator[i]] = inplaceOp; + Matrix.prototype[operator[i] + 'S'] = inplaceOpS; + Matrix.prototype[operator[i] + 'M'] = inplaceOpM; + Matrix[operator[i]] = staticOp; + } + } + + 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]); + }); + + for (var method of methods) { + var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]})); + var staticMeth = eval2(fillTemplateFunction(staticMethod, {name: method[1]})); + for (i = 1; i < method.length; i++) { + Matrix.prototype[method[i]] = inplaceMeth; + Matrix[method[i]] = staticMeth; + } + } + + var methodsWithArgs = [ + ['Math.pow', 1, 'pow'] + ]; + + for (var methodWithArg of methodsWithArgs) { + var args = 'arg0'; + for (i = 1; i < methodWithArg[1]; i++) { + args += `, arg${i}`; + } + if (methodWithArg[1] !== 1) { + var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, { + name: methodWithArg[2], + method: methodWithArg[0], + args: args + })); + var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args})); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs; + Matrix[methodWithArg[i]] = staticMethWithArgs; + } + } else { + var tmplVar = { + name: methodWithArg[2], + args: args, + method: methodWithArg[0] + }; + var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar)); + var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar)); + var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar)); + var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar)); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethod2; + Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM; + Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS; + Matrix[methodWithArg[i]] = staticMethod2; + } + } + } + + function fillTemplateFunction(template, values) { + for (var value in values) { + template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]); + } + return template; + } + + return Matrix; +} + + +/***/ }), +/* 32 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(6); + + +// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs +function LuDecomposition(matrix) { + if (!(this instanceof LuDecomposition)) { + return new LuDecomposition(matrix); + } + + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + + var lu = matrix.clone(), + rows = lu.rows, + columns = lu.columns, + pivotVector = new Array(rows), + pivotSign = 1, + i, j, k, p, s, t, v, + LUrowi, LUcolj, kmax; + + for (i = 0; i < rows; i++) { + pivotVector[i] = i; + } + + LUcolj = new Array(rows); + + for (j = 0; j < columns; j++) { + + for (i = 0; i < rows; i++) { + LUcolj[i] = lu[i][j]; + } + + for (i = 0; i < rows; i++) { + LUrowi = lu[i]; + kmax = Math.min(i, j); + s = 0; + for (k = 0; k < kmax; k++) { + s += LUrowi[k] * LUcolj[k]; + } + LUrowi[j] = LUcolj[i] -= s; + } + + 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[p][k]; + lu[p][k] = lu[j][k]; + lu[j][k] = t; + } + + v = pivotVector[p]; + pivotVector[p] = pivotVector[j]; + pivotVector[j] = v; + + pivotSign = -pivotSign; + } + + if (j < rows && lu[j][j] !== 0) { + for (i = j + 1; i < rows; i++) { + lu[i][j] /= lu[j][j]; + } + } + } + + this.LU = lu; + this.pivotVector = pivotVector; + this.pivotSign = pivotSign; +} + +LuDecomposition.prototype = { + isSingular: function () { + var data = this.LU, + col = data.columns; + for (var j = 0; j < col; j++) { + if (data[j][j] === 0) { + return true; + } + } + return false; + }, + get determinant() { + var data = this.LU; + if (!data.isSquare()) { + throw new Error('Matrix must be square'); + } + var determinant = this.pivotSign, col = data.columns; + for (var j = 0; j < col; j++) { + determinant *= data[j][j]; + } + return determinant; + }, + get lowerTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i > j) { + X[i][j] = data[i][j]; + } else if (i === j) { + X[i][j] = 1; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get upperTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i <= j) { + X[i][j] = data[i][j]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get pivotPermutationVector() { + return this.pivotVector.slice(); + }, + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var lu = this.LU, + rows = lu.rows; + + if (rows !== value.rows) { + throw new Error('Invalid matrix dimensions'); + } + if (this.isSingular()) { + throw new Error('LU matrix is singular'); + } + + var count = value.columns; + var X = value.subMatrixRow(this.pivotVector, 0, count - 1); + var columns = lu.columns; + var i, j, k; + + for (k = 0; k < columns; k++) { + for (i = k + 1; i < columns; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + for (k = columns - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= lu[k][k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + return X; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (LuDecomposition); + + +/***/ }), +/* 33 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = hypotenuse; +/* unused harmony export getEmpty2DArray */ +/* harmony export (immutable) */ __webpack_exports__["b"] = getFilled2DArray; +function hypotenuse(a, b) { + var r; + if (Math.abs(a) > Math.abs(b)) { + r = b / a; + return Math.abs(a) * Math.sqrt(1 + r * r); + } + if (b !== 0) { + r = a / b; + return Math.abs(b) * Math.sqrt(1 + r * r); + } + return 0; +} + +// For use in the decomposition algorithms. With big matrices, access time is +// too long on elements from array subclass +// todo check when it is fixed in v8 +// http://jsperf.com/access-and-write-array-subclass +function getEmpty2DArray(rows, columns) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + } + return array; +} + +function getFilled2DArray(rows, columns, value) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + for (var j = 0; j < columns; j++) { + array[i][j] = value; + } + } + return array; +} + + +/***/ }), +/* 34 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__ = __webpack_require__(14); + + +class SimpleLinearRegression extends __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["a" /* default */] { + constructor(x, y) { + super(); + if (x === true) { + this.slope = y.slope; + this.intercept = y.intercept; + this.coefficients = [y.intercept, y.slope]; + } else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["b" /* checkArrayLength */])(x, y); + regress(this, x, y); + } + } + + toJSON() { + return { + name: 'simpleLinearRegression', + slope: this.slope, + intercept: this.intercept + }; + } + + _predict(x) { + return this.slope * x + this.intercept; + } + + computeX(y) { + return (y - this.intercept) / this.slope; + } + + toString(precision) { + let result = 'f(x) = '; + if (this.slope !== 0) { + const xFactor = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.slope, precision); + result += (xFactor === '1' ? '' : xFactor + ' * ') + 'x'; + if (this.intercept) { + const absIntercept = Math.abs(this.intercept); + const operator = absIntercept === this.intercept ? '+' : '-'; + result += ` ${operator} ${__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(absIntercept, precision)}`; + } + } else { + result += __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.intercept, precision); + } + return result; + } + + toLaTeX(precision) { + return this.toString(precision); + } + + static load(json) { + if (json.name !== 'simpleLinearRegression') { + throw new TypeError('not a SLR model'); + } + return new SimpleLinearRegression(true, json); + } +} +/* harmony export (immutable) */ __webpack_exports__["default"] = SimpleLinearRegression; + + +function regress(slr, x, y) { + const n = x.length; + let xSum = 0; + let ySum = 0; + + let xSquared = 0; + let xY = 0; + + for (let i = 0; i < n; i++) { + xSum += x[i]; + ySum += y[i]; + xSquared += x[i] * x[i]; + xY += x[i] * y[i]; + } + + 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]; +} + + +/***/ }), +/* 35 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = AbstractMatrix; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__dc_lu__ = __webpack_require__(36); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__dc_svd__ = __webpack_require__(72); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ml_array_utils__ = __webpack_require__(13); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ml_array_utils___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(19); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__views_transpose__ = __webpack_require__(240); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__views_row__ = __webpack_require__(237); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__views_sub__ = __webpack_require__(239); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__views_selection__ = __webpack_require__(238); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__views_column__ = __webpack_require__(234); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__views_flipRow__ = __webpack_require__(236); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__views_flipColumn__ = __webpack_require__(235); + + + + + + + + + + + + +function AbstractMatrix(superCtor) { + if (superCtor === undefined) superCtor = Object; + + /** + * Real matrix + * @class Matrix + * @param {number|Array|Matrix} nRows - Number of rows of the new matrix, + * 2D array containing the data or Matrix instance to clone + * @param {number} [nColumns] - Number of columns of the new matrix + */ + class Matrix extends superCtor { + static get [Symbol.species]() { + return this; + } + + /** + * Constructs a Matrix with the chosen dimensions from a 1D array + * @param {number} newRows - Number of rows + * @param {number} newColumns - Number of columns + * @param {Array} newData - A 1D array containing data for the matrix + * @return {Matrix} - The new matrix + */ + static from1DArray(newRows, newColumns, newData) { + var length = newRows * newColumns; + if (length !== newData.length) { + throw new RangeError('Data length does not match given dimensions'); + } + var newMatrix = new this(newRows, newColumns); + for (var row = 0; row < newRows; row++) { + for (var column = 0; column < newColumns; column++) { + newMatrix.set(row, column, newData[row * newColumns + column]); + } + } + return newMatrix; + } + + /** + * Creates a row vector, a matrix with only one row. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static rowVector(newData) { + var vector = new this(1, newData.length); + for (var i = 0; i < newData.length; i++) { + vector.set(0, i, newData[i]); + } + return vector; + } + + /** + * Creates a column vector, a matrix with only one column. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static columnVector(newData) { + var vector = new this(newData.length, 1); + for (var i = 0; i < newData.length; i++) { + vector.set(i, 0, newData[i]); + } + return vector; + } + + /** + * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns). + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static empty(rows, columns) { + return new this(rows, columns); + } + + /** + * Creates a matrix with the given dimensions. Values will be set to zero. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static zeros(rows, columns) { + return this.empty(rows, columns).fill(0); + } + + /** + * Creates a matrix with the given dimensions. Values will be set to one. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static ones(rows, columns) { + return this.empty(rows, columns).fill(1); + } + + /** + * Creates a matrix with the given dimensions. Values will be randomly set. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static rand(rows, columns, rng) { + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + matrix.set(i, j, rng()); + } + } + return matrix; + } + + /** + * Creates a matrix with the given dimensions. Values will be random integers. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {number} [maxValue=1000] - Maximum value + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static randInt(rows, columns, maxValue, rng) { + if (maxValue === undefined) maxValue = 1000; + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + var value = Math.floor(rng() * maxValue); + matrix.set(i, j, value); + } + } + return matrix; + } + + /** + * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0. + * @param {number} rows - Number of rows + * @param {number} [columns=rows] - Number of columns + * @param {number} [value=1] - Value to fill the diagonal with + * @return {Matrix} - The new identity matrix + */ + static eye(rows, columns, value) { + if (columns === undefined) columns = rows; + if (value === undefined) value = 1; + var min = Math.min(rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, value); + } + return matrix; + } + + /** + * Creates a diagonal matrix based on the given array. + * @param {Array} data - Array containing the data for the diagonal + * @param {number} [rows] - Number of rows (Default: data.length) + * @param {number} [columns] - Number of columns (Default: rows) + * @return {Matrix} - The new diagonal matrix + */ + static diag(data, rows, columns) { + var l = data.length; + if (rows === undefined) rows = l; + if (columns === undefined) columns = rows; + var min = Math.min(l, rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, data[i]); + } + return matrix; + } + + /** + * Returns a matrix whose elements are the minimum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static min(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } + + /** + * Returns a matrix whose elements are the maximum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static max(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } + + /** + * Check that the provided value is a Matrix and tries to instantiate one if not + * @param {*} value - The value to check + * @return {Matrix} + */ + static checkMatrix(value) { + return Matrix.isMatrix(value) ? value : new this(value); + } + + /** + * Returns true if the argument is a Matrix, false otherwise + * @param {*} value - The value to check + * @return {boolean} + */ + static isMatrix(value) { + return (value != null) && (value.klass === 'Matrix'); + } + + /** + * @prop {number} size - The number of elements in the matrix. + */ + get size() { + return this.rows * this.columns; + } + + /** + * Applies a callback for each element of the matrix. The function is called in the matrix (this) context. + * @param {function} callback - Function that will be called with two parameters : i (row) and j (column) + * @return {Matrix} this + */ + apply(callback) { + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); + } + var ii = this.rows; + var jj = this.columns; + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + callback.call(this, i, j); + } + } + return this; + } + + /** + * Returns a new 1D array filled row by row with the matrix values + * @return {Array} + */ + to1DArray() { + var array = new Array(this.size); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + array[i * this.columns + j] = this.get(i, j); + } + } + return array; + } + + /** + * Returns a 2D array containing a copy of the data + * @return {Array} + */ + to2DArray() { + var copy = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + copy[i] = new Array(this.columns); + for (var j = 0; j < this.columns; j++) { + copy[i][j] = this.get(i, j); + } + } + return copy; + } + + /** + * @return {boolean} true if the matrix has one row + */ + isRowVector() { + return this.rows === 1; + } + + /** + * @return {boolean} true if the matrix has one column + */ + isColumnVector() { + return this.columns === 1; + } + + /** + * @return {boolean} true if the matrix has one row or one column + */ + isVector() { + return (this.rows === 1) || (this.columns === 1); + } + + /** + * @return {boolean} true if the matrix has the same number of rows and columns + */ + isSquare() { + return this.rows === this.columns; + } + + /** + * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal + */ + isSymmetric() { + if (this.isSquare()) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j <= i; j++) { + if (this.get(i, j) !== this.get(j, i)) { + return false; + } + } + } + return true; + } + return false; + } + + /** + * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1 + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @param {number} value - The new value for the element + * @return {Matrix} this + */ + set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars + throw new Error('set method is unimplemented'); + } + + /** + * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4] + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @return {number} + */ + get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars + throw new Error('get method is unimplemented'); + } + + /** + * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of + * rows of the matrix, and colRep times the number of columns of the matrix + * @param {number} rowRep - Number of times the rows should be repeated + * @param {number} colRep - Number of times the columns should be re + * @return {Matrix} + * @example + * var matrix = new Matrix([[1,2]]); + * matrix.repeat(2); // [[1,2],[1,2]] + */ + repeat(rowRep, colRep) { + rowRep = rowRep || 1; + colRep = colRep || 1; + var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep); + for (var i = 0; i < rowRep; i++) { + for (var j = 0; j < colRep; j++) { + matrix.setSubMatrix(this, this.rows * i, this.columns * j); + } + } + return matrix; + } + + /** + * Fills the matrix with a given value. All elements will be set to this value. + * @param {number} value - New value + * @return {Matrix} this + */ + fill(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, value); + } + } + return this; + } + + /** + * Negates the matrix. All elements will be multiplied by (-1) + * @return {Matrix} this + */ + neg() { + return this.mulS(-1); + } + + /** + * Returns a new array from the given row index + * @param {number} index - Row index + * @return {Array} + */ + getRow(index) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + var row = new Array(this.columns); + for (var i = 0; i < this.columns; i++) { + row[i] = this.get(index, i); + } + return row; + } + + /** + * Returns a new row vector from the given row index + * @param {number} index - Row index + * @return {Matrix} + */ + getRowVector(index) { + return this.constructor.rowVector(this.getRow(index)); + } + + /** + * Sets a row at the given index + * @param {number} index - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setRow(index, array) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + array = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, array); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, array[i]); + } + return this; + } + + /** + * Swaps two rows + * @param {number} row1 - First row index + * @param {number} row2 - Second row index + * @return {Matrix} this + */ + swapRows(row1, row2) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row1); + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row2); + for (var i = 0; i < this.columns; i++) { + var temp = this.get(row1, i); + this.set(row1, i, this.get(row2, i)); + this.set(row2, i, temp); + } + return this; + } + + /** + * Returns a new array from the given column index + * @param {number} index - Column index + * @return {Array} + */ + getColumn(index) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + var column = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + column[i] = this.get(i, index); + } + return column; + } + + /** + * Returns a new column vector from the given column index + * @param {number} index - Column index + * @return {Matrix} + */ + getColumnVector(index) { + return this.constructor.columnVector(this.getColumn(index)); + } + + /** + * Sets a column at the given index + * @param {number} index - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setColumn(index, array) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + array = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, array); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, array[i]); + } + return this; + } + + /** + * Swaps two columns + * @param {number} column1 - First column index + * @param {number} column2 - Second column index + * @return {Matrix} this + */ + swapColumns(column1, column2) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column1); + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column2); + for (var i = 0; i < this.rows; i++) { + var temp = this.get(i, column1); + this.set(i, column1, this.get(i, column2)); + this.set(i, column2, temp); + } + return this; + } + + /** + * Adds the values of a vector to each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[j]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[j]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[j]); + } + } + return this; + } + + /** + * Divides the values of each row by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divRowVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["b" /* checkRowVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[j]); + } + } + return this; + } + + /** + * Adds the values of a vector to each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[i]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[i]); + } + } + return this; + } + + /** + * Divides the values of each column by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divColumnVector(vector) { + vector = __WEBPACK_IMPORTED_MODULE_3__util__["d" /* checkColumnVector */](this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a row with a scalar + * @param {number} index - Row index + * @param {number} value + * @return {Matrix} this + */ + mulRow(index, value) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, index); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, this.get(index, i) * value); + } + return this; + } + + /** + * Multiplies the values of a column with a scalar + * @param {number} index - Column index + * @param {number} value + * @return {Matrix} this + */ + mulColumn(index, value) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, index); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, this.get(i, index) * value); + } + return this; + } + + /** + * Returns the maximum value of the matrix + * @return {number} + */ + max() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the maximum value + * @return {Array} + */ + maxIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the minimum value of the matrix + * @return {number} + */ + min() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the minimum value + * @return {Array} + */ + minIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the maximum value of one row + * @param {number} row - Row index + * @return {number} + */ + maxRow(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + maxRowIndex(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one row + * @param {number} row - Row index + * @return {number} + */ + minRow(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + minRowIndex(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the maximum value of one column + * @param {number} column - Column index + * @return {number} + */ + maxColumn(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one column + * @param {number} column - Column index + * @return {Array} + */ + maxColumnIndex(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one column + * @param {number} column - Column index + * @return {number} + */ + minColumn(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the minimum value of one column + * @param {number} column - Column index + * @return {Array} + */ + minColumnIndex(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns an array containing the diagonal values of the matrix + * @return {Array} + */ + diag() { + var min = Math.min(this.rows, this.columns); + var diag = new Array(min); + for (var i = 0; i < min; i++) { + diag[i] = this.get(i, i); + } + return diag; + } + + /** + * Returns the sum by the argument given, if no argument given, + * it returns the sum of all elements of the matrix. + * @param {string} by - sum by 'row' or 'column'. + * @return {Matrix|number} + */ + sum(by) { + switch (by) { + case 'row': + return __WEBPACK_IMPORTED_MODULE_3__util__["e" /* sumByRow */](this); + case 'column': + return __WEBPACK_IMPORTED_MODULE_3__util__["f" /* sumByColumn */](this); + default: + return __WEBPACK_IMPORTED_MODULE_3__util__["g" /* sumAll */](this); + } + } + + /** + * Returns the mean of all elements of the matrix + * @return {number} + */ + mean() { + return this.sum() / this.size; + } + + /** + * Returns the product of all elements of the matrix + * @return {number} + */ + prod() { + var prod = 1; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + prod *= this.get(i, j); + } + } + return prod; + } + + /** + * Computes the cumulative sum of the matrix elements (in place, row by row) + * @return {Matrix} this + */ + cumulativeSum() { + var sum = 0; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + sum += this.get(i, j); + this.set(i, j, sum); + } + } + return this; + } + + /** + * Computes the dot (scalar) product between the matrix and another + * @param {Matrix} vector2 vector + * @return {number} + */ + dot(vector2) { + if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); + var vector1 = this.to1DArray(); + if (vector1.length !== vector2.length) { + throw new RangeError('vectors do not have the same size'); + } + var dot = 0; + for (var i = 0; i < vector1.length; i++) { + dot += vector1[i] * vector2[i]; + } + return dot; + } + + /** + * Returns the matrix product between this and other + * @param {Matrix} other + * @return {Matrix} + */ + mmul(other) { + other = this.constructor.checkMatrix(other); + if (this.columns !== other.rows) { + // eslint-disable-next-line no-console + console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); + } + + var m = this.rows; + var n = this.columns; + var p = other.columns; + + var result = new this.constructor[Symbol.species](m, p); + + var Bcolj = new Array(n); + for (var j = 0; j < p; j++) { + for (var k = 0; k < n; k++) { + Bcolj[k] = other.get(k, j); + } + + for (var i = 0; i < m; i++) { + var s = 0; + for (k = 0; k < n; k++) { + s += this.get(i, k) * Bcolj[k]; + } + + result.set(i, j, s); + } + } + return result; + } + + strassen2x2(other) { + var result = new this.constructor[Symbol.species](2, 2); + const a11 = this.get(0, 0); + const b11 = other.get(0, 0); + const a12 = this.get(0, 1); + const b12 = other.get(0, 1); + const a21 = this.get(1, 0); + const b21 = other.get(1, 0); + const a22 = this.get(1, 1); + const b22 = other.get(1, 1); + + // Compute intermediate values. + const m1 = (a11 + a22) * (b11 + b22); + const m2 = (a21 + a22) * b11; + const m3 = a11 * (b12 - b22); + const m4 = a22 * (b21 - b11); + const m5 = (a11 + a12) * b22; + const m6 = (a21 - a11) * (b11 + b12); + const m7 = (a12 - a22) * (b21 + b22); + + // Combine intermediate values into the output. + const c00 = m1 + m4 - m5 + m7; + const c01 = m3 + m5; + const c10 = m2 + m4; + const c11 = m1 - m2 + m3 + m6; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(1, 0, c10); + result.set(1, 1, c11); + return result; + } + + strassen3x3(other) { + var result = new this.constructor[Symbol.species](3, 3); + + const a00 = this.get(0, 0); + const a01 = this.get(0, 1); + const a02 = this.get(0, 2); + const a10 = this.get(1, 0); + const a11 = this.get(1, 1); + const a12 = this.get(1, 2); + const a20 = this.get(2, 0); + const a21 = this.get(2, 1); + const a22 = this.get(2, 2); + + const b00 = other.get(0, 0); + const b01 = other.get(0, 1); + const b02 = other.get(0, 2); + const b10 = other.get(1, 0); + const b11 = other.get(1, 1); + const b12 = other.get(1, 2); + const b20 = other.get(2, 0); + const b21 = other.get(2, 1); + const b22 = other.get(2, 2); + + const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11; + const m2 = (a00 - a10) * (-b01 + b11); + const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22); + const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11); + const m5 = (a10 + a11) * (-b00 + b01); + const m6 = a00 * b00; + const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12); + const m8 = (-a00 + a20) * (b02 - b12); + const m9 = (a20 + a21) * (-b00 + b02); + const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12; + const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21); + const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21); + const m13 = (a02 - a22) * (b11 - b21); + const m14 = a02 * b20; + const m15 = (a21 + a22) * (-b20 + b21); + const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22); + const m17 = (a02 - a12) * (b12 - b22); + const m18 = (a11 + a12) * (-b20 + b22); + const m19 = a01 * b10; + const m20 = a12 * b21; + const m21 = a10 * b02; + const m22 = a20 * b01; + const m23 = a22 * b22; + + const c00 = m6 + m14 + m19; + const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15; + const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18; + const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17; + const c11 = m2 + m4 + m5 + m6 + m20; + const c12 = m14 + m16 + m17 + m18 + m21; + const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14; + const c21 = m12 + m13 + m14 + m15 + m22; + const c22 = m6 + m7 + m8 + m9 + m23; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(0, 2, c02); + result.set(1, 0, c10); + result.set(1, 1, c11); + result.set(1, 2, c12); + result.set(2, 0, c20); + result.set(2, 1, c21); + result.set(2, 2, c22); + return result; + } + + /** + * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000. + * @param {Matrix} y + * @return {Matrix} + */ + mmulStrassen(y) { + var x = this.clone(); + var r1 = x.rows; + var c1 = x.columns; + var r2 = y.rows; + var c2 = y.columns; + if (c1 !== r2) { + // eslint-disable-next-line no-console + console.warn(`Multiplying ${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. + function embed(mat, rows, cols) { + var r = mat.rows; + var c = mat.columns; + if ((r === rows) && (c === cols)) { + return mat; + } else { + var resultat = Matrix.zeros(rows, cols); + resultat = resultat.setSubMatrix(mat, 0, 0); + return resultat; + } + } + + + // Make sure both matrices are the same size. + // This is exclusively for simplicity: + // this algorithm can be implemented with matrices of different sizes. + + var r = Math.max(r1, r2); + var c = Math.max(c1, c2); + x = embed(x, r, c); + y = embed(y, r, c); + + // Our recursive multiplication function. + function blockMult(a, b, rows, cols) { + // For small matrices, resort to naive multiplication. + if (rows <= 512 || cols <= 512) { + return a.mmul(b); // a is equivalent to this + } + + // Apply dynamic padding. + if ((rows % 2 === 1) && (cols % 2 === 1)) { + a = embed(a, rows + 1, cols + 1); + b = embed(b, rows + 1, cols + 1); + } else if (rows % 2 === 1) { + a = embed(a, rows + 1, cols); + b = embed(b, rows + 1, cols); + } else if (cols % 2 === 1) { + a = embed(a, rows, cols + 1); + b = embed(b, rows, cols + 1); + } + + var halfRows = parseInt(a.rows / 2); + var halfCols = parseInt(a.columns / 2); + // Subdivide input matrices. + var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); + var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); + + var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); + var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); + + var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); + var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); + + var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); + var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); + + // Compute intermediate values. + var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols); + var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols); + var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols); + var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols); + var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols); + var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols); + var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); + + // Combine intermediate values into the output. + var c11 = Matrix.add(m1, m4); + c11.sub(m5); + c11.add(m7); + var c12 = Matrix.add(m3, m5); + var c21 = Matrix.add(m2, m4); + var c22 = Matrix.sub(m1, m2); + c22.add(m3); + c22.add(m6); + + //Crop output to the desired size (undo dynamic padding). + var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns); + resultat = resultat.setSubMatrix(c11, 0, 0); + resultat = resultat.setSubMatrix(c12, c11.rows, 0); + resultat = resultat.setSubMatrix(c21, 0, c11.columns); + resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns); + return resultat.subMatrix(0, rows - 1, 0, cols - 1); + } + return blockMult(x, y, r, c); + } + + /** + * Returns a row-by-row scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The scaled matrix + */ + scaleRows(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.rows; i++) { + var scaled = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__["scale"])(this.getRow(i), {min, max}); + newMatrix.setRow(i, scaled); + } + return newMatrix; + } + + /** + * Returns a new column-by-column scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The new scaled matrix + * @example + * var matrix = new Matrix([[1,2],[-1,0]]); + * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]] + */ + scaleColumns(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.columns; i++) { + var scaled = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2_ml_array_utils__["scale"])(this.getColumn(i), { + min: min, + max: max + }); + newMatrix.setColumn(i, scaled); + } + return newMatrix; + } + + + /** + * Returns the Kronecker product (also known as tensor product) between this and other + * See https://en.wikipedia.org/wiki/Kronecker_product + * @param {Matrix} other + * @return {Matrix} + */ + kroneckerProduct(other) { + other = this.constructor.checkMatrix(other); + + var m = this.rows; + var n = this.columns; + var p = other.rows; + var q = other.columns; + + var result = new this.constructor[Symbol.species](m * p, n * q); + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + for (var k = 0; k < p; k++) { + for (var l = 0; l < q; l++) { + result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l); + } + } + } + } + return result; + } + + /** + * Transposes the matrix and returns a new one containing the result + * @return {Matrix} + */ + transpose() { + var result = new this.constructor[Symbol.species](this.columns, this.rows); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + result.set(j, i, this.get(i, j)); + } + } + return result; + } + + /** + * Sorts the rows (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortRows(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.rows; i++) { + this.setRow(i, this.getRow(i).sort(compareFunction)); + } + return this; + } + + /** + * Sorts the columns (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortColumns(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.columns; i++) { + this.setColumn(i, this.getColumn(i).sort(compareFunction)); + } + return this; + } + + /** + * Returns a subset of the matrix + * @param {number} startRow - First row index + * @param {number} endRow - Last row index + * @param {number} startColumn - First column index + * @param {number} endColumn - Last column index + * @return {Matrix} + */ + subMatrix(startRow, endRow, startColumn, endColumn) { + __WEBPACK_IMPORTED_MODULE_3__util__["h" /* checkRange */](this, startRow, endRow, startColumn, endColumn); + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1); + for (var i = startRow; i <= endRow; i++) { + for (var j = startColumn; j <= endColumn; j++) { + newMatrix[i - startRow][j - startColumn] = this.get(i, j); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of row indices + * @param {Array} indices - Array containing the row indices + * @param {number} [startColumn = 0] - First column index + * @param {number} [endColumn = this.columns-1] - Last column index + * @return {Matrix} + */ + subMatrixRow(indices, startColumn, endColumn) { + if (startColumn === undefined) startColumn = 0; + if (endColumn === undefined) endColumn = this.columns - 1; + if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1); + for (var i = 0; i < indices.length; i++) { + for (var j = startColumn; j <= endColumn; j++) { + if (indices[i] < 0 || indices[i] >= this.rows) { + throw new RangeError('Row index out of range: ' + indices[i]); + } + newMatrix.set(i, j - startColumn, this.get(indices[i], j)); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of column indices + * @param {Array} indices - Array containing the column indices + * @param {number} [startRow = 0] - First row index + * @param {number} [endRow = this.rows-1] - Last row index + * @return {Matrix} + */ + subMatrixColumn(indices, startRow, endRow) { + if (startRow === undefined) startRow = 0; + if (endRow === undefined) endRow = this.rows - 1; + if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length); + for (var i = 0; i < indices.length; i++) { + for (var j = startRow; j <= endRow; j++) { + if (indices[i] < 0 || indices[i] >= this.columns) { + throw new RangeError('Column index out of range: ' + indices[i]); + } + newMatrix.set(j - startRow, i, this.get(j, indices[i])); + } + } + return newMatrix; + } + + /** + * Set a part of the matrix to the given sub-matrix + * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values. + * @param {number} startRow - The index of the first row to set + * @param {number} startColumn - The index of the first column to set + * @return {Matrix} + */ + setSubMatrix(matrix, startRow, startColumn) { + matrix = this.constructor.checkMatrix(matrix); + var endRow = startRow + matrix.rows - 1; + var endColumn = startColumn + matrix.columns - 1; + __WEBPACK_IMPORTED_MODULE_3__util__["h" /* checkRange */](this, startRow, endRow, startColumn, endColumn); + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + this[startRow + i][startColumn + j] = matrix.get(i, j); + } + } + return this; + } + + /** + * Return a new matrix based on a selection of rows and columns + * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once. + * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once. + * @return {Matrix} The new matrix + */ + selection(rowIndices, columnIndices) { + var indices = __WEBPACK_IMPORTED_MODULE_3__util__["i" /* checkIndices */](this, rowIndices, columnIndices); + var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length); + for (var i = 0; i < indices.row.length; i++) { + var rowIndex = indices.row[i]; + for (var j = 0; j < indices.column.length; j++) { + var columnIndex = indices.column[j]; + newMatrix[i][j] = this.get(rowIndex, columnIndex); + } + } + return newMatrix; + } + + /** + * Returns the trace of the matrix (sum of the diagonal elements) + * @return {number} + */ + trace() { + var min = Math.min(this.rows, this.columns); + var trace = 0; + for (var i = 0; i < min; i++) { + trace += this.get(i, i); + } + return trace; + } + + /* + Matrix views + */ + + /** + * Returns a view of the transposition of the matrix + * @return {MatrixTransposeView} + */ + transposeView() { + return new __WEBPACK_IMPORTED_MODULE_4__views_transpose__["a" /* default */](this); + } + + /** + * Returns a view of the row vector with the given index + * @param {number} row - row index of the vector + * @return {MatrixRowView} + */ + rowView(row) { + __WEBPACK_IMPORTED_MODULE_3__util__["a" /* checkRowIndex */](this, row); + return new __WEBPACK_IMPORTED_MODULE_5__views_row__["a" /* default */](this, row); + } + + /** + * Returns a view of the column vector with the given index + * @param {number} column - column index of the vector + * @return {MatrixColumnView} + */ + columnView(column) { + __WEBPACK_IMPORTED_MODULE_3__util__["c" /* checkColumnIndex */](this, column); + return new __WEBPACK_IMPORTED_MODULE_8__views_column__["a" /* default */](this, column); + } + + /** + * Returns a view of the matrix flipped in the row axis + * @return {MatrixFlipRowView} + */ + flipRowView() { + return new __WEBPACK_IMPORTED_MODULE_9__views_flipRow__["a" /* default */](this); + } + + /** + * Returns a view of the matrix flipped in the column axis + * @return {MatrixFlipColumnView} + */ + flipColumnView() { + return new __WEBPACK_IMPORTED_MODULE_10__views_flipColumn__["a" /* default */](this); + } + + /** + * Returns a view of a submatrix giving the index boundaries + * @param {number} startRow - first row index of the submatrix + * @param {number} endRow - last row index of the submatrix + * @param {number} startColumn - first column index of the submatrix + * @param {number} endColumn - last column index of the submatrix + * @return {MatrixSubView} + */ + subMatrixView(startRow, endRow, startColumn, endColumn) { + return new __WEBPACK_IMPORTED_MODULE_6__views_sub__["a" /* default */](this, startRow, endRow, startColumn, endColumn); + } + + /** + * Returns a view of the cross of the row indices and the column indices + * @example + * // resulting vector is [[2], [2]] + * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1]) + * @param {Array} rowIndices + * @param {Array} columnIndices + * @return {MatrixSelectionView} + */ + selectionView(rowIndices, columnIndices) { + return new __WEBPACK_IMPORTED_MODULE_7__views_selection__["a" /* default */](this, rowIndices, columnIndices); + } + + + /** + * Calculates and returns the determinant of a matrix as a Number + * @example + * new Matrix([[1,2,3], [4,5,6]]).det() + * @return {number} + */ + det() { + if (this.isSquare()) { + var a, b, c, d; + if (this.columns === 2) { + // 2 x 2 matrix + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(1, 0); + d = this.get(1, 1); + + return a * d - (b * c); + } else if (this.columns === 3) { + // 3 x 3 matrix + var subMatrix0, subMatrix1, subMatrix2; + subMatrix0 = this.selectionView([1, 2], [1, 2]); + subMatrix1 = this.selectionView([1, 2], [0, 2]); + subMatrix2 = this.selectionView([1, 2], [0, 1]); + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(0, 2); + + return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det(); + } else { + // general purpose determinant using the LU decomposition + return new __WEBPACK_IMPORTED_MODULE_0__dc_lu__["a" /* default */](this).determinant; + } + + } else { + throw Error('Determinant can only be calculated for a square matrix.'); + } + } + + /** + * Returns inverse of a matrix if it exists or the pseudoinverse + * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15) + * @return {Matrix} the (pseudo)inverted matrix. + */ + pseudoInverse(threshold) { + if (threshold === undefined) threshold = Number.EPSILON; + var svdSolution = new __WEBPACK_IMPORTED_MODULE_1__dc_svd__["a" /* default */](this, {autoTranspose: true}); + + var U = svdSolution.leftSingularVectors; + var V = svdSolution.rightSingularVectors; + var s = svdSolution.diagonal; + + for (var i = 0; i < s.length; i++) { + if (Math.abs(s[i]) > threshold) { + s[i] = 1.0 / s[i]; + } else { + s[i] = 0.0; + } + } + + // convert list to diagonal + s = this.constructor[Symbol.species].diag(s); + return V.mmul(s.mmul(U.transposeView())); + } + } + + Matrix.prototype.klass = 'Matrix'; + + function compareNumbers(a, b) { + return a - b; + } + + /* + Synonyms + */ + + Matrix.random = Matrix.rand; + Matrix.diagonal = Matrix.diag; + Matrix.prototype.diagonal = Matrix.prototype.diag; + Matrix.identity = Matrix.eye; + Matrix.prototype.negate = Matrix.prototype.neg; + Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct; + Matrix.prototype.determinant = Matrix.prototype.det; + + /* + Add dynamically instance and static methods for mathematical operations + */ + + var inplaceOperator = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var inplaceOperatorScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% value); + } + } + return this; +}) +`; + + var inplaceOperatorMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); + } + } + return this; +}) +`; + + var staticOperator = ` +(function %name%(matrix, value) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(value); +}) +`; + + var inplaceMethod = ` +(function %name%() { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j))); + } + } + return this; +}) +`; + + var staticMethod = ` +(function %name%(matrix) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(); +}) +`; + + var inplaceMethodWithArgs = ` +(function %name%(%args%) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), %args%)); + } + } + return this; +}) +`; + + var staticMethodWithArgs = ` +(function %name%(matrix, %args%) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(%args%); +}) +`; + + + var inplaceMethodWithOneArgScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), value)); + } + } + return this; +}) +`; + var inplaceMethodWithOneArgMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); + } + } + return this; +}) +`; + + var inplaceMethodWithOneArg = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var staticMethodWithOneArg = staticMethodWithArgs; + + var operators = [ + // Arithmetic operators + ['+', 'add'], + ['-', 'sub', 'subtract'], + ['*', 'mul', 'multiply'], + ['/', 'div', 'divide'], + ['%', 'mod', 'modulus'], + // Bitwise operators + ['&', 'and'], + ['|', 'or'], + ['^', 'xor'], + ['<<', 'leftShift'], + ['>>', 'signPropagatingRightShift'], + ['>>>', 'rightShift', 'zeroFillRightShift'] + ]; + + var i; + var eval2 = eval; + for (var operator of operators) { + var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]})); + var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]})); + var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]})); + var staticOp = eval2(fillTemplateFunction(staticOperator, {name: operator[1]})); + for (i = 1; i < operator.length; i++) { + Matrix.prototype[operator[i]] = inplaceOp; + Matrix.prototype[operator[i] + 'S'] = inplaceOpS; + Matrix.prototype[operator[i] + 'M'] = inplaceOpM; + Matrix[operator[i]] = staticOp; + } + } + + 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]); + }); + + for (var method of methods) { + var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]})); + var staticMeth = eval2(fillTemplateFunction(staticMethod, {name: method[1]})); + for (i = 1; i < method.length; i++) { + Matrix.prototype[method[i]] = inplaceMeth; + Matrix[method[i]] = staticMeth; + } + } + + var methodsWithArgs = [ + ['Math.pow', 1, 'pow'] + ]; + + for (var methodWithArg of methodsWithArgs) { + var args = 'arg0'; + for (i = 1; i < methodWithArg[1]; i++) { + args += `, arg${i}`; + } + if (methodWithArg[1] !== 1) { + var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, { + name: methodWithArg[2], + method: methodWithArg[0], + args: args + })); + var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args})); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs; + Matrix[methodWithArg[i]] = staticMethWithArgs; + } + } else { + var tmplVar = { + name: methodWithArg[2], + args: args, + method: methodWithArg[0] + }; + var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar)); + var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar)); + var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar)); + var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar)); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethod2; + Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM; + Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS; + Matrix[methodWithArg[i]] = staticMethod2; + } + } + } + + function fillTemplateFunction(template, values) { + for (var value in values) { + template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]); + } + return template; + } + + return Matrix; +} + + +/***/ }), +/* 36 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(7); + + +// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs +function LuDecomposition(matrix) { + if (!(this instanceof LuDecomposition)) { + return new LuDecomposition(matrix); + } + + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + + var lu = matrix.clone(), + rows = lu.rows, + columns = lu.columns, + pivotVector = new Array(rows), + pivotSign = 1, + i, j, k, p, s, t, v, + LUrowi, LUcolj, kmax; + + for (i = 0; i < rows; i++) { + pivotVector[i] = i; + } + + LUcolj = new Array(rows); + + for (j = 0; j < columns; j++) { + + for (i = 0; i < rows; i++) { + LUcolj[i] = lu[i][j]; + } + + for (i = 0; i < rows; i++) { + LUrowi = lu[i]; + kmax = Math.min(i, j); + s = 0; + for (k = 0; k < kmax; k++) { + s += LUrowi[k] * LUcolj[k]; + } + LUrowi[j] = LUcolj[i] -= s; + } + + 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[p][k]; + lu[p][k] = lu[j][k]; + lu[j][k] = t; + } + + v = pivotVector[p]; + pivotVector[p] = pivotVector[j]; + pivotVector[j] = v; + + pivotSign = -pivotSign; + } + + if (j < rows && lu[j][j] !== 0) { + for (i = j + 1; i < rows; i++) { + lu[i][j] /= lu[j][j]; + } + } + } + + this.LU = lu; + this.pivotVector = pivotVector; + this.pivotSign = pivotSign; +} + +LuDecomposition.prototype = { + isSingular: function () { + var data = this.LU, + col = data.columns; + for (var j = 0; j < col; j++) { + if (data[j][j] === 0) { + return true; + } + } + return false; + }, + get determinant() { + var data = this.LU; + if (!data.isSquare()) { + throw new Error('Matrix must be square'); + } + var determinant = this.pivotSign, col = data.columns; + for (var j = 0; j < col; j++) { + determinant *= data[j][j]; + } + return determinant; + }, + get lowerTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i > j) { + X[i][j] = data[i][j]; + } else if (i === j) { + X[i][j] = 1; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get upperTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i <= j) { + X[i][j] = data[i][j]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get pivotPermutationVector() { + return this.pivotVector.slice(); + }, + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var lu = this.LU, + rows = lu.rows; + + if (rows !== value.rows) { + throw new Error('Invalid matrix dimensions'); + } + if (this.isSingular()) { + throw new Error('LU matrix is singular'); + } + + var count = value.columns; + var X = value.subMatrixRow(this.pivotVector, 0, count - 1); + var columns = lu.columns; + var i, j, k; + + for (k = 0; k < columns; k++) { + for (i = k + 1; i < columns; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + for (k = columns - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= lu[k][k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + return X; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (LuDecomposition); + + +/***/ }), +/* 37 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (immutable) */ __webpack_exports__["a"] = hypotenuse; +/* unused harmony export getEmpty2DArray */ +/* harmony export (immutable) */ __webpack_exports__["b"] = getFilled2DArray; +function hypotenuse(a, b) { + var r; + if (Math.abs(a) > Math.abs(b)) { + r = b / a; + return Math.abs(a) * Math.sqrt(1 + r * r); + } + if (b !== 0) { + r = a / b; + return Math.abs(b) * Math.sqrt(1 + r * r); + } + return 0; +} + +// For use in the decomposition algorithms. With big matrices, access time is +// too long on elements from array subclass +// todo check when it is fixed in v8 +// http://jsperf.com/access-and-write-array-subclass +function getEmpty2DArray(rows, columns) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + } + return array; +} + +function getFilled2DArray(rows, columns, value) { + var array = new Array(rows); + for (var i = 0; i < rows; i++) { + array[i] = new Array(columns); + for (var j = 0; j < columns; j++) { + array[i][j] = value; + } + } + return array; +} + + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +class BaseRegression { + predict(x) { + var y2; + if (Array.isArray(x)) { + y2 = new Array(x.length); + for (var i = 0; i < x.length; i++) { + y2[i] = this._predict(x[i]); + } + } else if (Number.isFinite(x)) { + y2 = this._predict(x); + } else { + throw new TypeError('x must be a number or array'); + } + return y2; + } + + _predict() { + throw new Error('_compute not implemented'); + } + + train() { + //Do nothing for this package + } + + toString() { + return ''; + } + + toLaTeX() { + return ''; + } + + /** + * Return the correlation coefficient of determination (r) and chi-square. + * @param {Array} x + * @param {Array} y + * @return {object} + */ + modelQuality(x, y) { + let n = x.length; + var y2 = new Array(n); + for (let i = 0; i < n; i++) { + y2[i] = this._predict(x[i]); + } + var xSum = 0; + var ySum = 0; + var chi2 = 0; + var rmsd = 0; + var xSquared = 0; + var ySquared = 0; + var 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]; + if (y[i] !== 0) { + chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i]; + } + rmsd = (y[i] - y2[i]) * (y[i] - y2[i]); + } + + var r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum)); + + return { + r: r, + r2: r * r, + chi2: chi2, + rmsd: rmsd * rmsd / n + }; + } + +} + +module.exports = BaseRegression; + + +/***/ }), +/* 39 */ +/***/ (function(module, exports) { + +module.exports = function(haystack, needle, comparator, low, high) { + var mid, cmp; + + if(low === undefined) + low = 0; + + else { + low = low|0; + if(low < 0 || low >= haystack.length) + throw new RangeError("invalid lower bound"); + } + + if(high === undefined) + high = haystack.length - 1; + + else { + high = high|0; + if(high < low || high >= haystack.length) + throw new RangeError("invalid upper bound"); + } + + while(low <= high) { + /* Note that "(low + high) >>> 1" may overflow, and results in a typecast + * to double (which gives the wrong results). */ + mid = low + (high - low >> 1); + cmp = +comparator(haystack[mid], needle, mid, haystack); + + /* Too low. */ + if(cmp < 0.0) + low = mid + 1; + + /* Too high. */ + else if(cmp > 0.0) + high = mid - 1; + + /* Key found. */ + else + return mid; + } + + /* Key not found. */ + return ~low; +} + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + + +/** + * Computes a distance/similarity matrix given an array of data and a distance/similarity function. + * @param {Array} data An array of data + * @param {function} distanceFn A function that accepts two arguments and computes a distance/similarity between them + * @return {Array} The similarity matrix. The similarity matrix is square and has a size equal to the length of + * the data array + */ +function distanceMatrix(data, distanceFn) { + const length = data.length; + let result = Array.from({length}).map(() => Array.from({length})); + + // Compute upper distance matrix + for (let i = 0; i < length; i++) { + for (let j = 0; j <= i; j++) { + result[i][j] = distanceFn(data[i], data[j]); + } + } + + // Copy to lower distance matrix + for (let i = 0; i < length; i++) { + for (let j = i + 1; j < length; j++) { + result[i][j] = result[j][i]; + } + } + + return result; +} + +module.exports = distanceMatrix; + + +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.distance = __webpack_require__(108); +exports.similarity = __webpack_require__(144); + +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const newArray = __webpack_require__(250); + +const primeFinder = __webpack_require__(153); +const nextPrime = primeFinder.nextPrime; +const largestPrime = primeFinder.largestPrime; + +const FREE = 0; +const FULL = 1; +const REMOVED = 2; + +const defaultInitialCapacity = 150; +const defaultMinLoadFactor = 1 / 6; +const defaultMaxLoadFactor = 2 / 3; + +class HashTable { + constructor(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; + } + + const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity; + if (initialCapacity < 0) { + throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`); + } + + const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor; + const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor; + if (minLoadFactor < 0 || minLoadFactor >= 1) { + throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`); + } + if (maxLoadFactor <= 0 || maxLoadFactor >= 1) { + throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`); + } + if (minLoadFactor >= maxLoadFactor) { + throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`); + } + + let capacity = initialCapacity; + // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to + // avoid the need to rehash before this capacity is reached. + // actualCapacity * maxLoadFactor >= capacity + capacity = (capacity / maxLoadFactor) | 0; + capacity = nextPrime(capacity); + if (capacity === 0) capacity = 1; + + this.table = newArray(capacity, 0); + this.values = newArray(capacity, 0); + this.state = newArray(capacity, 0); + + this.minLoadFactor = minLoadFactor; + if (capacity === largestPrime) { + this.maxLoadFactor = 1; + } else { + this.maxLoadFactor = maxLoadFactor; + } + + this.distinct = 0; + this.freeEntries = capacity; + + this.lowWaterMark = 0; + this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor); + } + + clone() { + return new HashTable(this); + } + + get size() { + return this.distinct; + } + + get(key) { + const i = this.indexOfKey(key); + if (i < 0) return 0; + return this.values[i]; + } + + set(key, value) { + let i = this.indexOfInsertion(key); + if (i < 0) { + i = -i - 1; + this.values[i] = value; + return false; + } + + if (this.distinct > this.highWaterMark) { + const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); + this.rehash(newCapacity); + return this.set(key, value); + } + + this.table[i] = key; + this.values[i] = value; + if (this.state[i] === FREE) this.freeEntries--; + this.state[i] = FULL; + this.distinct++; + + if (this.freeEntries < 1) { + const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor); + this.rehash(newCapacity); + } + + return true; + } + + 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; + } + + 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; + } + + maybeShrinkCapacity() { + if (this.distinct < this.lowWaterMark) { + const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor); + this.rehash(newCapacity); + } + } + + containsKey(key) { + return this.indexOfKey(key) >= 0; + } + + 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; + + while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { + i -= decrement; + if (i < 0) i += length; + } + + if (state[i] === FREE) return -1; + return i; + } + + containsValue(value) { + return this.indexOfValue(value) >= 0; + } + + 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; + } + + 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; + } + + if (state[i] === REMOVED) { + const j = i; + while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) { + i -= decrement; + if (i < 0) i += length; + } + if (state[i] === FREE) i = j; + } + + if (state[i] === FULL) { + return -i - 1; + } + + return i; + } + + ensureCapacity(minCapacity) { + if (this.table.length < minCapacity) { + const newCapacity = nextPrime(minCapacity); + this.rehash(newCapacity); + } + } + + rehash(newCapacity) { + const oldCapacity = this.table.length; + + if (newCapacity <= this.distinct) throw new Error('Unexpected'); + + const oldTable = this.table; + const oldValues = this.values; + const oldState = this.state; + + const newTable = newArray(newCapacity, 0); + const newValues = newArray(newCapacity, 0); + const newState = newArray(newCapacity, 0); + + this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor); + this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor); + + this.table = newTable; + this.values = newValues; + this.state = newState; + this.freeEntries = newCapacity - this.distinct; + + for (var i = 0; i < oldCapacity; i++) { + if (oldState[i] === FULL) { + var element = oldTable[i]; + var index = this.indexOfInsertion(element); + newTable[index] = element; + newValues[index] = oldValues[i]; + newState[index] = FULL; + } + } + } + + forEachKey(callback) { + for (var i = 0; i < this.state.length; i++) { + if (this.state[i] === FULL) { + if (!callback(this.table[i])) return false; + } + } + return true; + } + + 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; + } +} + +module.exports = HashTable; + +function chooseLowWaterMark(capacity, minLoad) { + return (capacity * minLoad) | 0; +} + +function chooseHighWaterMark(capacity, maxLoad) { + return Math.min(capacity - 2, (capacity * maxLoad) | 0); +} + +function chooseGrowCapacity(size, minLoad, maxLoad) { + return nextPrime(Math.max(size + 1, (4 * size / (3 * minLoad + maxLoad)) | 0)); +} + +function chooseShrinkCapacity(size, minLoad, maxLoad) { + return nextPrime(Math.max(size + 1, (4 * size / (minLoad + 3 * maxLoad)) | 0)); +} + + +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var extend = __webpack_require__(21); + +var defaultOptions = { + size: 1, + value: 0 +}; + +/** + * Case when the entry is an array + * @param data + * @param options + * @returns {Array} + */ +function arrayCase(data, options) { + var len = data.length; + if (typeof options.size === 'number') + options.size = [options.size, options.size]; + + var cond = len + options.size[0] + options.size[1]; + + var output; + if (options.output) { + if (options.output.length !== cond) + throw new RangeError('Wrong output size'); + output = options.output; + } + else + output = new Array(cond); + + var i; + + // circular option + if (options.value === 'circular') { + for (i = 0; i < cond; i++) { + if (i < options.size[0]) + output[i] = data[((len - (options.size[0] % len)) + i) % len]; + else if (i < (options.size[0] + len)) + output[i] = data[i - options.size[0]]; + else + output[i] = data[(i - options.size[0]) % len]; + } + } + + // replicate option + else if (options.value === 'replicate') { + for (i = 0; i < cond; i++) { + if (i < options.size[0]) + output[i] = data[0]; + else if (i < (options.size[0] + len)) + output[i] = data[i - options.size[0]]; + else + output[i] = data[len - 1]; + } + } + + // symmetric option + else if (options.value === 'symmetric') { + if ((options.size[0] > len) || (options.size[1] > len)) + throw new RangeError('expanded value should not be bigger than the data length'); + for (i = 0; i < cond; i++) { + if (i < options.size[0]) + output[i] = data[options.size[0] - 1 - i]; + else if (i < (options.size[0] + len)) + output[i] = data[i - options.size[0]]; + else + output[i] = data[2*len + options.size[0] - i - 1]; + } + } + + // default option + else { + for (i = 0; i < cond; i++) { + if (i < options.size[0]) + output[i] = options.value; + else if (i < (options.size[0] + len)) + output[i] = data[i - options.size[0]]; + else + output[i] = options.value; + } + } + + return output; +} + +/** + * Case when the entry is a matrix + * @param data + * @param options + * @returns {Array} + */ +function matrixCase(data, options) { + var row = data.length; + var col = data[0].length; + if (options.size[0] === undefined) + options.size = [options.size, options.size, options.size, options.size]; + throw new Error('matrix not supported yet, sorry'); +} + +/** + * Pads and array + * @param {Array } data + * @param {object} options + */ +function padArray (data, options) { + options = extend({}, defaultOptions, options); + + if (Array.isArray(data)) { + if (Array.isArray(data[0])) + return matrixCase(data, options); + else + return arrayCase(data, options); + } + else + throw new TypeError('data should be an array'); +} + +module.exports = padArray; + + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var numberIsNan = __webpack_require__(251); + +function assertNum(x) { + if (typeof x !== 'number' || numberIsNan(x)) { + throw new TypeError('Expected a number'); + } +} + +exports.asc = function (a, b) { + assertNum(a); + assertNum(b); + return a - b; +}; + +exports.desc = function (a, b) { + assertNum(a); + assertNum(b); + return b - a; +}; + + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Created by acastillo on 8/24/15. + */ +/** + * Non in-place function definitions, compatible with mathjs code * + */ + + + +var Matrix = __webpack_require__(0); + +function matrix(A,B){ + return new Matrix(A,B); +} + +function ones(rows, cols){ + return Matrix.ones(rows,cols); +} + +function eye(rows, cols){ + return Matrix.eye(rows, cols); +} + +function zeros(rows, cols){ + return Matrix.zeros(rows, cols); +} + +function random(rows, cols){ + return Matrix.rand(rows,cols); +} + +function transpose(A){ + if(typeof A == 'number') + return A; + var result = A.clone(); + return result.transpose(); +} + +function add(A, B){ + if(typeof A == 'number'&&typeof B === 'number') + return A+B; + if(typeof A == 'number') + return this.add(B,A); + + var result = A.clone(); + return result.add(B); + +} + +function subtract(A, B){ + if(typeof A == 'number'&&typeof B === 'number') + return A-B; + if(typeof A == 'number') + return this.subtract(B,A); + var result = A.clone(); + return result.sub(B); +} + +function multiply(A, B){ + if(typeof A == 'number'&&typeof B === 'number') + return A*B; + if(typeof A == 'number') + return this.multiply(B,A); + + var result = A.clone(); + + if(typeof B === 'number') + result.mul(B); + else + result = result.mmul(B); + + if(result.rows==1&&result.columns==1) + return result[0][0]; + else + return result; + +} + +function dotMultiply(A, B){ + var result = A.clone(); + return result.mul(B); +} + +function dotDivide(A, B){ + var result = A.clone(); + return result.div(B); +} + +function diag(A){ + var diag = null; + var rows = A.rows, cols = A.columns, j, r; + //It is an array + if(typeof cols === "undefined" && (typeof A)=='object'){ + if(A[0]&&A[0].length){ + rows = A.length; + cols = A[0].length; + r = Math.min(rows,cols); + diag = Matrix.zeros(cols, cols); + for (j = 0; j < cols; j++) { + diag[j][j]=A[j][j]; + } + } + else{ + cols = A.length; + diag = Matrix.zeros(cols, cols); + for (j = 0; j < cols; j++) { + diag[j][j]=A[j]; + } + } + + } + if(rows == 1){ + diag = Matrix.zeros(cols, cols); + for (j = 0; j < cols; j++) { + diag[j][j]=A[0][j]; + } + } + else{ + if(rows>0 && cols > 0){ + r = Math.min(rows,cols); + diag = new Array(r); + for (j = 0; j < r; j++) { + diag[j] = A[j][j]; + } + } + } + return diag; +} + +function min(A, B){ + if(typeof A==='number' && typeof B ==='number') + return Math.min(A,B); + var ii = A.rows, jj = A.columns; + var result = new Matrix(ii,jj); + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + if (A[i][j] < B[i][j]) { + result[i][j] = A[i][j]; + } + else{ + result[i][j] = B[i][j]; + } + } + } + return result; +} + +function max(A, B){ + if(typeof A==='number' && typeof B ==='number') + return Math.max(A,B); + var ii = A.rows, jj = A.columns; + var result = new Matrix(ii,jj); + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + if (A[i][j] > B[i][j]) { + result[i][j] = A[i][j]; + } + else{ + result[i][j] = B[i][j]; + } + } + } + return result; +} + +function sqrt(A){ + if(typeof A==='number' ) + return Math.sqrt(A); + var ii = A.rows, jj = A.columns; + var result = new Matrix(ii,jj); + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + result[i][j] = Math.sqrt(A[i][j]); + + } + } + return result; +} + +function abs(A){ + if(typeof A==='number' ) + return Math.abs(A); + var ii = A.rows, jj = A.columns; + var result = new Matrix(ii,jj); + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + result[i][j] = Math.abs(A[i][j]); + + } + } + return result; +} + +function exp(A){ + if(typeof A==='number' ) + return Math.sqrt(A); + var ii = A.rows, jj = A.columns; + var result = new Matrix(ii,jj); + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + result[i][j] = Math.exp(A[i][j]); + } + } + return result; +} + +function dotPow(A, b){ + if(typeof A==='number' ) + return Math.pow(A,b); + //console.log(A); + var ii = A.rows, jj = A.columns; + var result = new Matrix(ii,jj); + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + result[i][j] = Math.pow(A[i][j],b); + } + } + return result; +} + +function solve(A, B){ + return A.solve(B); +} + +function inv(A){ + if(typeof A ==="number") + return 1/A; + return A.inverse(); +} + +module.exports = { + transpose:transpose, + add:add, + subtract:subtract, + multiply:multiply, + dotMultiply:dotMultiply, + dotDivide:dotDivide, + diag:diag, + min:min, + max:max, + solve:solve, + inv:inv, + sqrt:sqrt, + exp:exp, + dotPow:dotPow, + abs:abs, + matrix:matrix, + ones:ones, + zeros:zeros, + random:random, + eye:eye +}; + + +/***/ }), +/* 46 */ +/***/ (function(module, exports) { + +module.exports = function dice(a, b) { + var ii = a.length, + p = 0, + q1 = 0, + q2 = 0; + for (var i = 0; i < ii ; i++) { + p += a[i] * a[i]; + q1 += b[i] * b[i]; + q2 += (a[i] - b[i]) * (a[i] - b[i]); + } + return q2 / (p + q1); +}; + + +/***/ }), +/* 47 */ +/***/ (function(module, exports) { + +module.exports = function intersection(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii ; i++) { + ans += Math.min(a[i], b[i]); + } + return 1 - ans; +}; + + +/***/ }), +/* 48 */ +/***/ (function(module, exports) { + +module.exports = function jaccard(a, b) { + var ii = a.length, + p1 = 0, + p2 = 0, + q1 = 0, + q2 = 0; + for (var i = 0; i < ii ; i++) { + p1 += a[i] * b[i]; + p2 += a[i] * a[i]; + q1 += b[i] * b[i]; + q2 += (a[i] - b[i]) * (a[i] - b[i]); + } + return q2 / (p2 + q1 - p1); +}; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports) { + +module.exports = function kulczynski(a, b) { + var ii = a.length, + up = 0, + down = 0; + for (var i = 0; i < ii ; i++) { + up += Math.abs(a[i] - b[i]); + down += Math.min(a[i],b[i]); + } + return up / down; +}; + + +/***/ }), +/* 50 */ +/***/ (function(module, exports) { + +module.exports = function motyka(a, b) { + var ii = a.length, + up = 0, + down = 0; + for (var i = 0; i < ii ; i++) { + up += Math.min(a[i], b[i]); + down += a[i] + b[i]; + } + return 1 - (up / down); +}; + + +/***/ }), +/* 51 */ +/***/ (function(module, exports) { + +module.exports = function squaredChord(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii ; i++) { + ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i])); + } + return ans; +}; + + +/***/ }), +/* 52 */ +/***/ (function(module, exports) { + +module.exports = function cosine(a, b) { + var ii = a.length, + p = 0, + p2 = 0, + q2 = 0; + for (var i = 0; i < ii ; i++) { + p += a[i] * b[i]; + p2 += a[i] * a[i]; + q2 += b[i] * b[i]; + } + return p / (Math.sqrt(p2) * Math.sqrt(q2)); +}; + + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function czekanowskiSimilarity(a, b) { + var up = 0; + var down = 0; + for (var i = 0; i < a.length; i++) { + up += Math.min(a[i], b[i]); + down += a[i] + b[i]; + } + return 2 * up / down; +}; + + +/***/ }), +/* 54 */ +/***/ (function(module, exports) { + +module.exports = function tanimoto(a, b, bitvector) { + if (bitvector) { + var inter = 0, + union = 0; + for (var j = 0; j < a.length; j++) { + inter += a[j] && b[j]; + union += a[j] || b[j]; + } + if (union === 0) + return 1; + return inter / union; + } + else { + var ii = a.length, + p = 0, + q = 0, + m = 0; + for (var i = 0; i < ii ; i++) { + p += a[i]; + q += b[i]; + m += Math.min(a[i],b[i]); + } + return 1 - (p + q - 2 * m) / (p + q - m); + } +}; + + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Matrix = __webpack_require__(0); + +var Utils = __webpack_require__(57); +const ACTIVATION_FUNCTIONS = __webpack_require__(56); + +class Layer { + /** + * Create a new layer with the given options + * @param {object} options + * @param {number} [options.inputSize] - Number of conections that enter the neurons. + * @param {number} [options.outputSize] - Number of conections that leave the neurons. + * @param {number} [options.regularization] - Regularization parameter. + * @param {number} [options.epsilon] - Learning rate parameter. + * @param {string} [options.activation] - Activation function parameter from the FeedForwardNeuralNetwork class. + * @param {number} [options.activationParam] - Activation parameter if needed. + */ + constructor(options) { + this.inputSize = options.inputSize; + this.outputSize = options.outputSize; + this.regularization = options.regularization; + this.epsilon = options.epsilon; + this.activation = options.activation; + this.activationParam = options.activationParam; + + var selectedFunction = ACTIVATION_FUNCTIONS[options.activation]; + var params = selectedFunction.activation.length; + + var actFunction = params > 1 ? val => selectedFunction.activation(val, options.activationParam) : selectedFunction.activation; + var derFunction = params > 1 ? val => selectedFunction.derivate(val, options.activationParam) : selectedFunction.derivate; + + this.activationFunction = function (i, j) { + this[i][j] = actFunction(this[i][j]); + }; + this.derivate = function (i, j) { + this[i][j] = derFunction(this[i][j]); + }; + + if (options.model) { + // load model + this.W = Matrix.checkMatrix(options.W); + this.b = Matrix.checkMatrix(options.b); + + } else { + // default constructor + + this.W = Matrix.rand(this.inputSize, this.outputSize); + this.b = Matrix.zeros(1, this.outputSize); + + this.W.apply(function (i, j) { + this[i][j] /= Math.sqrt(options.inputSize); + }); + } + } + + /** + * 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; + } + + /** + * apply backpropagation algorithm at the current layer + * @param {Matrix} delta - delta values estimated at the following layer. + * @param {Matrix} a - 'a' values from the following layer. + * @return {Matrix} the new delta values for the next layer. + */ + backpropagation(delta, a) { + this.dW = a.transposeView().mmul(delta); + this.db = Utils.sumCol(delta); + + var aCopy = a.clone(); + return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate)); + } + + /** + * 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)); + } + + /** + * 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 + }; + } + + /** + * Creates a new Layer with the given model. + * @param {object} model + * @return {Layer} + */ + static load(model) { + if (model.model !== 'Layer') { + throw new RangeError('the current model is not a Layer model'); + } + return new Layer(model); + } + +} + +module.exports = Layer; + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +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 + } +}; + +module.exports = ACTIVATION_FUNCTIONS; + + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Matrix = __webpack_require__(0); + +/** + * Retrieves the sum at each row of the given matrix. + * @param {Matrix} matrix + * @return {Matrix} + */ +function sumRow(matrix) { + var sum = Matrix.zeros(matrix.rows, 1); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum[i][0] += matrix[i][j]; + } + } + return sum; +} + +/** + * Retrieves the sum at each column of the given matrix. + * @param {Matrix} matrix + * @return {Matrix} + */ +function sumCol(matrix) { + var sum = Matrix.zeros(1, matrix.columns); + for (var i = 0; i < matrix.rows; ++i) { + for (var j = 0; j < matrix.columns; ++j) { + sum[0][j] += matrix[i][j]; + } + } + return sum; +} + +/** + * 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 = {}, outputs = {}, l = array.length, index = 0; + for (var i = 0; i < l; i += 1) { + if (inputs[array[i]] === undefined) { + inputs[array[i]] = index; + outputs[index] = array[i]; + index++; + } + } + + return { + inputs: inputs, + outputs: outputs + }; +} + +module.exports = { + dictOutputs: dictOutputs, + sumCol: sumCol, + sumRow: sumRow +}; + + +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const Cluster = __webpack_require__(22); +const util = __webpack_require__(255); + +function ClusterLeaf(index) { + Cluster.call(this); + this.index = index; + this.distance = 0; + this.children = []; +} + +util.inherits(ClusterLeaf, Cluster); + +module.exports = ClusterLeaf; + + +/***/ }), +/* 59 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(25); + + + +//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs +function QrDecomposition(value) { + if (!(this instanceof QrDecomposition)) { + return new QrDecomposition(value); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var qr = value.clone(), + m = value.rows, + n = value.columns, + rdiag = new Array(n), + i, j, k, s; + + for (k = 0; k < n; k++) { + var nrm = 0; + for (i = k; i < m; i++) { + nrm = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(nrm, qr[i][k]); + } + if (nrm !== 0) { + if (qr[k][k] < 0) { + nrm = -nrm; + } + for (i = k; i < m; i++) { + qr[i][k] /= nrm; + } + qr[k][k] += 1; + for (j = k + 1; j < n; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * qr[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + qr[i][j] += s * qr[i][k]; + } + } + } + rdiag[k] = -nrm; + } + + this.QR = qr; + this.Rdiag = rdiag; +} + +QrDecomposition.prototype = { + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var qr = this.QR, + m = qr.rows; + + if (value.rows !== m) { + throw new Error('Matrix row dimensions must agree'); + } + if (!this.isFullRank()) { + throw new Error('Matrix is rank deficient'); + } + + var count = value.columns; + var X = value.clone(); + var n = qr.columns; + var i, j, k, s; + + for (k = 0; k < n; k++) { + for (j = 0; j < count; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * X[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + for (k = n - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= this.Rdiag[k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * qr[i][k]; + } + } + } + + return X.subMatrix(0, n - 1, 0, count - 1); + }, + isFullRank: function () { + var columns = this.QR.columns; + for (var i = 0; i < columns; i++) { + if (this.Rdiag[i] === 0) { + return false; + } + } + return true; + }, + get upperTriangularMatrix() { + var qr = this.QR, + n = qr.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + if (i < j) { + X[i][j] = qr[i][j]; + } else if (i === j) { + X[i][j] = this.Rdiag[i]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get orthogonalMatrix() { + var qr = this.QR, + rows = qr.rows, + columns = qr.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns), + i, j, k, s; + + for (k = columns - 1; k >= 0; k--) { + for (i = 0; i < rows; i++) { + X[i][k] = 0; + } + X[k][k] = 1; + for (j = k; j < columns; j++) { + if (qr[k][k] !== 0) { + s = 0; + for (i = k; i < rows; i++) { + s += qr[i][k] * X[i][j]; + } + + s = -s / qr[k][k]; + + for (i = k; i < rows; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + } + return X; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (QrDecomposition); + + +/***/ }), +/* 60 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(25); + + + +// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs +function SingularValueDecomposition(value, options) { + if (!(this instanceof SingularValueDecomposition)) { + return new SingularValueDecomposition(value, options); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + options = options || {}; + + var m = value.rows, + n = value.columns, + nu = Math.min(m, n); + + var wantu = true, wantv = true; + if (options.computeLeftSingularVectors === false) wantu = false; + if (options.computeRightSingularVectors === false) wantv = false; + var autoTranspose = options.autoTranspose === true; + + var swapped = false; + var a; + if (m < n) { + if (!autoTranspose) { + a = value.clone(); + // eslint-disable-next-line no-console + console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'); + } else { + a = value.transpose(); + m = a.rows; + n = a.columns; + swapped = true; + var aux = wantu; + wantu = wantv; + wantv = aux; + } + } else { + a = value.clone(); + } + + var s = new Array(Math.min(m + 1, n)), + U = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(m, nu, 0), + V = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + e = new Array(n), + work = new Array(m); + + var nct = Math.min(m - 1, n); + var nrt = Math.max(0, Math.min(n - 2, m)); + + var i, j, k, p, t, ks, f, cs, sn, max, kase, + scale, sp, spm1, epm1, sk, ek, b, c, shift, g; + + for (k = 0, max = Math.max(nct, nrt); k < max; k++) { + if (k < nct) { + s[k] = 0; + for (i = k; i < m; i++) { + s[k] = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[k], a[i][k]); + } + if (s[k] !== 0) { + if (a[k][k] < 0) { + s[k] = -s[k]; + } + for (i = k; i < m; i++) { + a[i][k] /= s[k]; + } + a[k][k] += 1; + } + s[k] = -s[k]; + } + + for (j = k + 1; j < n; j++) { + if ((k < nct) && (s[k] !== 0)) { + t = 0; + for (i = k; i < m; i++) { + t += a[i][k] * a[i][j]; + } + t = -t / a[k][k]; + for (i = k; i < m; i++) { + a[i][j] += t * a[i][k]; + } + } + e[j] = a[k][j]; + } + + if (wantu && (k < nct)) { + for (i = k; i < m; i++) { + U[i][k] = a[i][k]; + } + } + + if (k < nrt) { + e[k] = 0; + for (i = k + 1; i < n; i++) { + e[k] = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(e[k], e[i]); + } + if (e[k] !== 0) { + if (e[k + 1] < 0) { + e[k] = 0 - e[k]; + } + for (i = k + 1; i < n; i++) { + e[i] /= e[k]; + } + e[k + 1] += 1; + } + e[k] = -e[k]; + if ((k + 1 < m) && (e[k] !== 0)) { + for (i = k + 1; i < m; i++) { + work[i] = 0; + } + for (j = k + 1; j < n; j++) { + for (i = k + 1; i < m; i++) { + work[i] += e[j] * a[i][j]; + } + } + for (j = k + 1; j < n; j++) { + t = -e[j] / e[k + 1]; + for (i = k + 1; i < m; i++) { + a[i][j] += t * work[i]; + } + } + } + if (wantv) { + for (i = k + 1; i < n; i++) { + V[i][k] = e[i]; + } + } + } + } + + p = Math.min(n, m + 1); + if (nct < n) { + s[nct] = a[nct][nct]; + } + if (m < p) { + s[p - 1] = 0; + } + if (nrt + 1 < p) { + e[nrt] = a[nrt][p - 1]; + } + e[p - 1] = 0; + + if (wantu) { + for (j = nct; j < nu; j++) { + for (i = 0; i < m; i++) { + U[i][j] = 0; + } + U[j][j] = 1; + } + for (k = nct - 1; k >= 0; k--) { + if (s[k] !== 0) { + for (j = k + 1; j < nu; j++) { + t = 0; + for (i = k; i < m; i++) { + t += U[i][k] * U[i][j]; + } + t = -t / U[k][k]; + for (i = k; i < m; i++) { + U[i][j] += t * U[i][k]; + } + } + for (i = k; i < m; i++) { + U[i][k] = -U[i][k]; + } + U[k][k] = 1 + U[k][k]; + for (i = 0; i < k - 1; i++) { + U[i][k] = 0; + } + } else { + for (i = 0; i < m; i++) { + U[i][k] = 0; + } + U[k][k] = 1; + } + } + } + + if (wantv) { + for (k = n - 1; k >= 0; k--) { + if ((k < nrt) && (e[k] !== 0)) { + for (j = k + 1; j < n; j++) { + t = 0; + for (i = k + 1; i < n; i++) { + t += V[i][k] * V[i][j]; + } + t = -t / V[k + 1][k]; + for (i = k + 1; i < n; i++) { + V[i][j] += t * V[i][k]; + } + } + } + for (i = 0; i < n; i++) { + V[i][k] = 0; + } + V[k][k] = 1; + } + } + + var pp = p - 1, + iter = 0, + eps = Math.pow(2, -52); + while (p > 0) { + for (k = p - 2; k >= -1; k--) { + if (k === -1) { + break; + } + if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { + e[k] = 0; + break; + } + } + if (k === p - 2) { + kase = 4; + } else { + for (ks = p - 1; ks >= k; ks--) { + if (ks === k) { + break; + } + t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0); + if (Math.abs(s[ks]) <= eps * t) { + s[ks] = 0; + break; + } + } + if (ks === k) { + kase = 3; + } else if (ks === p - 1) { + kase = 1; + } else { + kase = 2; + k = ks; + } + } + + k++; + + switch (kase) { + case 1: { + f = e[p - 2]; + e[p - 2] = 0; + for (j = p - 2; j >= k; j--) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + if (j !== k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } + if (wantv) { + for (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][p - 1]; + V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; + V[i][j] = t; + } + } + } + break; + } + case 2 : { + f = e[k - 1]; + e[k - 1] = 0; + for (j = k; j < p; j++) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + f = -sn * e[j]; + e[j] = cs * e[j]; + if (wantu) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][k - 1]; + U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; + U[i][j] = t; + } + } + } + break; + } + case 3 : { + scale = Math.max(Math.max(Math.max(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])); + sp = s[p - 1] / scale; + spm1 = s[p - 2] / scale; + epm1 = e[p - 2] / scale; + sk = s[k] / scale; + ek = e[k] / scale; + b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2; + c = (sp * epm1) * (sp * epm1); + shift = 0; + if ((b !== 0) || (c !== 0)) { + shift = Math.sqrt(b * b + c); + if (b < 0) { + shift = -shift; + } + shift = c / (b + shift); + } + f = (sk + sp) * (sk - sp) + shift; + g = sk * ek; + for (j = k; j < p - 1; j++) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(f, g); + cs = f / t; + sn = g / t; + if (j !== k) { + e[j - 1] = t; + } + 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 (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][j + 1]; + V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; + V[i][j] = t; + } + } + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(f, g); + cs = f / t; + sn = g / t; + s[j] = t; + f = cs * e[j] + sn * s[j + 1]; + s[j + 1] = -sn * e[j] + cs * s[j + 1]; + g = sn * e[j + 1]; + e[j + 1] = cs * e[j + 1]; + if (wantu && (j < m - 1)) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][j + 1]; + U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; + U[i][j] = t; + } + } + } + e[p - 2] = f; + iter = iter + 1; + break; + } + case 4: { + if (s[k] <= 0) { + s[k] = (s[k] < 0 ? -s[k] : 0); + if (wantv) { + for (i = 0; i <= pp; i++) { + V[i][k] = -V[i][k]; + } + } + } + while (k < pp) { + if (s[k] >= s[k + 1]) { + break; + } + t = s[k]; + s[k] = s[k + 1]; + s[k + 1] = t; + if (wantv && (k < n - 1)) { + for (i = 0; i < n; i++) { + t = V[i][k + 1]; + V[i][k + 1] = V[i][k]; + V[i][k] = t; + } + } + if (wantu && (k < m - 1)) { + for (i = 0; i < m; i++) { + t = U[i][k + 1]; + U[i][k + 1] = U[i][k]; + U[i][k] = t; + } + } + k++; + } + iter = 0; + p--; + break; + } + // no default + } + } + + if (swapped) { + var tmp = V; + V = U; + U = tmp; + } + + this.m = m; + this.n = n; + this.s = s; + this.U = U; + this.V = V; +} + +SingularValueDecomposition.prototype = { + get condition() { + return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; + }, + get norm2() { + return this.s[0]; + }, + get rank() { + var eps = Math.pow(2, -52), + tol = Math.max(this.m, this.n) * this.s[0] * eps, + r = 0, + s = this.s; + for (var i = 0, ii = s.length; i < ii; i++) { + if (s[i] > tol) { + r++; + } + } + return r; + }, + get diagonal() { + return this.s; + }, + // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs + get threshold() { + return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0]; + }, + get leftSingularVectors() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.U)) { + this.U = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.U); + } + return this.U; + }, + get rightSingularVectors() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.V)) { + this.V = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.V); + } + return this.V; + }, + get diagonalMatrix() { + return __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].diag(this.s); + }, + solve: function (value) { + + var Y = value, + e = this.threshold, + scols = this.s.length, + Ls = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(scols, scols), + i; + + for (i = 0; i < scols; i++) { + if (Math.abs(this.s[i]) <= e) { + Ls[i][i] = 0; + } else { + Ls[i][i] = 1 / this.s[i]; + } + } + + var U = this.U; + var V = this.rightSingularVectors; + + var VL = V.mmul(Ls), + vrows = V.rows, + urows = U.length, + VLU = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(vrows, urows), + j, k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < scols; k++) { + sum += VL[i][k] * U[j][k]; + } + VLU[i][j] = sum; + } + } + + return VLU.mmul(Y); + }, + solveForDiagonal: function (value) { + return this.solve(__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].diag(value)); + }, + inverse: function () { + var V = this.V; + var e = this.threshold, + vrows = V.length, + vcols = V[0].length, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](vrows, this.s.length), + i, j; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < vcols; j++) { + if (Math.abs(this.s[j]) > e) { + X[i][j] = V[i][j] / this.s[j]; + } else { + X[i][j] = 0; + } + } + } + + var U = this.U; + + var urows = U.length, + ucols = U[0].length, + Y = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](vrows, urows), + k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < ucols; k++) { + sum += X[i][k] * U[j][k]; + } + Y[i][j] = sum; + } + } + + return Y; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (SingularValueDecomposition); + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const nearestVector = __webpack_require__(196); + +/** + * Calculates the distance matrix for a given array of points + * @ignore + * @param {Array>} data - the [x,y,z,...] points to cluster + * @param {Function} distance - Distance function to use between the points + * @return {Array>} - matrix with the distance values + */ +function calculateDistanceMatrix(data, distance) { + var distanceMatrix = new Array(data.length); + for (var i = 0; i < data.length; ++i) { + for (var j = i; j < data.length; ++j) { + if (!distanceMatrix[i]) { + distanceMatrix[i] = new Array(data.length); + } + if (!distanceMatrix[j]) { + distanceMatrix[j] = new Array(data.length); + } + const dist = distance(data[i], data[j]); + distanceMatrix[i][j] = dist; + distanceMatrix[j][i] = dist; + } + } + return distanceMatrix; +} + +/** + * Updates the cluster identifier based in the new data + * @ignore + * @param {Array>} data - the [x,y,z,...] points to cluster + * @param {Array>} centers - the K centers in format [x,y,z,...] + * @param {Array } clusterID - the cluster identifier for each data dot + * @param {Function} distance - Distance function to use between the points + * @returns {Array} the cluster identifier for each data dot + */ +function updateClusterID(data, centers, clusterID, distance) { + for (var i = 0; i < data.length; i++) { + clusterID[i] = nearestVector(centers, data[i], {distanceFunction: distance}); + } + return clusterID; +} + +/** + * Update the center values based in the new configurations of the clusters + * @ignore + * @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 + * @returns {Array} he K centers in format [x,y,z,...] + */ +function updateCenters(data, clusterID, K) { + const nDim = data[0].length; + + // creates empty centers with 0 size + var centers = new Array(K); + var centersLen = new Array(K); + for (var i = 0; i < K; i++) { + centers[i] = new Array(nDim); + centersLen[i] = 0; + for (var j = 0; j < nDim; j++) { + centers[i][j] = 0; + } + } + + // add the value for all dimensions of the point + for (var l = 0; l < data.length; l++) { + centersLen[clusterID[l]]++; + for (var dim = 0; dim < nDim; dim++) { + centers[clusterID[l]][dim] += data[l][dim]; + } + } + + // divides by length + for (var id = 0; id < K; id++) { + for (var d = 0; d < nDim; d++) { + centers[id][d] /= centersLen[id]; + } + } + 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} + */ +function converged(centers, oldCenters, distanceFunction, tolerance) { + for (var i = 0; i < centers.length; i++) { + if (distanceFunction(centers[i], oldCenters[i]) > tolerance) { + return false; + } + } + return true; +} + +exports.updateClusterID = updateClusterID; +exports.updateCenters = updateCenters; +exports.calculateDistanceMatrix = calculateDistanceMatrix; +exports.converged = converged; + + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = abstractMatrix; + +var LuDecomposition = __webpack_require__(63); +var SvDecomposition = __webpack_require__(64); +var arrayUtils = __webpack_require__(13); +var util = __webpack_require__(16); +var MatrixTransposeView = __webpack_require__(195); +var MatrixRowView = __webpack_require__(192); +var MatrixSubView = __webpack_require__(194); +var MatrixSelectionView = __webpack_require__(193); +var MatrixColumnView = __webpack_require__(189); +var MatrixFlipRowView = __webpack_require__(191); +var MatrixFlipColumnView = __webpack_require__(190); + +function abstractMatrix(superCtor) { + if (superCtor === undefined) superCtor = Object; + + /** + * Real matrix + * @class Matrix + * @param {number|Array|Matrix} nRows - Number of rows of the new matrix, + * 2D array containing the data or Matrix instance to clone + * @param {number} [nColumns] - Number of columns of the new matrix + */ + class Matrix extends superCtor { + static get [Symbol.species]() { + return this; + } + + /** + * Constructs a Matrix with the chosen dimensions from a 1D array + * @param {number} newRows - Number of rows + * @param {number} newColumns - Number of columns + * @param {Array} newData - A 1D array containing data for the matrix + * @return {Matrix} - The new matrix + */ + static from1DArray(newRows, newColumns, newData) { + var length = newRows * newColumns; + if (length !== newData.length) { + throw new RangeError('Data length does not match given dimensions'); + } + var newMatrix = new this(newRows, newColumns); + for (var row = 0; row < newRows; row++) { + for (var column = 0; column < newColumns; column++) { + newMatrix.set(row, column, newData[row * newColumns + column]); + } + } + return newMatrix; + } + + /** + * Creates a row vector, a matrix with only one row. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static rowVector(newData) { + var vector = new this(1, newData.length); + for (var i = 0; i < newData.length; i++) { + vector.set(0, i, newData[i]); + } + return vector; + } + + /** + * Creates a column vector, a matrix with only one column. + * @param {Array} newData - A 1D array containing data for the vector + * @return {Matrix} - The new matrix + */ + static columnVector(newData) { + var vector = new this(newData.length, 1); + for (var i = 0; i < newData.length; i++) { + vector.set(i, 0, newData[i]); + } + return vector; + } + + /** + * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns). + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static empty(rows, columns) { + return new this(rows, columns); + } + + /** + * Creates a matrix with the given dimensions. Values will be set to zero. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static zeros(rows, columns) { + return this.empty(rows, columns).fill(0); + } + + /** + * Creates a matrix with the given dimensions. Values will be set to one. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @return {Matrix} - The new matrix + */ + static ones(rows, columns) { + return this.empty(rows, columns).fill(1); + } + + /** + * Creates a matrix with the given dimensions. Values will be randomly set. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static rand(rows, columns, rng) { + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + matrix.set(i, j, rng()); + } + } + return matrix; + } + + /** + * Creates a matrix with the given dimensions. Values will be random integers. + * @param {number} rows - Number of rows + * @param {number} columns - Number of columns + * @param {number} [maxValue=1000] - Maximum value + * @param {function} [rng=Math.random] - Random number generator + * @return {Matrix} The new matrix + */ + static randInt(rows, columns, maxValue, rng) { + if (maxValue === undefined) maxValue = 1000; + if (rng === undefined) rng = Math.random; + var matrix = this.empty(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + var value = Math.floor(rng() * maxValue); + matrix.set(i, j, value); + } + } + return matrix; + } + + /** + * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0. + * @param {number} rows - Number of rows + * @param {number} [columns=rows] - Number of columns + * @param {number} [value=1] - Value to fill the diagonal with + * @return {Matrix} - The new identity matrix + */ + static eye(rows, columns, value) { + if (columns === undefined) columns = rows; + if (value === undefined) value = 1; + var min = Math.min(rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, value); + } + return matrix; + } + + /** + * Creates a diagonal matrix based on the given array. + * @param {Array} data - Array containing the data for the diagonal + * @param {number} [rows] - Number of rows (Default: data.length) + * @param {number} [columns] - Number of columns (Default: rows) + * @return {Matrix} - The new diagonal matrix + */ + static diag(data, rows, columns) { + var l = data.length; + if (rows === undefined) rows = l; + if (columns === undefined) columns = rows; + var min = Math.min(l, rows, columns); + var matrix = this.zeros(rows, columns); + for (var i = 0; i < min; i++) { + matrix.set(i, i, data[i]); + } + return matrix; + } + + /** + * Returns a matrix whose elements are the minimum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static min(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } + + /** + * Returns a matrix whose elements are the maximum between matrix1 and matrix2 + * @param {Matrix} matrix1 + * @param {Matrix} matrix2 + * @return {Matrix} + */ + static max(matrix1, matrix2) { + matrix1 = this.checkMatrix(matrix1); + matrix2 = this.checkMatrix(matrix2); + var rows = matrix1.rows; + var columns = matrix1.columns; + var result = new this(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); + } + } + return result; + } + + /** + * Check that the provided value is a Matrix and tries to instantiate one if not + * @param {*} value - The value to check + * @return {Matrix} + */ + static checkMatrix(value) { + return Matrix.isMatrix(value) ? value : new this(value); + } + + /** + * Returns true if the argument is a Matrix, false otherwise + * @param {*} value - The value to check + * @return {boolean} + */ + static isMatrix(value) { + return (value != null) && (value.klass === 'Matrix'); + } + + /** + * @prop {number} size - The number of elements in the matrix. + */ + get size() { + return this.rows * this.columns; + } + + /** + * Applies a callback for each element of the matrix. The function is called in the matrix (this) context. + * @param {function} callback - Function that will be called with two parameters : i (row) and j (column) + * @return {Matrix} this + */ + apply(callback) { + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); + } + var ii = this.rows; + var jj = this.columns; + for (var i = 0; i < ii; i++) { + for (var j = 0; j < jj; j++) { + callback.call(this, i, j); + } + } + return this; + } + + /** + * Returns a new 1D array filled row by row with the matrix values + * @return {Array} + */ + to1DArray() { + var array = new Array(this.size); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + array[i * this.columns + j] = this.get(i, j); + } + } + return array; + } + + /** + * Returns a 2D array containing a copy of the data + * @return {Array} + */ + to2DArray() { + var copy = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + copy[i] = new Array(this.columns); + for (var j = 0; j < this.columns; j++) { + copy[i][j] = this.get(i, j); + } + } + return copy; + } + + /** + * @return {boolean} true if the matrix has one row + */ + isRowVector() { + return this.rows === 1; + } + + /** + * @return {boolean} true if the matrix has one column + */ + isColumnVector() { + return this.columns === 1; + } + + /** + * @return {boolean} true if the matrix has one row or one column + */ + isVector() { + return (this.rows === 1) || (this.columns === 1); + } + + /** + * @return {boolean} true if the matrix has the same number of rows and columns + */ + isSquare() { + return this.rows === this.columns; + } + + /** + * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal + */ + isSymmetric() { + if (this.isSquare()) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j <= i; j++) { + if (this.get(i, j) !== this.get(j, i)) { + return false; + } + } + } + return true; + } + return false; + } + + /** + * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1 + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @param {number} value - The new value for the element + * @return {Matrix} this + */ + set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars + throw new Error('set method is unimplemented'); + } + + /** + * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4] + * @abstract + * @param {number} rowIndex - Index of the row + * @param {number} columnIndex - Index of the column + * @return {number} + */ + get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars + throw new Error('get method is unimplemented'); + } + + /** + * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of + * rows of the matrix, and colRep times the number of columns of the matrix + * @param {number} rowRep - Number of times the rows should be repeated + * @param {number} colRep - Number of times the columns should be re + * @return {Matrix} + * @example + * var matrix = new Matrix([[1,2]]); + * matrix.repeat(2); // [[1,2],[1,2]] + */ + repeat(rowRep, colRep) { + rowRep = rowRep || 1; + colRep = colRep || 1; + var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep); + for (var i = 0; i < rowRep; i++) { + for (var j = 0; j < colRep; j++) { + matrix.setSubMatrix(this, this.rows * i, this.columns * j); + } + } + return matrix; + } + + /** + * Fills the matrix with a given value. All elements will be set to this value. + * @param {number} value - New value + * @return {Matrix} this + */ + fill(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, value); + } + } + return this; + } + + /** + * Negates the matrix. All elements will be multiplied by (-1) + * @return {Matrix} this + */ + neg() { + return this.mulS(-1); + } + + /** + * Returns a new array from the given row index + * @param {number} index - Row index + * @return {Array} + */ + getRow(index) { + util.checkRowIndex(this, index); + var row = new Array(this.columns); + for (var i = 0; i < this.columns; i++) { + row[i] = this.get(index, i); + } + return row; + } + + /** + * Returns a new row vector from the given row index + * @param {number} index - Row index + * @return {Matrix} + */ + getRowVector(index) { + return this.constructor.rowVector(this.getRow(index)); + } + + /** + * Sets a row at the given index + * @param {number} index - Row index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setRow(index, array) { + util.checkRowIndex(this, index); + array = util.checkRowVector(this, array); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, array[i]); + } + return this; + } + + /** + * Swaps two rows + * @param {number} row1 - First row index + * @param {number} row2 - Second row index + * @return {Matrix} this + */ + swapRows(row1, row2) { + util.checkRowIndex(this, row1); + util.checkRowIndex(this, row2); + for (var i = 0; i < this.columns; i++) { + var temp = this.get(row1, i); + this.set(row1, i, this.get(row2, i)); + this.set(row2, i, temp); + } + return this; + } + + /** + * Returns a new array from the given column index + * @param {number} index - Column index + * @return {Array} + */ + getColumn(index) { + util.checkColumnIndex(this, index); + var column = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + column[i] = this.get(i, index); + } + return column; + } + + /** + * Returns a new column vector from the given column index + * @param {number} index - Column index + * @return {Matrix} + */ + getColumnVector(index) { + return this.constructor.columnVector(this.getColumn(index)); + } + + /** + * Sets a column at the given index + * @param {number} index - Column index + * @param {Array|Matrix} array - Array or vector + * @return {Matrix} this + */ + setColumn(index, array) { + util.checkColumnIndex(this, index); + array = util.checkColumnVector(this, array); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, array[i]); + } + return this; + } + + /** + * Swaps two columns + * @param {number} column1 - First column index + * @param {number} column2 - Second column index + * @return {Matrix} this + */ + swapColumns(column1, column2) { + util.checkColumnIndex(this, column1); + util.checkColumnIndex(this, column2); + for (var i = 0; i < this.rows; i++) { + var temp = this.get(i, column1); + this.set(i, column1, this.get(i, column2)); + this.set(i, column2, temp); + } + return this; + } + + /** + * Adds the values of a vector to each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addRowVector(vector) { + vector = util.checkRowVector(this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[j]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subRowVector(vector) { + vector = util.checkRowVector(this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[j]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each row + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulRowVector(vector) { + vector = util.checkRowVector(this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[j]); + } + } + return this; + } + + /** + * Divides the values of each row by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divRowVector(vector) { + vector = util.checkRowVector(this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[j]); + } + } + return this; + } + + /** + * Adds the values of a vector to each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + addColumnVector(vector) { + vector = util.checkColumnVector(this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + vector[i]); + } + } + return this; + } + + /** + * Subtracts the values of a vector from each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + subColumnVector(vector) { + vector = util.checkColumnVector(this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a vector with each column + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + mulColumnVector(vector) { + vector = util.checkColumnVector(this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * vector[i]); + } + } + return this; + } + + /** + * Divides the values of each column by those of a vector + * @param {Array|Matrix} vector - Array or vector + * @return {Matrix} this + */ + divColumnVector(vector) { + vector = util.checkColumnVector(this, vector); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) / vector[i]); + } + } + return this; + } + + /** + * Multiplies the values of a row with a scalar + * @param {number} index - Row index + * @param {number} value + * @return {Matrix} this + */ + mulRow(index, value) { + util.checkRowIndex(this, index); + for (var i = 0; i < this.columns; i++) { + this.set(index, i, this.get(index, i) * value); + } + return this; + } + + /** + * Multiplies the values of a column with a scalar + * @param {number} index - Column index + * @param {number} value + * @return {Matrix} this + */ + mulColumn(index, value) { + util.checkColumnIndex(this, index); + for (var i = 0; i < this.rows; i++) { + this.set(i, index, this.get(i, index) * value); + } + return this; + } + + /** + * Returns the maximum value of the matrix + * @return {number} + */ + max() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the maximum value + * @return {Array} + */ + maxIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) > v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the minimum value of the matrix + * @return {number} + */ + min() { + var v = this.get(0, 0); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + } + } + } + return v; + } + + /** + * Returns the index of the minimum value + * @return {Array} + */ + minIndex() { + var v = this.get(0, 0); + var idx = [0, 0]; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + if (this.get(i, j) < v) { + v = this.get(i, j); + idx[0] = i; + idx[1] = j; + } + } + } + return idx; + } + + /** + * Returns the maximum value of one row + * @param {number} row - Row index + * @return {number} + */ + maxRow(row) { + util.checkRowIndex(this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + maxRowIndex(row) { + util.checkRowIndex(this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) > v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one row + * @param {number} row - Row index + * @return {number} + */ + minRow(row) { + util.checkRowIndex(this, row); + var v = this.get(row, 0); + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one row + * @param {number} row - Row index + * @return {Array} + */ + minRowIndex(row) { + util.checkRowIndex(this, row); + var v = this.get(row, 0); + var idx = [row, 0]; + for (var i = 1; i < this.columns; i++) { + if (this.get(row, i) < v) { + v = this.get(row, i); + idx[1] = i; + } + } + return idx; + } + + /** + * Returns the maximum value of one column + * @param {number} column - Column index + * @return {number} + */ + maxColumn(column) { + util.checkColumnIndex(this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the maximum value of one column + * @param {number} column - Column index + * @return {Array} + */ + maxColumnIndex(column) { + util.checkColumnIndex(this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) > v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns the minimum value of one column + * @param {number} column - Column index + * @return {number} + */ + minColumn(column) { + util.checkColumnIndex(this, column); + var v = this.get(0, column); + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + } + } + return v; + } + + /** + * Returns the index of the minimum value of one column + * @param {number} column - Column index + * @return {Array} + */ + minColumnIndex(column) { + util.checkColumnIndex(this, column); + var v = this.get(0, column); + var idx = [0, column]; + for (var i = 1; i < this.rows; i++) { + if (this.get(i, column) < v) { + v = this.get(i, column); + idx[0] = i; + } + } + return idx; + } + + /** + * Returns an array containing the diagonal values of the matrix + * @return {Array} + */ + diag() { + var min = Math.min(this.rows, this.columns); + var diag = new Array(min); + for (var i = 0; i < min; i++) { + diag[i] = this.get(i, i); + } + return diag; + } + + /** + * Returns the sum by the argument given, if no argument given, + * it returns the sum of all elements of the matrix. + * @param {string} by - sum by 'row' or 'column'. + * @return {Matrix|number} + */ + sum(by) { + switch (by) { + case 'row': + return util.sumByRow(this); + case 'column': + return util.sumByColumn(this); + default: + return util.sumAll(this); + } + } + + /** + * Returns the mean of all elements of the matrix + * @return {number} + */ + mean() { + return this.sum() / this.size; + } + + /** + * Returns the product of all elements of the matrix + * @return {number} + */ + prod() { + var prod = 1; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + prod *= this.get(i, j); + } + } + return prod; + } + + /** + * Computes the cumulative sum of the matrix elements (in place, row by row) + * @return {Matrix} this + */ + cumulativeSum() { + var sum = 0; + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + sum += this.get(i, j); + this.set(i, j, sum); + } + } + return this; + } + + /** + * Computes the dot (scalar) product between the matrix and another + * @param {Matrix} vector2 vector + * @return {number} + */ + dot(vector2) { + if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); + var vector1 = this.to1DArray(); + if (vector1.length !== vector2.length) { + throw new RangeError('vectors do not have the same size'); + } + var dot = 0; + for (var i = 0; i < vector1.length; i++) { + dot += vector1[i] * vector2[i]; + } + return dot; + } + + /** + * Returns the matrix product between this and other + * @param {Matrix} other + * @return {Matrix} + */ + mmul(other) { + other = this.constructor.checkMatrix(other); + if (this.columns !== other.rows) { + // eslint-disable-next-line no-console + console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); + } + + var m = this.rows; + var n = this.columns; + var p = other.columns; + + var result = new this.constructor[Symbol.species](m, p); + + var Bcolj = new Array(n); + for (var j = 0; j < p; j++) { + for (var k = 0; k < n; k++) { + Bcolj[k] = other.get(k, j); + } + + for (var i = 0; i < m; i++) { + var s = 0; + for (k = 0; k < n; k++) { + s += this.get(i, k) * Bcolj[k]; + } + + result.set(i, j, s); + } + } + return result; + } + + strassen2x2(other) { + var result = new this.constructor[Symbol.species](2, 2); + const a11 = this.get(0, 0); + const b11 = other.get(0, 0); + const a12 = this.get(0, 1); + const b12 = other.get(0, 1); + const a21 = this.get(1, 0); + const b21 = other.get(1, 0); + const a22 = this.get(1, 1); + const b22 = other.get(1, 1); + + // Compute intermediate values. + const m1 = (a11 + a22) * (b11 + b22); + const m2 = (a21 + a22) * b11; + const m3 = a11 * (b12 - b22); + const m4 = a22 * (b21 - b11); + const m5 = (a11 + a12) * b22; + const m6 = (a21 - a11) * (b11 + b12); + const m7 = (a12 - a22) * (b21 + b22); + + // Combine intermediate values into the output. + const c00 = m1 + m4 - m5 + m7; + const c01 = m3 + m5; + const c10 = m2 + m4; + const c11 = m1 - m2 + m3 + m6; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(1, 0, c10); + result.set(1, 1, c11); + return result; + } + + strassen3x3(other) { + var result = new this.constructor[Symbol.species](3, 3); + + const a00 = this.get(0, 0); + const a01 = this.get(0, 1); + const a02 = this.get(0, 2); + const a10 = this.get(1, 0); + const a11 = this.get(1, 1); + const a12 = this.get(1, 2); + const a20 = this.get(2, 0); + const a21 = this.get(2, 1); + const a22 = this.get(2, 2); + + const b00 = other.get(0, 0); + const b01 = other.get(0, 1); + const b02 = other.get(0, 2); + const b10 = other.get(1, 0); + const b11 = other.get(1, 1); + const b12 = other.get(1, 2); + const b20 = other.get(2, 0); + const b21 = other.get(2, 1); + const b22 = other.get(2, 2); + + const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11; + const m2 = (a00 - a10) * (-b01 + b11); + const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22); + const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11); + const m5 = (a10 + a11) * (-b00 + b01); + const m6 = a00 * b00; + const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12); + const m8 = (-a00 + a20) * (b02 - b12); + const m9 = (a20 + a21) * (-b00 + b02); + const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12; + const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21); + const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21); + const m13 = (a02 - a22) * (b11 - b21); + const m14 = a02 * b20; + const m15 = (a21 + a22) * (-b20 + b21); + const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22); + const m17 = (a02 - a12) * (b12 - b22); + const m18 = (a11 + a12) * (-b20 + b22); + const m19 = a01 * b10; + const m20 = a12 * b21; + const m21 = a10 * b02; + const m22 = a20 * b01; + const m23 = a22 * b22; + + const c00 = m6 + m14 + m19; + const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15; + const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18; + const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17; + const c11 = m2 + m4 + m5 + m6 + m20; + const c12 = m14 + m16 + m17 + m18 + m21; + const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14; + const c21 = m12 + m13 + m14 + m15 + m22; + const c22 = m6 + m7 + m8 + m9 + m23; + + result.set(0, 0, c00); + result.set(0, 1, c01); + result.set(0, 2, c02); + result.set(1, 0, c10); + result.set(1, 1, c11); + result.set(1, 2, c12); + result.set(2, 0, c20); + result.set(2, 1, c21); + result.set(2, 2, c22); + return result; + } + + /** + * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000. + * @param {Matrix} y + * @return {Matrix} + */ + mmulStrassen(y) { + var x = this.clone(); + var r1 = x.rows; + var c1 = x.columns; + var r2 = y.rows; + var c2 = y.columns; + if (c1 !== r2) { + // eslint-disable-next-line no-console + console.warn(`Multiplying ${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. + function embed(mat, rows, cols) { + var r = mat.rows; + var c = mat.columns; + if ((r === rows) && (c === cols)) { + return mat; + } else { + var resultat = Matrix.zeros(rows, cols); + resultat = resultat.setSubMatrix(mat, 0, 0); + return resultat; + } + } + + + // Make sure both matrices are the same size. + // This is exclusively for simplicity: + // this algorithm can be implemented with matrices of different sizes. + + var r = Math.max(r1, r2); + var c = Math.max(c1, c2); + x = embed(x, r, c); + y = embed(y, r, c); + + // Our recursive multiplication function. + function blockMult(a, b, rows, cols) { + // For small matrices, resort to naive multiplication. + if (rows <= 512 || cols <= 512) { + return a.mmul(b); // a is equivalent to this + } + + // Apply dynamic padding. + if ((rows % 2 === 1) && (cols % 2 === 1)) { + a = embed(a, rows + 1, cols + 1); + b = embed(b, rows + 1, cols + 1); + } else if (rows % 2 === 1) { + a = embed(a, rows + 1, cols); + b = embed(b, rows + 1, cols); + } else if (cols % 2 === 1) { + a = embed(a, rows, cols + 1); + b = embed(b, rows, cols + 1); + } + + var halfRows = parseInt(a.rows / 2); + var halfCols = parseInt(a.columns / 2); + // Subdivide input matrices. + var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); + var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); + + var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); + var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); + + var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); + var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); + + var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); + var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); + + // Compute intermediate values. + var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols); + var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols); + var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols); + var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols); + var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols); + var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols); + var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); + + // Combine intermediate values into the output. + var c11 = Matrix.add(m1, m4); + c11.sub(m5); + c11.add(m7); + var c12 = Matrix.add(m3, m5); + var c21 = Matrix.add(m2, m4); + var c22 = Matrix.sub(m1, m2); + c22.add(m3); + c22.add(m6); + + //Crop output to the desired size (undo dynamic padding). + var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns); + resultat = resultat.setSubMatrix(c11, 0, 0); + resultat = resultat.setSubMatrix(c12, c11.rows, 0); + resultat = resultat.setSubMatrix(c21, 0, c11.columns); + resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns); + return resultat.subMatrix(0, rows - 1, 0, cols - 1); + } + return blockMult(x, y, r, c); + } + + /** + * Returns a row-by-row scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The scaled matrix + */ + scaleRows(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.rows; i++) { + var scaled = arrayUtils.scale(this.getRow(i), {min, max}); + newMatrix.setRow(i, scaled); + } + return newMatrix; + } + + /** + * Returns a new column-by-column scaled matrix + * @param {number} [min=0] - Minimum scaled value + * @param {number} [max=1] - Maximum scaled value + * @return {Matrix} - The new scaled matrix + * @example + * var matrix = new Matrix([[1,2],[-1,0]]); + * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]] + */ + scaleColumns(min, max) { + min = min === undefined ? 0 : min; + max = max === undefined ? 1 : max; + if (min >= max) { + throw new RangeError('min should be strictly smaller than max'); + } + var newMatrix = this.constructor.empty(this.rows, this.columns); + for (var i = 0; i < this.columns; i++) { + var scaled = arrayUtils.scale(this.getColumn(i), { + min: min, + max: max + }); + newMatrix.setColumn(i, scaled); + } + return newMatrix; + } + + + /** + * Returns the Kronecker product (also known as tensor product) between this and other + * See https://en.wikipedia.org/wiki/Kronecker_product + * @param {Matrix} other + * @return {Matrix} + */ + kroneckerProduct(other) { + other = this.constructor.checkMatrix(other); + + var m = this.rows; + var n = this.columns; + var p = other.rows; + var q = other.columns; + + var result = new this.constructor[Symbol.species](m * p, n * q); + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + for (var k = 0; k < p; k++) { + for (var l = 0; l < q; l++) { + result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l); + } + } + } + } + return result; + } + + /** + * Transposes the matrix and returns a new one containing the result + * @return {Matrix} + */ + transpose() { + var result = new this.constructor[Symbol.species](this.columns, this.rows); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + result.set(j, i, this.get(i, j)); + } + } + return result; + } + + /** + * Sorts the rows (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortRows(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.rows; i++) { + this.setRow(i, this.getRow(i).sort(compareFunction)); + } + return this; + } + + /** + * Sorts the columns (in place) + * @param {function} compareFunction - usual Array.prototype.sort comparison function + * @return {Matrix} this + */ + sortColumns(compareFunction) { + if (compareFunction === undefined) compareFunction = compareNumbers; + for (var i = 0; i < this.columns; i++) { + this.setColumn(i, this.getColumn(i).sort(compareFunction)); + } + return this; + } + + /** + * Returns a subset of the matrix + * @param {number} startRow - First row index + * @param {number} endRow - Last row index + * @param {number} startColumn - First column index + * @param {number} endColumn - Last column index + * @return {Matrix} + */ + subMatrix(startRow, endRow, startColumn, endColumn) { + util.checkRange(this, startRow, endRow, startColumn, endColumn); + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1); + for (var i = startRow; i <= endRow; i++) { + for (var j = startColumn; j <= endColumn; j++) { + newMatrix[i - startRow][j - startColumn] = this.get(i, j); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of row indices + * @param {Array} indices - Array containing the row indices + * @param {number} [startColumn = 0] - First column index + * @param {number} [endColumn = this.columns-1] - Last column index + * @return {Matrix} + */ + subMatrixRow(indices, startColumn, endColumn) { + if (startColumn === undefined) startColumn = 0; + if (endColumn === undefined) endColumn = this.columns - 1; + if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1); + for (var i = 0; i < indices.length; i++) { + for (var j = startColumn; j <= endColumn; j++) { + if (indices[i] < 0 || indices[i] >= this.rows) { + throw new RangeError('Row index out of range: ' + indices[i]); + } + newMatrix.set(i, j - startColumn, this.get(indices[i], j)); + } + } + return newMatrix; + } + + /** + * Returns a subset of the matrix based on an array of column indices + * @param {Array} indices - Array containing the column indices + * @param {number} [startRow = 0] - First row index + * @param {number} [endRow = this.rows-1] - Last row index + * @return {Matrix} + */ + subMatrixColumn(indices, startRow, endRow) { + if (startRow === undefined) startRow = 0; + if (endRow === undefined) endRow = this.rows - 1; + if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) { + throw new RangeError('Argument out of range'); + } + + var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length); + for (var i = 0; i < indices.length; i++) { + for (var j = startRow; j <= endRow; j++) { + if (indices[i] < 0 || indices[i] >= this.columns) { + throw new RangeError('Column index out of range: ' + indices[i]); + } + newMatrix.set(j - startRow, i, this.get(j, indices[i])); + } + } + return newMatrix; + } + + /** + * Set a part of the matrix to the given sub-matrix + * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values. + * @param {number} startRow - The index of the first row to set + * @param {number} startColumn - The index of the first column to set + * @return {Matrix} + */ + setSubMatrix(matrix, startRow, startColumn) { + matrix = this.constructor.checkMatrix(matrix); + var endRow = startRow + matrix.rows - 1; + var endColumn = startColumn + matrix.columns - 1; + util.checkRange(this, startRow, endRow, startColumn, endColumn); + for (var i = 0; i < matrix.rows; i++) { + for (var j = 0; j < matrix.columns; j++) { + this[startRow + i][startColumn + j] = matrix.get(i, j); + } + } + return this; + } + + /** + * Return a new matrix based on a selection of rows and columns + * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once. + * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once. + * @return {Matrix} The new matrix + */ + selection(rowIndices, columnIndices) { + var indices = util.checkIndices(this, rowIndices, columnIndices); + var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length); + for (var i = 0; i < indices.row.length; i++) { + var rowIndex = indices.row[i]; + for (var j = 0; j < indices.column.length; j++) { + var columnIndex = indices.column[j]; + newMatrix[i][j] = this.get(rowIndex, columnIndex); + } + } + return newMatrix; + } + + /** + * Returns the trace of the matrix (sum of the diagonal elements) + * @return {number} + */ + trace() { + var min = Math.min(this.rows, this.columns); + var trace = 0; + for (var i = 0; i < min; i++) { + trace += this.get(i, i); + } + return trace; + } + + /* + Matrix views + */ + + /** + * Returns a view of the transposition of the matrix + * @return {MatrixTransposeView} + */ + transposeView() { + return new MatrixTransposeView(this); + } + + /** + * Returns a view of the row vector with the given index + * @param {number} row - row index of the vector + * @return {MatrixRowView} + */ + rowView(row) { + util.checkRowIndex(this, row); + return new MatrixRowView(this, row); + } + + /** + * Returns a view of the column vector with the given index + * @param {number} column - column index of the vector + * @return {MatrixColumnView} + */ + columnView(column) { + util.checkColumnIndex(this, column); + return new MatrixColumnView(this, column); + } + + /** + * Returns a view of the matrix flipped in the row axis + * @return {MatrixFlipRowView} + */ + flipRowView() { + return new MatrixFlipRowView(this); + } + + /** + * Returns a view of the matrix flipped in the column axis + * @return {MatrixFlipColumnView} + */ + flipColumnView() { + return new MatrixFlipColumnView(this); + } + + /** + * Returns a view of a submatrix giving the index boundaries + * @param {number} startRow - first row index of the submatrix + * @param {number} endRow - last row index of the submatrix + * @param {number} startColumn - first column index of the submatrix + * @param {number} endColumn - last column index of the submatrix + * @return {MatrixSubView} + */ + subMatrixView(startRow, endRow, startColumn, endColumn) { + return new MatrixSubView(this, startRow, endRow, startColumn, endColumn); + } + + /** + * Returns a view of the cross of the row indices and the column indices + * @example + * // resulting vector is [[2], [2]] + * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1]) + * @param {Array} rowIndices + * @param {Array} columnIndices + * @return {MatrixSelectionView} + */ + selectionView(rowIndices, columnIndices) { + return new MatrixSelectionView(this, rowIndices, columnIndices); + } + + + /** + * Calculates and returns the determinant of a matrix as a Number + * @example + * new Matrix([[1,2,3], [4,5,6]]).det() + * @return {number} + */ + det() { + if (this.isSquare()) { + var a, b, c, d; + if (this.columns === 2) { + // 2 x 2 matrix + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(1, 0); + d = this.get(1, 1); + + return a * d - (b * c); + } else if (this.columns === 3) { + // 3 x 3 matrix + var subMatrix0, subMatrix1, subMatrix2; + subMatrix0 = this.selectionView([1, 2], [1, 2]); + subMatrix1 = this.selectionView([1, 2], [0, 2]); + subMatrix2 = this.selectionView([1, 2], [0, 1]); + a = this.get(0, 0); + b = this.get(0, 1); + c = this.get(0, 2); + + return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det(); + } else { + // general purpose determinant using the LU decomposition + return new LuDecomposition(this).determinant; + } + + } else { + throw Error('Determinant can only be calculated for a square matrix.'); + } + } + + /** + * Returns inverse of a matrix if it exists or the pseudoinverse + * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15) + * @return {Matrix} the (pseudo)inverted matrix. + */ + pseudoInverse(threshold) { + if (threshold === undefined) threshold = Number.EPSILON; + var svdSolution = new SvDecomposition(this, {autoTranspose: true}); + + var U = svdSolution.leftSingularVectors; + var V = svdSolution.rightSingularVectors; + var s = svdSolution.diagonal; + + for (var i = 0; i < s.length; i++) { + if (Math.abs(s[i]) > threshold) { + s[i] = 1.0 / s[i]; + } else { + s[i] = 0.0; + } + } + + // convert list to diagonal + s = this.constructor[Symbol.species].diag(s); + return V.mmul(s.mmul(U.transposeView())); + } + } + + Matrix.prototype.klass = 'Matrix'; + + /** + * @private + * Check that two matrices have the same dimensions + * @param {Matrix} matrix + * @param {Matrix} otherMatrix + */ + function checkDimensions(matrix, otherMatrix) { // eslint-disable-line no-unused-vars + if (matrix.rows !== otherMatrix.rows || + matrix.columns !== otherMatrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + } + + function compareNumbers(a, b) { + return a - b; + } + + /* + Synonyms + */ + + Matrix.random = Matrix.rand; + Matrix.diagonal = Matrix.diag; + Matrix.prototype.diagonal = Matrix.prototype.diag; + Matrix.identity = Matrix.eye; + Matrix.prototype.negate = Matrix.prototype.neg; + Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct; + Matrix.prototype.determinant = Matrix.prototype.det; + + /* + Add dynamically instance and static methods for mathematical operations + */ + + var inplaceOperator = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var inplaceOperatorScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% value); + } + } + return this; +}) +`; + + var inplaceOperatorMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + checkDimensions(this, matrix); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); + } + } + return this; +}) +`; + + var staticOperator = ` +(function %name%(matrix, value) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(value); +}) +`; + + var inplaceMethod = ` +(function %name%() { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j))); + } + } + return this; +}) +`; + + var staticMethod = ` +(function %name%(matrix) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(); +}) +`; + + var inplaceMethodWithArgs = ` +(function %name%(%args%) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), %args%)); + } + } + return this; +}) +`; + + var staticMethodWithArgs = ` +(function %name%(matrix, %args%) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(%args%); +}) +`; + + + var inplaceMethodWithOneArgScalar = ` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), value)); + } + } + return this; +}) +`; + var inplaceMethodWithOneArgMatrix = ` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + checkDimensions(this, matrix); + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); + } + } + return this; +}) +`; + + var inplaceMethodWithOneArg = ` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`; + + var staticMethodWithOneArg = staticMethodWithArgs; + + var operators = [ + // Arithmetic operators + ['+', 'add'], + ['-', 'sub', 'subtract'], + ['*', 'mul', 'multiply'], + ['/', 'div', 'divide'], + ['%', 'mod', 'modulus'], + // Bitwise operators + ['&', 'and'], + ['|', 'or'], + ['^', 'xor'], + ['<<', 'leftShift'], + ['>>', 'signPropagatingRightShift'], + ['>>>', 'rightShift', 'zeroFillRightShift'] + ]; + + var i; + + for (var operator of operators) { + var inplaceOp = eval(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]})); + var inplaceOpS = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]})); + var inplaceOpM = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]})); + var staticOp = eval(fillTemplateFunction(staticOperator, {name: operator[1]})); + for (i = 1; i < operator.length; i++) { + Matrix.prototype[operator[i]] = inplaceOp; + Matrix.prototype[operator[i] + 'S'] = inplaceOpS; + Matrix.prototype[operator[i] + 'M'] = inplaceOpM; + Matrix[operator[i]] = staticOp; + } + } + + 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]); + }); + + for (var method of methods) { + var inplaceMeth = eval(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]})); + var staticMeth = eval(fillTemplateFunction(staticMethod, {name: method[1]})); + for (i = 1; i < method.length; i++) { + Matrix.prototype[method[i]] = inplaceMeth; + Matrix[method[i]] = staticMeth; + } + } + + var methodsWithArgs = [ + ['Math.pow', 1, 'pow'] + ]; + + for (var methodWithArg of methodsWithArgs) { + var args = 'arg0'; + for (i = 1; i < methodWithArg[1]; i++) { + args += `, arg${i}`; + } + if (methodWithArg[1] !== 1) { + var inplaceMethWithArgs = eval(fillTemplateFunction(inplaceMethodWithArgs, { + name: methodWithArg[2], + method: methodWithArg[0], + args: args + })); + var staticMethWithArgs = eval(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args})); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs; + Matrix[methodWithArg[i]] = staticMethWithArgs; + } + } else { + var tmplVar = { + name: methodWithArg[2], + args: args, + method: methodWithArg[0] + }; + var inplaceMethod2 = eval(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar)); + var inplaceMethodS = eval(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar)); + var inplaceMethodM = eval(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar)); + var staticMethod2 = eval(fillTemplateFunction(staticMethodWithOneArg, tmplVar)); + for (i = 2; i < methodWithArg.length; i++) { + Matrix.prototype[methodWithArg[i]] = inplaceMethod2; + Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM; + Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS; + Matrix[methodWithArg[i]] = staticMethod2; + } + } + } + + function fillTemplateFunction(template, values) { + for (var value in values) { + template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]); + } + return template; + } + + return Matrix; +} + + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Matrix = __webpack_require__(4); + +// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs +function LuDecomposition(matrix) { + if (!(this instanceof LuDecomposition)) { + return new LuDecomposition(matrix); + } + + matrix = Matrix.Matrix.checkMatrix(matrix); + + var lu = matrix.clone(), + rows = lu.rows, + columns = lu.columns, + pivotVector = new Array(rows), + pivotSign = 1, + i, j, k, p, s, t, v, + LUrowi, LUcolj, kmax; + + for (i = 0; i < rows; i++) { + pivotVector[i] = i; + } + + LUcolj = new Array(rows); + + for (j = 0; j < columns; j++) { + + for (i = 0; i < rows; i++) { + LUcolj[i] = lu[i][j]; + } + + for (i = 0; i < rows; i++) { + LUrowi = lu[i]; + kmax = Math.min(i, j); + s = 0; + for (k = 0; k < kmax; k++) { + s += LUrowi[k] * LUcolj[k]; + } + LUrowi[j] = LUcolj[i] -= s; + } + + 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[p][k]; + lu[p][k] = lu[j][k]; + lu[j][k] = t; + } + + v = pivotVector[p]; + pivotVector[p] = pivotVector[j]; + pivotVector[j] = v; + + pivotSign = -pivotSign; + } + + if (j < rows && lu[j][j] !== 0) { + for (i = j + 1; i < rows; i++) { + lu[i][j] /= lu[j][j]; + } + } + } + + this.LU = lu; + this.pivotVector = pivotVector; + this.pivotSign = pivotSign; +} + +LuDecomposition.prototype = { + isSingular: function () { + var data = this.LU, + col = data.columns; + for (var j = 0; j < col; j++) { + if (data[j][j] === 0) { + return true; + } + } + return false; + }, + get determinant() { + var data = this.LU; + if (!data.isSquare()) { + throw new Error('Matrix must be square'); + } + var determinant = this.pivotSign, col = data.columns; + for (var j = 0; j < col; j++) { + determinant *= data[j][j]; + } + return determinant; + }, + get lowerTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new Matrix.Matrix(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i > j) { + X[i][j] = data[i][j]; + } else if (i === j) { + X[i][j] = 1; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get upperTriangularMatrix() { + var data = this.LU, + rows = data.rows, + columns = data.columns, + X = new Matrix.Matrix(rows, columns); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + if (i <= j) { + X[i][j] = data[i][j]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get pivotPermutationVector() { + return this.pivotVector.slice(); + }, + solve: function (value) { + value = Matrix.Matrix.checkMatrix(value); + + var lu = this.LU, + rows = lu.rows; + + if (rows !== value.rows) { + throw new Error('Invalid matrix dimensions'); + } + if (this.isSingular()) { + throw new Error('LU matrix is singular'); + } + + var count = value.columns; + var X = value.subMatrixRow(this.pivotVector, 0, count - 1); + var columns = lu.columns; + var i, j, k; + + for (k = 0; k < columns; k++) { + for (i = k + 1; i < columns; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + for (k = columns - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= lu[k][k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * lu[i][k]; + } + } + } + return X; + } +}; + +module.exports = LuDecomposition; + + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Matrix = __webpack_require__(4); +var util = __webpack_require__(26); +var hypotenuse = util.hypotenuse; +var getFilled2DArray = util.getFilled2DArray; + +// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs +function SingularValueDecomposition(value, options) { + if (!(this instanceof SingularValueDecomposition)) { + return new SingularValueDecomposition(value, options); + } + value = Matrix.Matrix.checkMatrix(value); + + options = options || {}; + + var m = value.rows, + n = value.columns, + nu = Math.min(m, n); + + var wantu = true, wantv = true; + if (options.computeLeftSingularVectors === false) wantu = false; + if (options.computeRightSingularVectors === false) wantv = false; + var autoTranspose = options.autoTranspose === true; + + var swapped = false; + var a; + if (m < n) { + if (!autoTranspose) { + a = value.clone(); + // eslint-disable-next-line no-console + console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'); + } else { + a = value.transpose(); + m = a.rows; + n = a.columns; + swapped = true; + var aux = wantu; + wantu = wantv; + wantv = aux; + } + } else { + a = value.clone(); + } + + var s = new Array(Math.min(m + 1, n)), + U = getFilled2DArray(m, nu, 0), + V = getFilled2DArray(n, n, 0), + e = new Array(n), + work = new Array(m); + + var nct = Math.min(m - 1, n); + var nrt = Math.max(0, Math.min(n - 2, m)); + + var i, j, k, p, t, ks, f, cs, sn, max, kase, + scale, sp, spm1, epm1, sk, ek, b, c, shift, g; + + for (k = 0, max = Math.max(nct, nrt); k < max; k++) { + if (k < nct) { + s[k] = 0; + for (i = k; i < m; i++) { + s[k] = hypotenuse(s[k], a[i][k]); + } + if (s[k] !== 0) { + if (a[k][k] < 0) { + s[k] = -s[k]; + } + for (i = k; i < m; i++) { + a[i][k] /= s[k]; + } + a[k][k] += 1; + } + s[k] = -s[k]; + } + + for (j = k + 1; j < n; j++) { + if ((k < nct) && (s[k] !== 0)) { + t = 0; + for (i = k; i < m; i++) { + t += a[i][k] * a[i][j]; + } + t = -t / a[k][k]; + for (i = k; i < m; i++) { + a[i][j] += t * a[i][k]; + } + } + e[j] = a[k][j]; + } + + if (wantu && (k < nct)) { + for (i = k; i < m; i++) { + U[i][k] = a[i][k]; + } + } + + if (k < nrt) { + e[k] = 0; + for (i = k + 1; i < n; i++) { + e[k] = hypotenuse(e[k], e[i]); + } + if (e[k] !== 0) { + if (e[k + 1] < 0) { + e[k] = 0 - e[k]; + } + for (i = k + 1; i < n; i++) { + e[i] /= e[k]; + } + e[k + 1] += 1; + } + e[k] = -e[k]; + if ((k + 1 < m) && (e[k] !== 0)) { + for (i = k + 1; i < m; i++) { + work[i] = 0; + } + for (j = k + 1; j < n; j++) { + for (i = k + 1; i < m; i++) { + work[i] += e[j] * a[i][j]; + } + } + for (j = k + 1; j < n; j++) { + t = -e[j] / e[k + 1]; + for (i = k + 1; i < m; i++) { + a[i][j] += t * work[i]; + } + } + } + if (wantv) { + for (i = k + 1; i < n; i++) { + V[i][k] = e[i]; + } + } + } + } + + p = Math.min(n, m + 1); + if (nct < n) { + s[nct] = a[nct][nct]; + } + if (m < p) { + s[p - 1] = 0; + } + if (nrt + 1 < p) { + e[nrt] = a[nrt][p - 1]; + } + e[p - 1] = 0; + + if (wantu) { + for (j = nct; j < nu; j++) { + for (i = 0; i < m; i++) { + U[i][j] = 0; + } + U[j][j] = 1; + } + for (k = nct - 1; k >= 0; k--) { + if (s[k] !== 0) { + for (j = k + 1; j < nu; j++) { + t = 0; + for (i = k; i < m; i++) { + t += U[i][k] * U[i][j]; + } + t = -t / U[k][k]; + for (i = k; i < m; i++) { + U[i][j] += t * U[i][k]; + } + } + for (i = k; i < m; i++) { + U[i][k] = -U[i][k]; + } + U[k][k] = 1 + U[k][k]; + for (i = 0; i < k - 1; i++) { + U[i][k] = 0; + } + } else { + for (i = 0; i < m; i++) { + U[i][k] = 0; + } + U[k][k] = 1; + } + } + } + + if (wantv) { + for (k = n - 1; k >= 0; k--) { + if ((k < nrt) && (e[k] !== 0)) { + for (j = k + 1; j < n; j++) { + t = 0; + for (i = k + 1; i < n; i++) { + t += V[i][k] * V[i][j]; + } + t = -t / V[k + 1][k]; + for (i = k + 1; i < n; i++) { + V[i][j] += t * V[i][k]; + } + } + } + for (i = 0; i < n; i++) { + V[i][k] = 0; + } + V[k][k] = 1; + } + } + + var pp = p - 1, + iter = 0, + eps = Math.pow(2, -52); + while (p > 0) { + for (k = p - 2; k >= -1; k--) { + if (k === -1) { + break; + } + if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { + e[k] = 0; + break; + } + } + if (k === p - 2) { + kase = 4; + } else { + for (ks = p - 1; ks >= k; ks--) { + if (ks === k) { + break; + } + t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0); + if (Math.abs(s[ks]) <= eps * t) { + s[ks] = 0; + break; + } + } + if (ks === k) { + kase = 3; + } else if (ks === p - 1) { + kase = 1; + } else { + kase = 2; + k = ks; + } + } + + k++; + + switch (kase) { + case 1: { + f = e[p - 2]; + e[p - 2] = 0; + for (j = p - 2; j >= k; j--) { + t = hypotenuse(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + if (j !== k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } + if (wantv) { + for (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][p - 1]; + V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; + V[i][j] = t; + } + } + } + break; + } + case 2 : { + f = e[k - 1]; + e[k - 1] = 0; + for (j = k; j < p; j++) { + t = hypotenuse(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + f = -sn * e[j]; + e[j] = cs * e[j]; + if (wantu) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][k - 1]; + U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; + U[i][j] = t; + } + } + } + break; + } + case 3 : { + scale = Math.max(Math.max(Math.max(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])); + sp = s[p - 1] / scale; + spm1 = s[p - 2] / scale; + epm1 = e[p - 2] / scale; + sk = s[k] / scale; + ek = e[k] / scale; + b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2; + c = (sp * epm1) * (sp * epm1); + shift = 0; + if ((b !== 0) || (c !== 0)) { + shift = Math.sqrt(b * b + c); + if (b < 0) { + shift = -shift; + } + shift = c / (b + shift); + } + f = (sk + sp) * (sk - sp) + shift; + g = sk * ek; + for (j = k; j < p - 1; j++) { + t = hypotenuse(f, g); + cs = f / t; + sn = g / t; + if (j !== k) { + e[j - 1] = t; + } + 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 (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][j + 1]; + V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; + V[i][j] = t; + } + } + t = hypotenuse(f, g); + cs = f / t; + sn = g / t; + s[j] = t; + f = cs * e[j] + sn * s[j + 1]; + s[j + 1] = -sn * e[j] + cs * s[j + 1]; + g = sn * e[j + 1]; + e[j + 1] = cs * e[j + 1]; + if (wantu && (j < m - 1)) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][j + 1]; + U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; + U[i][j] = t; + } + } + } + e[p - 2] = f; + iter = iter + 1; + break; + } + case 4: { + if (s[k] <= 0) { + s[k] = (s[k] < 0 ? -s[k] : 0); + if (wantv) { + for (i = 0; i <= pp; i++) { + V[i][k] = -V[i][k]; + } + } + } + while (k < pp) { + if (s[k] >= s[k + 1]) { + break; + } + t = s[k]; + s[k] = s[k + 1]; + s[k + 1] = t; + if (wantv && (k < n - 1)) { + for (i = 0; i < n; i++) { + t = V[i][k + 1]; + V[i][k + 1] = V[i][k]; + V[i][k] = t; + } + } + if (wantu && (k < m - 1)) { + for (i = 0; i < m; i++) { + t = U[i][k + 1]; + U[i][k + 1] = U[i][k]; + U[i][k] = t; + } + } + k++; + } + iter = 0; + p--; + break; + } + // no default + } + } + + if (swapped) { + var tmp = V; + V = U; + U = tmp; + } + + this.m = m; + this.n = n; + this.s = s; + this.U = U; + this.V = V; +} + +SingularValueDecomposition.prototype = { + get condition() { + return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; + }, + get norm2() { + return this.s[0]; + }, + get rank() { + var eps = Math.pow(2, -52), + tol = Math.max(this.m, this.n) * this.s[0] * eps, + r = 0, + s = this.s; + for (var i = 0, ii = s.length; i < ii; i++) { + if (s[i] > tol) { + r++; + } + } + return r; + }, + get diagonal() { + return this.s; + }, + // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs + get threshold() { + return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0]; + }, + get leftSingularVectors() { + if (!Matrix.Matrix.isMatrix(this.U)) { + this.U = new Matrix.Matrix(this.U); + } + return this.U; + }, + get rightSingularVectors() { + if (!Matrix.Matrix.isMatrix(this.V)) { + this.V = new Matrix.Matrix(this.V); + } + return this.V; + }, + get diagonalMatrix() { + return Matrix.Matrix.diag(this.s); + }, + solve: function (value) { + + var Y = value, + e = this.threshold, + scols = this.s.length, + Ls = Matrix.Matrix.zeros(scols, scols), + i; + + for (i = 0; i < scols; i++) { + if (Math.abs(this.s[i]) <= e) { + Ls[i][i] = 0; + } else { + Ls[i][i] = 1 / this.s[i]; + } + } + + var U = this.U; + var V = this.rightSingularVectors; + + var VL = V.mmul(Ls), + vrows = V.rows, + urows = U.length, + VLU = Matrix.Matrix.zeros(vrows, urows), + j, k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < scols; k++) { + sum += VL[i][k] * U[j][k]; + } + VLU[i][j] = sum; + } + } + + return VLU.mmul(Y); + }, + solveForDiagonal: function (value) { + return this.solve(Matrix.Matrix.diag(value)); + }, + inverse: function () { + var V = this.V; + var e = this.threshold, + vrows = V.length, + vcols = V[0].length, + X = new Matrix.Matrix(vrows, this.s.length), + i, j; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < vcols; j++) { + if (Math.abs(this.s[j]) > e) { + X[i][j] = V[i][j] / this.s[j]; + } else { + X[i][j] = 0; + } + } + } + + var U = this.U; + + var urows = U.length, + ucols = U[0].length, + Y = new Matrix.Matrix(vrows, urows), + k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < ucols; k++) { + sum += X[i][k] * U[j][k]; + } + Y[i][j] = sum; + } + } + + return Y; + } +}; + +module.exports = SingularValueDecomposition; + + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Matrix = __webpack_require__(0); +var Stat = __webpack_require__(2); + +module.exports.NaiveBayes = NaiveBayes; +module.exports.separateClasses = separateClasses; + +/** + * Constructor for the Naive Bayes classifier, the parameters here is just for loading purposes. + * + * @param reload + * @param model + * @constructor + */ +function NaiveBayes(reload, model) { + if(reload) { + this.means = model.means; + this.calculateProbabilities = model.calculateProbabilities; + } +} + +/** + * Function that trains the classifier with a matrix that represents the training set and an array that + * represents the label of each row in the training set. the labels must be numbers between 0 to n-1 where + * n represents the number of classes. + * + * WARNING: in the case that one class, all the cases in one or more features have the same value, the + * Naive Bayes classifier will not work well. + * @param trainingSet + * @param trainingLabels + */ +NaiveBayes.prototype.train = function (trainingSet, trainingLabels) { + var C1 = Math.sqrt(2*Math.PI); // constant to precalculate the squared root + if(!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet); + else trainingSet = trainingSet.clone(); + + if(trainingSet.rows !== trainingLabels.length) + throw new RangeError("the size of the training set and the training labels must be the same."); + + var separatedClasses = separateClasses(trainingSet, trainingLabels); + var calculateProbabilities = new Array(separatedClasses.length); + this.means = new Array(separatedClasses.length); + for(var i = 0; i < separatedClasses.length; ++i) { + var means = Stat.matrix.mean(separatedClasses[i]); + var std = Stat.matrix.standardDeviation(separatedClasses[i], means); + + var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows); + calculateProbabilities[i] = new Array(means.length + 1); + + calculateProbabilities[i][0] = logPriorProbability; + for(var j = 1; j < means.length + 1; ++j) { + var currentStd = std[j - 1]; + calculateProbabilities[i][j] = [(1 / (C1 * currentStd)), -2*currentStd*currentStd]; + } + + this.means[i] = means; + } + + this.calculateProbabilities = calculateProbabilities; +}; + +/** + * function that predicts each row of the dataset (must be a matrix). + * + * @param dataset + * @returns {Array} + */ +NaiveBayes.prototype.predict = function (dataset) { + if(dataset[0].length === this.calculateProbabilities[0].length) + throw new RangeError('the dataset must have the same features as the training set'); + + var predictions = new Array(dataset.length); + + for(var i = 0; i < predictions.length; ++i) { + predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities); + } + + return predictions; +}; + +/** + * Function the retrieves a prediction with one case. + * + * @param currentCase + * @param mean - Precalculated means of each class trained + * @param classes - Precalculated value of each class (Prior probability and probability function of each feature) + * @returns {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 + 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]); + } + + currentProbability = Math.exp(currentProbability); + if(currentProbability > maxProbability) { + maxProbability = currentProbability; + predictedClass = i; + } + } + + return predictedClass; +} + +/** + * Function that export the NaiveBayes model. + * @returns {{modelName: string, means: *, calculateProbabilities: *}} + */ +NaiveBayes.prototype.export = function () { + return { + modelName: "NaiveBayes", + means: this.means, + calculateProbabilities: this.calculateProbabilities + }; +}; + +/** + * Function that create a Naive Bayes classifier with the given model. + * @param model + * @returns {NaiveBayes} + */ +NaiveBayes.load = function (model) { + if(model.modelName !== 'NaiveBayes') + throw new RangeError("The given model is invalid!"); + + return new NaiveBayes(true, model); +}; + +/** + * function that retrieves the probability of the feature given the class. + * @param value - value of the feature. + * @param mean - mean of the feature for the given class. + * @param C1 - precalculated value of (1 / (sqrt(2*pi) * std)). + * @param C2 - precalculated value of (2 * std^2) for the denominator of the exponential. + * @returns {number} + */ +function calculateLogProbability(value, mean, C1, C2) { + var value = value - mean; + return Math.log(C1 * Math.exp((value * value) / C2)) +} + +/** + * Function that retuns an array of matrices of the cases that belong to each class. + * @param X - dataset + * @param y - predictions + * @returns {Array} + */ +function separateClasses(X, y) { + var features = X.columns; + + var classes = 0; + var totalPerClasses = new Array(100); // max upperbound of classes + for (var i = 0; i < y.length; i++) { + if(totalPerClasses[y[i]] === undefined) { + totalPerClasses[y[i]] = 0; + classes++; + } + totalPerClasses[y[i]]++; + } + var separatedClasses = new Array(classes); + var currentIndex = new Array(classes); + for(i = 0; i < classes; ++i) { + separatedClasses[i] = new 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]]++; + } + return separatedClasses; +} + + +/***/ }), +/* 66 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(30); + + + +//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs +function QrDecomposition(value) { + if (!(this instanceof QrDecomposition)) { + return new QrDecomposition(value); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var qr = value.clone(), + m = value.rows, + n = value.columns, + rdiag = new Array(n), + i, j, k, s; + + for (k = 0; k < n; k++) { + var nrm = 0; + for (i = k; i < m; i++) { + nrm = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(nrm, qr[i][k]); + } + if (nrm !== 0) { + if (qr[k][k] < 0) { + nrm = -nrm; + } + for (i = k; i < m; i++) { + qr[i][k] /= nrm; + } + qr[k][k] += 1; + for (j = k + 1; j < n; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * qr[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + qr[i][j] += s * qr[i][k]; + } + } + } + rdiag[k] = -nrm; + } + + this.QR = qr; + this.Rdiag = rdiag; +} + +QrDecomposition.prototype = { + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var qr = this.QR, + m = qr.rows; + + if (value.rows !== m) { + throw new Error('Matrix row dimensions must agree'); + } + if (!this.isFullRank()) { + throw new Error('Matrix is rank deficient'); + } + + var count = value.columns; + var X = value.clone(); + var n = qr.columns; + var i, j, k, s; + + for (k = 0; k < n; k++) { + for (j = 0; j < count; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * X[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + for (k = n - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= this.Rdiag[k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * qr[i][k]; + } + } + } + + return X.subMatrix(0, n - 1, 0, count - 1); + }, + isFullRank: function () { + var columns = this.QR.columns; + for (var i = 0; i < columns; i++) { + if (this.Rdiag[i] === 0) { + return false; + } + } + return true; + }, + get upperTriangularMatrix() { + var qr = this.QR, + n = qr.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + if (i < j) { + X[i][j] = qr[i][j]; + } else if (i === j) { + X[i][j] = this.Rdiag[i]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get orthogonalMatrix() { + var qr = this.QR, + rows = qr.rows, + columns = qr.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns), + i, j, k, s; + + for (k = columns - 1; k >= 0; k--) { + for (i = 0; i < rows; i++) { + X[i][k] = 0; + } + X[k][k] = 1; + for (j = k; j < columns; j++) { + if (qr[k][k] !== 0) { + s = 0; + for (i = k; i < rows; i++) { + s += qr[i][k] * X[i][j]; + } + + s = -s / qr[k][k]; + + for (i = k; i < rows; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + } + return X; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (QrDecomposition); + + +/***/ }), +/* 67 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(30); + + + +// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs +function SingularValueDecomposition(value, options) { + if (!(this instanceof SingularValueDecomposition)) { + return new SingularValueDecomposition(value, options); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + options = options || {}; + + var m = value.rows, + n = value.columns, + nu = Math.min(m, n); + + var wantu = true, wantv = true; + if (options.computeLeftSingularVectors === false) wantu = false; + if (options.computeRightSingularVectors === false) wantv = false; + var autoTranspose = options.autoTranspose === true; + + var swapped = false; + var a; + if (m < n) { + if (!autoTranspose) { + a = value.clone(); + // eslint-disable-next-line no-console + console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'); + } else { + a = value.transpose(); + m = a.rows; + n = a.columns; + swapped = true; + var aux = wantu; + wantu = wantv; + wantv = aux; + } + } else { + a = value.clone(); + } + + var s = new Array(Math.min(m + 1, n)), + U = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(m, nu, 0), + V = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + e = new Array(n), + work = new Array(m); + + var nct = Math.min(m - 1, n); + var nrt = Math.max(0, Math.min(n - 2, m)); + + var i, j, k, p, t, ks, f, cs, sn, max, kase, + scale, sp, spm1, epm1, sk, ek, b, c, shift, g; + + for (k = 0, max = Math.max(nct, nrt); k < max; k++) { + if (k < nct) { + s[k] = 0; + for (i = k; i < m; i++) { + s[k] = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[k], a[i][k]); + } + if (s[k] !== 0) { + if (a[k][k] < 0) { + s[k] = -s[k]; + } + for (i = k; i < m; i++) { + a[i][k] /= s[k]; + } + a[k][k] += 1; + } + s[k] = -s[k]; + } + + for (j = k + 1; j < n; j++) { + if ((k < nct) && (s[k] !== 0)) { + t = 0; + for (i = k; i < m; i++) { + t += a[i][k] * a[i][j]; + } + t = -t / a[k][k]; + for (i = k; i < m; i++) { + a[i][j] += t * a[i][k]; + } + } + e[j] = a[k][j]; + } + + if (wantu && (k < nct)) { + for (i = k; i < m; i++) { + U[i][k] = a[i][k]; + } + } + + if (k < nrt) { + e[k] = 0; + for (i = k + 1; i < n; i++) { + e[k] = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(e[k], e[i]); + } + if (e[k] !== 0) { + if (e[k + 1] < 0) { + e[k] = 0 - e[k]; + } + for (i = k + 1; i < n; i++) { + e[i] /= e[k]; + } + e[k + 1] += 1; + } + e[k] = -e[k]; + if ((k + 1 < m) && (e[k] !== 0)) { + for (i = k + 1; i < m; i++) { + work[i] = 0; + } + for (j = k + 1; j < n; j++) { + for (i = k + 1; i < m; i++) { + work[i] += e[j] * a[i][j]; + } + } + for (j = k + 1; j < n; j++) { + t = -e[j] / e[k + 1]; + for (i = k + 1; i < m; i++) { + a[i][j] += t * work[i]; + } + } + } + if (wantv) { + for (i = k + 1; i < n; i++) { + V[i][k] = e[i]; + } + } + } + } + + p = Math.min(n, m + 1); + if (nct < n) { + s[nct] = a[nct][nct]; + } + if (m < p) { + s[p - 1] = 0; + } + if (nrt + 1 < p) { + e[nrt] = a[nrt][p - 1]; + } + e[p - 1] = 0; + + if (wantu) { + for (j = nct; j < nu; j++) { + for (i = 0; i < m; i++) { + U[i][j] = 0; + } + U[j][j] = 1; + } + for (k = nct - 1; k >= 0; k--) { + if (s[k] !== 0) { + for (j = k + 1; j < nu; j++) { + t = 0; + for (i = k; i < m; i++) { + t += U[i][k] * U[i][j]; + } + t = -t / U[k][k]; + for (i = k; i < m; i++) { + U[i][j] += t * U[i][k]; + } + } + for (i = k; i < m; i++) { + U[i][k] = -U[i][k]; + } + U[k][k] = 1 + U[k][k]; + for (i = 0; i < k - 1; i++) { + U[i][k] = 0; + } + } else { + for (i = 0; i < m; i++) { + U[i][k] = 0; + } + U[k][k] = 1; + } + } + } + + if (wantv) { + for (k = n - 1; k >= 0; k--) { + if ((k < nrt) && (e[k] !== 0)) { + for (j = k + 1; j < n; j++) { + t = 0; + for (i = k + 1; i < n; i++) { + t += V[i][k] * V[i][j]; + } + t = -t / V[k + 1][k]; + for (i = k + 1; i < n; i++) { + V[i][j] += t * V[i][k]; + } + } + } + for (i = 0; i < n; i++) { + V[i][k] = 0; + } + V[k][k] = 1; + } + } + + var pp = p - 1, + iter = 0, + eps = Math.pow(2, -52); + while (p > 0) { + for (k = p - 2; k >= -1; k--) { + if (k === -1) { + break; + } + if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { + e[k] = 0; + break; + } + } + if (k === p - 2) { + kase = 4; + } else { + for (ks = p - 1; ks >= k; ks--) { + if (ks === k) { + break; + } + t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0); + if (Math.abs(s[ks]) <= eps * t) { + s[ks] = 0; + break; + } + } + if (ks === k) { + kase = 3; + } else if (ks === p - 1) { + kase = 1; + } else { + kase = 2; + k = ks; + } + } + + k++; + + switch (kase) { + case 1: { + f = e[p - 2]; + e[p - 2] = 0; + for (j = p - 2; j >= k; j--) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + if (j !== k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } + if (wantv) { + for (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][p - 1]; + V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; + V[i][j] = t; + } + } + } + break; + } + case 2 : { + f = e[k - 1]; + e[k - 1] = 0; + for (j = k; j < p; j++) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + f = -sn * e[j]; + e[j] = cs * e[j]; + if (wantu) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][k - 1]; + U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; + U[i][j] = t; + } + } + } + break; + } + case 3 : { + scale = Math.max(Math.max(Math.max(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])); + sp = s[p - 1] / scale; + spm1 = s[p - 2] / scale; + epm1 = e[p - 2] / scale; + sk = s[k] / scale; + ek = e[k] / scale; + b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2; + c = (sp * epm1) * (sp * epm1); + shift = 0; + if ((b !== 0) || (c !== 0)) { + shift = Math.sqrt(b * b + c); + if (b < 0) { + shift = -shift; + } + shift = c / (b + shift); + } + f = (sk + sp) * (sk - sp) + shift; + g = sk * ek; + for (j = k; j < p - 1; j++) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(f, g); + cs = f / t; + sn = g / t; + if (j !== k) { + e[j - 1] = t; + } + 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 (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][j + 1]; + V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; + V[i][j] = t; + } + } + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(f, g); + cs = f / t; + sn = g / t; + s[j] = t; + f = cs * e[j] + sn * s[j + 1]; + s[j + 1] = -sn * e[j] + cs * s[j + 1]; + g = sn * e[j + 1]; + e[j + 1] = cs * e[j + 1]; + if (wantu && (j < m - 1)) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][j + 1]; + U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; + U[i][j] = t; + } + } + } + e[p - 2] = f; + iter = iter + 1; + break; + } + case 4: { + if (s[k] <= 0) { + s[k] = (s[k] < 0 ? -s[k] : 0); + if (wantv) { + for (i = 0; i <= pp; i++) { + V[i][k] = -V[i][k]; + } + } + } + while (k < pp) { + if (s[k] >= s[k + 1]) { + break; + } + t = s[k]; + s[k] = s[k + 1]; + s[k + 1] = t; + if (wantv && (k < n - 1)) { + for (i = 0; i < n; i++) { + t = V[i][k + 1]; + V[i][k + 1] = V[i][k]; + V[i][k] = t; + } + } + if (wantu && (k < m - 1)) { + for (i = 0; i < m; i++) { + t = U[i][k + 1]; + U[i][k + 1] = U[i][k]; + U[i][k] = t; + } + } + k++; + } + iter = 0; + p--; + break; + } + // no default + } + } + + if (swapped) { + var tmp = V; + V = U; + U = tmp; + } + + this.m = m; + this.n = n; + this.s = s; + this.U = U; + this.V = V; +} + +SingularValueDecomposition.prototype = { + get condition() { + return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; + }, + get norm2() { + return this.s[0]; + }, + get rank() { + var eps = Math.pow(2, -52), + tol = Math.max(this.m, this.n) * this.s[0] * eps, + r = 0, + s = this.s; + for (var i = 0, ii = s.length; i < ii; i++) { + if (s[i] > tol) { + r++; + } + } + return r; + }, + get diagonal() { + return this.s; + }, + // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs + get threshold() { + return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0]; + }, + get leftSingularVectors() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.U)) { + this.U = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.U); + } + return this.U; + }, + get rightSingularVectors() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.V)) { + this.V = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.V); + } + return this.V; + }, + get diagonalMatrix() { + return __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].diag(this.s); + }, + solve: function (value) { + + var Y = value, + e = this.threshold, + scols = this.s.length, + Ls = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(scols, scols), + i; + + for (i = 0; i < scols; i++) { + if (Math.abs(this.s[i]) <= e) { + Ls[i][i] = 0; + } else { + Ls[i][i] = 1 / this.s[i]; + } + } + + var U = this.U; + var V = this.rightSingularVectors; + + var VL = V.mmul(Ls), + vrows = V.rows, + urows = U.length, + VLU = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(vrows, urows), + j, k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < scols; k++) { + sum += VL[i][k] * U[j][k]; + } + VLU[i][j] = sum; + } + } + + return VLU.mmul(Y); + }, + solveForDiagonal: function (value) { + return this.solve(__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].diag(value)); + }, + inverse: function () { + var V = this.V; + var e = this.threshold, + vrows = V.length, + vcols = V[0].length, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](vrows, this.s.length), + i, j; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < vcols; j++) { + if (Math.abs(this.s[j]) > e) { + X[i][j] = V[i][j] / this.s[j]; + } else { + X[i][j] = 0; + } + } + } + + var U = this.U; + + var urows = U.length, + ucols = U[0].length, + Y = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](vrows, urows), + k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < ucols; k++) { + sum += X[i][k] * U[j][k]; + } + Y[i][j] = sum; + } + } + + return Y; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (SingularValueDecomposition); + + +/***/ }), +/* 68 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ml_matrix__ = __webpack_require__(206); + + + +class PolynomialRegression extends __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["a" /* default */] { + constructor(x, y, degree) { + super(); + if (x === true) { + this.degree = y.degree; + this.powers = y.powers; + this.coefficients = y.coefficients; + } else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["b" /* checkArrayLength */])(x, y); + regress(this, x, y, degree); + } + } + + _predict(x) { + let y = 0; + for (let k = 0; k < this.powers.length; k++) { + y += this.coefficients[k] * Math.pow(x, this.powers[k]); + } + return y; + } + + toJSON() { + return { + name: 'polynomialRegression', + degree: this.degree, + powers: this.powers, + coefficients: this.coefficients + }; + } + + toString(precision) { + return this._toFormula(precision, false); + } + + toLaTeX(precision) { + return this._toFormula(precision, true); + } + + _toFormula(precision, isLaTeX) { + let sup = '^'; + let closeSup = ''; + let times = ' * '; + if (isLaTeX) { + sup = '^{'; + closeSup = '}'; + times = ''; + } + + 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 = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.coefficients[k], precision); + } else { + if (this.powers[k] === 1) { + str = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.coefficients[k], precision) + times + 'x'; + } else { + str = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* 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; + } + + static load(json) { + if (json.name !== 'polynomialRegression') { + throw new TypeError('not a polynomial regression model'); + } + return new PolynomialRegression(true, json); + } +} +/* harmony export (immutable) */ __webpack_exports__["default"] = PolynomialRegression; + + +function regress(pr, x, y, degree) { + const n = x.length; + let powers; + if (Array.isArray(degree)) { + powers = degree; + degree = powers.length; + } else { + degree++; + powers = new Array(degree); + for (let k = 0; k < degree; k++) { + powers[k] = k; + } + } + const F = new __WEBPACK_IMPORTED_MODULE_1_ml_matrix__["a" /* default */](n, degree); + const Y = new __WEBPACK_IMPORTED_MODULE_1_ml_matrix__["a" /* default */]([y]); + for (let k = 0; k < degree; k++) { + for (let i = 0; i < n; i++) { + if (powers[k] === 0) { + F[i][k] = 1; + } else { + F[i][k] = Math.pow(x[i], powers[k]); + } + } + } + + const FT = F.transposeView(); + const A = FT.mmul(F); + const B = FT.mmul(Y.transposeView()); + + pr.degree = degree - 1; + pr.powers = powers; + pr.coefficients = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_ml_matrix__["b" /* solve */])(A, B).to1DArray(); +} + + +/***/ }), +/* 69 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(33); + + + +//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs +function QrDecomposition(value) { + if (!(this instanceof QrDecomposition)) { + return new QrDecomposition(value); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var qr = value.clone(), + m = value.rows, + n = value.columns, + rdiag = new Array(n), + i, j, k, s; + + for (k = 0; k < n; k++) { + var nrm = 0; + for (i = k; i < m; i++) { + nrm = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(nrm, qr[i][k]); + } + if (nrm !== 0) { + if (qr[k][k] < 0) { + nrm = -nrm; + } + for (i = k; i < m; i++) { + qr[i][k] /= nrm; + } + qr[k][k] += 1; + for (j = k + 1; j < n; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * qr[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + qr[i][j] += s * qr[i][k]; + } + } + } + rdiag[k] = -nrm; + } + + this.QR = qr; + this.Rdiag = rdiag; +} + +QrDecomposition.prototype = { + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var qr = this.QR, + m = qr.rows; + + if (value.rows !== m) { + throw new Error('Matrix row dimensions must agree'); + } + if (!this.isFullRank()) { + throw new Error('Matrix is rank deficient'); + } + + var count = value.columns; + var X = value.clone(); + var n = qr.columns; + var i, j, k, s; + + for (k = 0; k < n; k++) { + for (j = 0; j < count; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * X[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + for (k = n - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= this.Rdiag[k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * qr[i][k]; + } + } + } + + return X.subMatrix(0, n - 1, 0, count - 1); + }, + isFullRank: function () { + var columns = this.QR.columns; + for (var i = 0; i < columns; i++) { + if (this.Rdiag[i] === 0) { + return false; + } + } + return true; + }, + get upperTriangularMatrix() { + var qr = this.QR, + n = qr.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + if (i < j) { + X[i][j] = qr[i][j]; + } else if (i === j) { + X[i][j] = this.Rdiag[i]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get orthogonalMatrix() { + var qr = this.QR, + rows = qr.rows, + columns = qr.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns), + i, j, k, s; + + for (k = columns - 1; k >= 0; k--) { + for (i = 0; i < rows; i++) { + X[i][k] = 0; + } + X[k][k] = 1; + for (j = k; j < columns; j++) { + if (qr[k][k] !== 0) { + s = 0; + for (i = k; i < rows; i++) { + s += qr[i][k] * X[i][j]; + } + + s = -s / qr[k][k]; + + for (i = k; i < rows; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + } + return X; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (QrDecomposition); + + +/***/ }), +/* 70 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(33); + + + +// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs +function SingularValueDecomposition(value, options) { + if (!(this instanceof SingularValueDecomposition)) { + return new SingularValueDecomposition(value, options); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + options = options || {}; + + var m = value.rows, + n = value.columns, + nu = Math.min(m, n); + + var wantu = true, wantv = true; + if (options.computeLeftSingularVectors === false) wantu = false; + if (options.computeRightSingularVectors === false) wantv = false; + var autoTranspose = options.autoTranspose === true; + + var swapped = false; + var a; + if (m < n) { + if (!autoTranspose) { + a = value.clone(); + // eslint-disable-next-line no-console + console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'); + } else { + a = value.transpose(); + m = a.rows; + n = a.columns; + swapped = true; + var aux = wantu; + wantu = wantv; + wantv = aux; + } + } else { + a = value.clone(); + } + + var s = new Array(Math.min(m + 1, n)), + U = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(m, nu, 0), + V = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + e = new Array(n), + work = new Array(m); + + var nct = Math.min(m - 1, n); + var nrt = Math.max(0, Math.min(n - 2, m)); + + var i, j, k, p, t, ks, f, cs, sn, max, kase, + scale, sp, spm1, epm1, sk, ek, b, c, shift, g; + + for (k = 0, max = Math.max(nct, nrt); k < max; k++) { + if (k < nct) { + s[k] = 0; + for (i = k; i < m; i++) { + s[k] = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[k], a[i][k]); + } + if (s[k] !== 0) { + if (a[k][k] < 0) { + s[k] = -s[k]; + } + for (i = k; i < m; i++) { + a[i][k] /= s[k]; + } + a[k][k] += 1; + } + s[k] = -s[k]; + } + + for (j = k + 1; j < n; j++) { + if ((k < nct) && (s[k] !== 0)) { + t = 0; + for (i = k; i < m; i++) { + t += a[i][k] * a[i][j]; + } + t = -t / a[k][k]; + for (i = k; i < m; i++) { + a[i][j] += t * a[i][k]; + } + } + e[j] = a[k][j]; + } + + if (wantu && (k < nct)) { + for (i = k; i < m; i++) { + U[i][k] = a[i][k]; + } + } + + if (k < nrt) { + e[k] = 0; + for (i = k + 1; i < n; i++) { + e[k] = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(e[k], e[i]); + } + if (e[k] !== 0) { + if (e[k + 1] < 0) { + e[k] = 0 - e[k]; + } + for (i = k + 1; i < n; i++) { + e[i] /= e[k]; + } + e[k + 1] += 1; + } + e[k] = -e[k]; + if ((k + 1 < m) && (e[k] !== 0)) { + for (i = k + 1; i < m; i++) { + work[i] = 0; + } + for (j = k + 1; j < n; j++) { + for (i = k + 1; i < m; i++) { + work[i] += e[j] * a[i][j]; + } + } + for (j = k + 1; j < n; j++) { + t = -e[j] / e[k + 1]; + for (i = k + 1; i < m; i++) { + a[i][j] += t * work[i]; + } + } + } + if (wantv) { + for (i = k + 1; i < n; i++) { + V[i][k] = e[i]; + } + } + } + } + + p = Math.min(n, m + 1); + if (nct < n) { + s[nct] = a[nct][nct]; + } + if (m < p) { + s[p - 1] = 0; + } + if (nrt + 1 < p) { + e[nrt] = a[nrt][p - 1]; + } + e[p - 1] = 0; + + if (wantu) { + for (j = nct; j < nu; j++) { + for (i = 0; i < m; i++) { + U[i][j] = 0; + } + U[j][j] = 1; + } + for (k = nct - 1; k >= 0; k--) { + if (s[k] !== 0) { + for (j = k + 1; j < nu; j++) { + t = 0; + for (i = k; i < m; i++) { + t += U[i][k] * U[i][j]; + } + t = -t / U[k][k]; + for (i = k; i < m; i++) { + U[i][j] += t * U[i][k]; + } + } + for (i = k; i < m; i++) { + U[i][k] = -U[i][k]; + } + U[k][k] = 1 + U[k][k]; + for (i = 0; i < k - 1; i++) { + U[i][k] = 0; + } + } else { + for (i = 0; i < m; i++) { + U[i][k] = 0; + } + U[k][k] = 1; + } + } + } + + if (wantv) { + for (k = n - 1; k >= 0; k--) { + if ((k < nrt) && (e[k] !== 0)) { + for (j = k + 1; j < n; j++) { + t = 0; + for (i = k + 1; i < n; i++) { + t += V[i][k] * V[i][j]; + } + t = -t / V[k + 1][k]; + for (i = k + 1; i < n; i++) { + V[i][j] += t * V[i][k]; + } + } + } + for (i = 0; i < n; i++) { + V[i][k] = 0; + } + V[k][k] = 1; + } + } + + var pp = p - 1, + iter = 0, + eps = Math.pow(2, -52); + while (p > 0) { + for (k = p - 2; k >= -1; k--) { + if (k === -1) { + break; + } + if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { + e[k] = 0; + break; + } + } + if (k === p - 2) { + kase = 4; + } else { + for (ks = p - 1; ks >= k; ks--) { + if (ks === k) { + break; + } + t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0); + if (Math.abs(s[ks]) <= eps * t) { + s[ks] = 0; + break; + } + } + if (ks === k) { + kase = 3; + } else if (ks === p - 1) { + kase = 1; + } else { + kase = 2; + k = ks; + } + } + + k++; + + switch (kase) { + case 1: { + f = e[p - 2]; + e[p - 2] = 0; + for (j = p - 2; j >= k; j--) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + if (j !== k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } + if (wantv) { + for (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][p - 1]; + V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; + V[i][j] = t; + } + } + } + break; + } + case 2 : { + f = e[k - 1]; + e[k - 1] = 0; + for (j = k; j < p; j++) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + f = -sn * e[j]; + e[j] = cs * e[j]; + if (wantu) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][k - 1]; + U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; + U[i][j] = t; + } + } + } + break; + } + case 3 : { + scale = Math.max(Math.max(Math.max(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])); + sp = s[p - 1] / scale; + spm1 = s[p - 2] / scale; + epm1 = e[p - 2] / scale; + sk = s[k] / scale; + ek = e[k] / scale; + b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2; + c = (sp * epm1) * (sp * epm1); + shift = 0; + if ((b !== 0) || (c !== 0)) { + shift = Math.sqrt(b * b + c); + if (b < 0) { + shift = -shift; + } + shift = c / (b + shift); + } + f = (sk + sp) * (sk - sp) + shift; + g = sk * ek; + for (j = k; j < p - 1; j++) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(f, g); + cs = f / t; + sn = g / t; + if (j !== k) { + e[j - 1] = t; + } + 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 (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][j + 1]; + V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; + V[i][j] = t; + } + } + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(f, g); + cs = f / t; + sn = g / t; + s[j] = t; + f = cs * e[j] + sn * s[j + 1]; + s[j + 1] = -sn * e[j] + cs * s[j + 1]; + g = sn * e[j + 1]; + e[j + 1] = cs * e[j + 1]; + if (wantu && (j < m - 1)) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][j + 1]; + U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; + U[i][j] = t; + } + } + } + e[p - 2] = f; + iter = iter + 1; + break; + } + case 4: { + if (s[k] <= 0) { + s[k] = (s[k] < 0 ? -s[k] : 0); + if (wantv) { + for (i = 0; i <= pp; i++) { + V[i][k] = -V[i][k]; + } + } + } + while (k < pp) { + if (s[k] >= s[k + 1]) { + break; + } + t = s[k]; + s[k] = s[k + 1]; + s[k + 1] = t; + if (wantv && (k < n - 1)) { + for (i = 0; i < n; i++) { + t = V[i][k + 1]; + V[i][k + 1] = V[i][k]; + V[i][k] = t; + } + } + if (wantu && (k < m - 1)) { + for (i = 0; i < m; i++) { + t = U[i][k + 1]; + U[i][k + 1] = U[i][k]; + U[i][k] = t; + } + } + k++; + } + iter = 0; + p--; + break; + } + // no default + } + } + + if (swapped) { + var tmp = V; + V = U; + U = tmp; + } + + this.m = m; + this.n = n; + this.s = s; + this.U = U; + this.V = V; +} + +SingularValueDecomposition.prototype = { + get condition() { + return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; + }, + get norm2() { + return this.s[0]; + }, + get rank() { + var eps = Math.pow(2, -52), + tol = Math.max(this.m, this.n) * this.s[0] * eps, + r = 0, + s = this.s; + for (var i = 0, ii = s.length; i < ii; i++) { + if (s[i] > tol) { + r++; + } + } + return r; + }, + get diagonal() { + return this.s; + }, + // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs + get threshold() { + return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0]; + }, + get leftSingularVectors() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.U)) { + this.U = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.U); + } + return this.U; + }, + get rightSingularVectors() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.V)) { + this.V = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.V); + } + return this.V; + }, + get diagonalMatrix() { + return __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].diag(this.s); + }, + solve: function (value) { + + var Y = value, + e = this.threshold, + scols = this.s.length, + Ls = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(scols, scols), + i; + + for (i = 0; i < scols; i++) { + if (Math.abs(this.s[i]) <= e) { + Ls[i][i] = 0; + } else { + Ls[i][i] = 1 / this.s[i]; + } + } + + var U = this.U; + var V = this.rightSingularVectors; + + var VL = V.mmul(Ls), + vrows = V.rows, + urows = U.length, + VLU = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(vrows, urows), + j, k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < scols; k++) { + sum += VL[i][k] * U[j][k]; + } + VLU[i][j] = sum; + } + } + + return VLU.mmul(Y); + }, + solveForDiagonal: function (value) { + return this.solve(__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].diag(value)); + }, + inverse: function () { + var V = this.V; + var e = this.threshold, + vrows = V.length, + vcols = V[0].length, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](vrows, this.s.length), + i, j; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < vcols; j++) { + if (Math.abs(this.s[j]) > e) { + X[i][j] = V[i][j] / this.s[j]; + } else { + X[i][j] = 0; + } + } + } + + var U = this.U; + + var urows = U.length, + ucols = U[0].length, + Y = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](vrows, urows), + k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < ucols; k++) { + sum += X[i][k] * U[j][k]; + } + Y[i][j] = sum; + } + } + + return Y; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (SingularValueDecomposition); + + +/***/ }), +/* 71 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(37); + + + +//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs +function QrDecomposition(value) { + if (!(this instanceof QrDecomposition)) { + return new QrDecomposition(value); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var qr = value.clone(), + m = value.rows, + n = value.columns, + rdiag = new Array(n), + i, j, k, s; + + for (k = 0; k < n; k++) { + var nrm = 0; + for (i = k; i < m; i++) { + nrm = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(nrm, qr[i][k]); + } + if (nrm !== 0) { + if (qr[k][k] < 0) { + nrm = -nrm; + } + for (i = k; i < m; i++) { + qr[i][k] /= nrm; + } + qr[k][k] += 1; + for (j = k + 1; j < n; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * qr[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + qr[i][j] += s * qr[i][k]; + } + } + } + rdiag[k] = -nrm; + } + + this.QR = qr; + this.Rdiag = rdiag; +} + +QrDecomposition.prototype = { + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var qr = this.QR, + m = qr.rows; + + if (value.rows !== m) { + throw new Error('Matrix row dimensions must agree'); + } + if (!this.isFullRank()) { + throw new Error('Matrix is rank deficient'); + } + + var count = value.columns; + var X = value.clone(); + var n = qr.columns; + var i, j, k, s; + + for (k = 0; k < n; k++) { + for (j = 0; j < count; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * X[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + for (k = n - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= this.Rdiag[k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * qr[i][k]; + } + } + } + + return X.subMatrix(0, n - 1, 0, count - 1); + }, + isFullRank: function () { + var columns = this.QR.columns; + for (var i = 0; i < columns; i++) { + if (this.Rdiag[i] === 0) { + return false; + } + } + return true; + }, + get upperTriangularMatrix() { + var qr = this.QR, + n = qr.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + if (i < j) { + X[i][j] = qr[i][j]; + } else if (i === j) { + X[i][j] = this.Rdiag[i]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get orthogonalMatrix() { + var qr = this.QR, + rows = qr.rows, + columns = qr.columns, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](rows, columns), + i, j, k, s; + + for (k = columns - 1; k >= 0; k--) { + for (i = 0; i < rows; i++) { + X[i][k] = 0; + } + X[k][k] = 1; + for (j = k; j < columns; j++) { + if (qr[k][k] !== 0) { + s = 0; + for (i = k; i < rows; i++) { + s += qr[i][k] * X[i][j]; + } + + s = -s / qr[k][k]; + + for (i = k; i < rows; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + } + return X; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (QrDecomposition); + + +/***/ }), +/* 72 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(37); + + + +// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs +function SingularValueDecomposition(value, options) { + if (!(this instanceof SingularValueDecomposition)) { + return new SingularValueDecomposition(value, options); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + options = options || {}; + + var m = value.rows, + n = value.columns, + nu = Math.min(m, n); + + var wantu = true, wantv = true; + if (options.computeLeftSingularVectors === false) wantu = false; + if (options.computeRightSingularVectors === false) wantv = false; + var autoTranspose = options.autoTranspose === true; + + var swapped = false; + var a; + if (m < n) { + if (!autoTranspose) { + a = value.clone(); + // eslint-disable-next-line no-console + console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'); + } else { + a = value.transpose(); + m = a.rows; + n = a.columns; + swapped = true; + var aux = wantu; + wantu = wantv; + wantv = aux; + } + } else { + a = value.clone(); + } + + var s = new Array(Math.min(m + 1, n)), + U = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(m, nu, 0), + V = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + e = new Array(n), + work = new Array(m); + + var nct = Math.min(m - 1, n); + var nrt = Math.max(0, Math.min(n - 2, m)); + + var i, j, k, p, t, ks, f, cs, sn, max, kase, + scale, sp, spm1, epm1, sk, ek, b, c, shift, g; + + for (k = 0, max = Math.max(nct, nrt); k < max; k++) { + if (k < nct) { + s[k] = 0; + for (i = k; i < m; i++) { + s[k] = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[k], a[i][k]); + } + if (s[k] !== 0) { + if (a[k][k] < 0) { + s[k] = -s[k]; + } + for (i = k; i < m; i++) { + a[i][k] /= s[k]; + } + a[k][k] += 1; + } + s[k] = -s[k]; + } + + for (j = k + 1; j < n; j++) { + if ((k < nct) && (s[k] !== 0)) { + t = 0; + for (i = k; i < m; i++) { + t += a[i][k] * a[i][j]; + } + t = -t / a[k][k]; + for (i = k; i < m; i++) { + a[i][j] += t * a[i][k]; + } + } + e[j] = a[k][j]; + } + + if (wantu && (k < nct)) { + for (i = k; i < m; i++) { + U[i][k] = a[i][k]; + } + } + + if (k < nrt) { + e[k] = 0; + for (i = k + 1; i < n; i++) { + e[k] = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(e[k], e[i]); + } + if (e[k] !== 0) { + if (e[k + 1] < 0) { + e[k] = 0 - e[k]; + } + for (i = k + 1; i < n; i++) { + e[i] /= e[k]; + } + e[k + 1] += 1; + } + e[k] = -e[k]; + if ((k + 1 < m) && (e[k] !== 0)) { + for (i = k + 1; i < m; i++) { + work[i] = 0; + } + for (j = k + 1; j < n; j++) { + for (i = k + 1; i < m; i++) { + work[i] += e[j] * a[i][j]; + } + } + for (j = k + 1; j < n; j++) { + t = -e[j] / e[k + 1]; + for (i = k + 1; i < m; i++) { + a[i][j] += t * work[i]; + } + } + } + if (wantv) { + for (i = k + 1; i < n; i++) { + V[i][k] = e[i]; + } + } + } + } + + p = Math.min(n, m + 1); + if (nct < n) { + s[nct] = a[nct][nct]; + } + if (m < p) { + s[p - 1] = 0; + } + if (nrt + 1 < p) { + e[nrt] = a[nrt][p - 1]; + } + e[p - 1] = 0; + + if (wantu) { + for (j = nct; j < nu; j++) { + for (i = 0; i < m; i++) { + U[i][j] = 0; + } + U[j][j] = 1; + } + for (k = nct - 1; k >= 0; k--) { + if (s[k] !== 0) { + for (j = k + 1; j < nu; j++) { + t = 0; + for (i = k; i < m; i++) { + t += U[i][k] * U[i][j]; + } + t = -t / U[k][k]; + for (i = k; i < m; i++) { + U[i][j] += t * U[i][k]; + } + } + for (i = k; i < m; i++) { + U[i][k] = -U[i][k]; + } + U[k][k] = 1 + U[k][k]; + for (i = 0; i < k - 1; i++) { + U[i][k] = 0; + } + } else { + for (i = 0; i < m; i++) { + U[i][k] = 0; + } + U[k][k] = 1; + } + } + } + + if (wantv) { + for (k = n - 1; k >= 0; k--) { + if ((k < nrt) && (e[k] !== 0)) { + for (j = k + 1; j < n; j++) { + t = 0; + for (i = k + 1; i < n; i++) { + t += V[i][k] * V[i][j]; + } + t = -t / V[k + 1][k]; + for (i = k + 1; i < n; i++) { + V[i][j] += t * V[i][k]; + } + } + } + for (i = 0; i < n; i++) { + V[i][k] = 0; + } + V[k][k] = 1; + } + } + + var pp = p - 1, + iter = 0, + eps = Math.pow(2, -52); + while (p > 0) { + for (k = p - 2; k >= -1; k--) { + if (k === -1) { + break; + } + if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { + e[k] = 0; + break; + } + } + if (k === p - 2) { + kase = 4; + } else { + for (ks = p - 1; ks >= k; ks--) { + if (ks === k) { + break; + } + t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0); + if (Math.abs(s[ks]) <= eps * t) { + s[ks] = 0; + break; + } + } + if (ks === k) { + kase = 3; + } else if (ks === p - 1) { + kase = 1; + } else { + kase = 2; + k = ks; + } + } + + k++; + + switch (kase) { + case 1: { + f = e[p - 2]; + e[p - 2] = 0; + for (j = p - 2; j >= k; j--) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + if (j !== k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } + if (wantv) { + for (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][p - 1]; + V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; + V[i][j] = t; + } + } + } + break; + } + case 2 : { + f = e[k - 1]; + e[k - 1] = 0; + for (j = k; j < p; j++) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(s[j], f); + cs = s[j] / t; + sn = f / t; + s[j] = t; + f = -sn * e[j]; + e[j] = cs * e[j]; + if (wantu) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][k - 1]; + U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; + U[i][j] = t; + } + } + } + break; + } + case 3 : { + scale = Math.max(Math.max(Math.max(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])); + sp = s[p - 1] / scale; + spm1 = s[p - 2] / scale; + epm1 = e[p - 2] / scale; + sk = s[k] / scale; + ek = e[k] / scale; + b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2; + c = (sp * epm1) * (sp * epm1); + shift = 0; + if ((b !== 0) || (c !== 0)) { + shift = Math.sqrt(b * b + c); + if (b < 0) { + shift = -shift; + } + shift = c / (b + shift); + } + f = (sk + sp) * (sk - sp) + shift; + g = sk * ek; + for (j = k; j < p - 1; j++) { + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(f, g); + cs = f / t; + sn = g / t; + if (j !== k) { + e[j - 1] = t; + } + 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 (i = 0; i < n; i++) { + t = cs * V[i][j] + sn * V[i][j + 1]; + V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; + V[i][j] = t; + } + } + t = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(f, g); + cs = f / t; + sn = g / t; + s[j] = t; + f = cs * e[j] + sn * s[j + 1]; + s[j + 1] = -sn * e[j] + cs * s[j + 1]; + g = sn * e[j + 1]; + e[j + 1] = cs * e[j + 1]; + if (wantu && (j < m - 1)) { + for (i = 0; i < m; i++) { + t = cs * U[i][j] + sn * U[i][j + 1]; + U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; + U[i][j] = t; + } + } + } + e[p - 2] = f; + iter = iter + 1; + break; + } + case 4: { + if (s[k] <= 0) { + s[k] = (s[k] < 0 ? -s[k] : 0); + if (wantv) { + for (i = 0; i <= pp; i++) { + V[i][k] = -V[i][k]; + } + } + } + while (k < pp) { + if (s[k] >= s[k + 1]) { + break; + } + t = s[k]; + s[k] = s[k + 1]; + s[k + 1] = t; + if (wantv && (k < n - 1)) { + for (i = 0; i < n; i++) { + t = V[i][k + 1]; + V[i][k + 1] = V[i][k]; + V[i][k] = t; + } + } + if (wantu && (k < m - 1)) { + for (i = 0; i < m; i++) { + t = U[i][k + 1]; + U[i][k + 1] = U[i][k]; + U[i][k] = t; + } + } + k++; + } + iter = 0; + p--; + break; + } + // no default + } + } + + if (swapped) { + var tmp = V; + V = U; + U = tmp; + } + + this.m = m; + this.n = n; + this.s = s; + this.U = U; + this.V = V; +} + +SingularValueDecomposition.prototype = { + get condition() { + return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; + }, + get norm2() { + return this.s[0]; + }, + get rank() { + var eps = Math.pow(2, -52), + tol = Math.max(this.m, this.n) * this.s[0] * eps, + r = 0, + s = this.s; + for (var i = 0, ii = s.length; i < ii; i++) { + if (s[i] > tol) { + r++; + } + } + return r; + }, + get diagonal() { + return this.s; + }, + // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs + get threshold() { + return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0]; + }, + get leftSingularVectors() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.U)) { + this.U = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.U); + } + return this.U; + }, + get rightSingularVectors() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.V)) { + this.V = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.V); + } + return this.V; + }, + get diagonalMatrix() { + return __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].diag(this.s); + }, + solve: function (value) { + + var Y = value, + e = this.threshold, + scols = this.s.length, + Ls = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(scols, scols), + i; + + for (i = 0; i < scols; i++) { + if (Math.abs(this.s[i]) <= e) { + Ls[i][i] = 0; + } else { + Ls[i][i] = 1 / this.s[i]; + } + } + + var U = this.U; + var V = this.rightSingularVectors; + + var VL = V.mmul(Ls), + vrows = V.rows, + urows = U.length, + VLU = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].zeros(vrows, urows), + j, k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < scols; k++) { + sum += VL[i][k] * U[j][k]; + } + VLU[i][j] = sum; + } + } + + return VLU.mmul(Y); + }, + solveForDiagonal: function (value) { + return this.solve(__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].diag(value)); + }, + inverse: function () { + var V = this.V; + var e = this.threshold, + vrows = V.length, + vcols = V[0].length, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](vrows, this.s.length), + i, j; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < vcols; j++) { + if (Math.abs(this.s[j]) > e) { + X[i][j] = V[i][j] / this.s[j]; + } else { + X[i][j] = 0; + } + } + } + + var U = this.U; + + var urows = U.length, + ucols = U[0].length, + Y = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](vrows, urows), + k, sum; + + for (i = 0; i < vrows; i++) { + for (j = 0; j < urows; j++) { + sum = 0; + for (k = 0; k < ucols; k++) { + sum += X[i][k] * U[j][k]; + } + Y[i][j] = sum; + } + } + + return Y; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (SingularValueDecomposition); + + +/***/ }), +/* 73 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(7); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return __WEBPACK_IMPORTED_MODULE_0__matrix__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Matrix", function() { return __WEBPACK_IMPORTED_MODULE_0__matrix__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__ = __webpack_require__(35); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "abstractMatrix", function() { return __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__decompositions__ = __webpack_require__(232); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "solve", function() { return __WEBPACK_IMPORTED_MODULE_2__decompositions__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "inverse", function() { return __WEBPACK_IMPORTED_MODULE_2__decompositions__["b"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__dc_svd_js__ = __webpack_require__(72); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "SingularValueDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_3__dc_svd_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "SVD", function() { return __WEBPACK_IMPORTED_MODULE_3__dc_svd_js__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__dc_evd_js__ = __webpack_require__(231); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "EigenvalueDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_4__dc_evd_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "EVD", function() { return __WEBPACK_IMPORTED_MODULE_4__dc_evd_js__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__dc_cholesky_js__ = __webpack_require__(230); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CholeskyDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_5__dc_cholesky_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CHO", function() { return __WEBPACK_IMPORTED_MODULE_5__dc_cholesky_js__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__dc_lu_js__ = __webpack_require__(36); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "LuDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_6__dc_lu_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "LU", function() { return __WEBPACK_IMPORTED_MODULE_6__dc_lu_js__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__dc_qr_js__ = __webpack_require__(71); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "QrDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_7__dc_qr_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "QR", function() { return __WEBPACK_IMPORTED_MODULE_7__dc_qr_js__["a"]; }); + + + + + + + + + + + +/***/ }), +/* 74 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function compareNumbers(a, b) { + return a - b; +} + +/** + * Computes the sum of the given values + * @param {Array} values + * @returns {number} + */ +exports.sum = function sum(values) { + var sum = 0; + for (var i = 0; i < values.length; i++) { + sum += values[i]; + } + return sum; +}; + +/** + * Computes the maximum of the given values + * @param {Array} values + * @returns {number} + */ +exports.max = function max(values) { + var max = -Infinity; + var l = values.length; + for (var i = 0; i < l; i++) { + if (values[i] > max) max = values[i]; + } + return max; +}; + +/** + * Computes the minimum of the given values + * @param {Array} values + * @returns {number} + */ +exports.min = function min(values) { + var min = Infinity; + var l = values.length; + for (var i = 0; i < l; i++) { + if (values[i] < min) min = values[i]; + } + return min; +}; + +/** + * Computes the min and max of the given values + * @param {Array} values + * @returns {{min: number, max: number}} + */ +exports.minMax = function minMax(values) { + var min = Infinity; + var max = -Infinity; + var l = values.length; + for (var i = 0; i < l; i++) { + if (values[i] < min) min = values[i]; + if (values[i] > max) max = values[i]; + } + return { + min: min, + max: max + }; +}; + +/** + * Computes the arithmetic mean of the given values + * @param {Array} values + * @returns {number} + */ +exports.arithmeticMean = function arithmeticMean(values) { + var sum = 0; + var l = values.length; + for (var i = 0; i < l; i++) { + sum += values[i]; + } + return sum / l; +}; + +/** + * {@link arithmeticMean} + */ +exports.mean = exports.arithmeticMean; + +/** + * Computes the geometric mean of the given values + * @param {Array} values + * @returns {number} + */ +exports.geometricMean = function geometricMean(values) { + var mul = 1; + var l = values.length; + for (var i = 0; i < l; i++) { + mul *= values[i]; + } + return Math.pow(mul, 1 / l); +}; + +/** + * Computes the mean of the log of the given values + * If the return value is exponentiated, it gives the same result as the + * geometric mean. + * @param {Array} values + * @returns {number} + */ +exports.logMean = function logMean(values) { + var lnsum = 0; + var l = values.length; + for (var i = 0; i < l; i++) { + lnsum += Math.log(values[i]); + } + return lnsum / l; +}; + +/** + * Computes the weighted grand mean for a list of means and sample sizes + * @param {Array} means - Mean values for each set of samples + * @param {Array} samples - Number of original values for each set of samples + * @returns {number} + */ +exports.grandMean = function grandMean(means, samples) { + var sum = 0; + var n = 0; + var l = means.length; + for (var i = 0; i < l; i++) { + sum += samples[i] * means[i]; + n += samples[i]; + } + return sum / n; +}; + +/** + * Computes the truncated mean of the given values using a given percentage + * @param {Array} values + * @param {number} percent - The percentage of values to keep (range: [0,1]) + * @param {boolean} [alreadySorted=false] + * @returns {number} + */ +exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) { + if (alreadySorted === undefined) alreadySorted = false; + if (!alreadySorted) { + values = values.slice().sort(compareNumbers); + } + var l = values.length; + var k = Math.floor(l * percent); + var sum = 0; + for (var i = k; i < (l - k); i++) { + sum += values[i]; + } + return sum / (l - 2 * k); +}; + +/** + * Computes the harmonic mean of the given values + * @param {Array} values + * @returns {number} + */ +exports.harmonicMean = function harmonicMean(values) { + var sum = 0; + var l = values.length; + for (var i = 0; i < l; i++) { + if (values[i] === 0) { + throw new RangeError('value at index ' + i + 'is zero'); + } + sum += 1 / values[i]; + } + return l / sum; +}; + +/** + * Computes the contraharmonic mean of the given values + * @param {Array} values + * @returns {number} + */ +exports.contraHarmonicMean = function contraHarmonicMean(values) { + var r1 = 0; + var r2 = 0; + var l = values.length; + for (var i = 0; i < l; i++) { + r1 += values[i] * values[i]; + r2 += values[i]; + } + if (r2 < 0) { + throw new RangeError('sum of values is negative'); + } + return r1 / r2; +}; + +/** + * Computes the median of the given values + * @param {Array} values + * @param {boolean} [alreadySorted=false] + * @returns {number} + */ +exports.median = function median(values, alreadySorted) { + if (alreadySorted === undefined) alreadySorted = false; + if (!alreadySorted) { + values = values.slice().sort(compareNumbers); + } + var l = values.length; + var half = Math.floor(l / 2); + if (l % 2 === 0) { + return (values[half - 1] + values[half]) * 0.5; + } else { + return values[half]; + } +}; + +/** + * Computes the variance of the given values + * @param {Array} values + * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. + * @returns {number} + */ +exports.variance = function variance(values, unbiased) { + if (unbiased === undefined) unbiased = true; + var theMean = exports.mean(values); + var theVariance = 0; + var l = values.length; + + for (var i = 0; i < l; i++) { + var x = values[i] - theMean; + theVariance += x * x; + } + + if (unbiased) { + return theVariance / (l - 1); + } else { + return theVariance / l; + } +}; + +/** + * Computes the standard deviation of the given values + * @param {Array} values + * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. + * @returns {number} + */ +exports.standardDeviation = function standardDeviation(values, unbiased) { + return Math.sqrt(exports.variance(values, unbiased)); +}; + +exports.standardError = function standardError(values) { + return exports.standardDeviation(values) / Math.sqrt(values.length); +}; + +exports.quartiles = function quartiles(values, alreadySorted) { + if (typeof(alreadySorted) === 'undefined') alreadySorted = false; + if (!alreadySorted) { + values = values.slice(); + values.sort(compareNumbers); + } + + var quart = values.length / 4; + var q1 = values[Math.ceil(quart) - 1]; + var q2 = exports.median(values, true); + var q3 = values[Math.ceil(quart * 3) - 1]; + + return {q1: q1, q2: q2, q3: q3}; +}; + +exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) { + return Math.sqrt(exports.pooledVariance(samples, unbiased)); +}; + +exports.pooledVariance = function pooledVariance(samples, unbiased) { + if (typeof(unbiased) === 'undefined') unbiased = true; + var sum = 0; + var length = 0, l = samples.length; + for (var i = 0; i < l; i++) { + var values = samples[i]; + var vari = exports.variance(values); + + sum += (values.length - 1) * vari; + + if (unbiased) + length += values.length - 1; + else + length += values.length; + } + return sum / length; +}; + +exports.mode = function mode(values) { + var l = values.length, + itemCount = new Array(l), + i; + for (i = 0; i < l; i++) { + itemCount[i] = 0; + } + var itemArray = new Array(l); + var count = 0; + + for (i = 0; i < l; i++) { + var index = itemArray.indexOf(values[i]); + if (index >= 0) + itemCount[index]++; + else { + itemArray[count] = values[i]; + itemCount[count] = 1; + count++; + } + } + + var maxValue = 0, maxIndex = 0; + for (i = 0; i < count; i++) { + if (itemCount[i] > maxValue) { + maxValue = itemCount[i]; + maxIndex = i; + } + } + + return itemArray[maxIndex]; +}; + +exports.covariance = function covariance(vector1, vector2, unbiased) { + if (typeof(unbiased) === 'undefined') unbiased = true; + var mean1 = exports.mean(vector1); + var mean2 = exports.mean(vector2); + + if (vector1.length !== vector2.length) + throw "Vectors do not have the same dimensions"; + + var cov = 0, l = vector1.length; + for (var i = 0; i < l; i++) { + var x = vector1[i] - mean1; + var y = vector2[i] - mean2; + cov += x * y; + } + + if (unbiased) + return cov / (l - 1); + else + return cov / l; +}; + +exports.skewness = function skewness(values, unbiased) { + if (typeof(unbiased) === 'undefined') unbiased = true; + var theMean = exports.mean(values); + + var s2 = 0, s3 = 0, l = values.length; + for (var i = 0; i < l; i++) { + var dev = values[i] - theMean; + s2 += dev * dev; + s3 += dev * dev * dev; + } + var m2 = s2 / l; + var m3 = s3 / l; + + var g = m3 / (Math.pow(m2, 3 / 2.0)); + if (unbiased) { + var a = Math.sqrt(l * (l - 1)); + var b = l - 2; + return (a / b) * g; + } + else { + return g; + } +}; + +exports.kurtosis = function kurtosis(values, unbiased) { + if (typeof(unbiased) === 'undefined') unbiased = true; + var theMean = exports.mean(values); + var n = values.length, s2 = 0, s4 = 0; + + for (var i = 0; i < n; i++) { + var dev = values[i] - theMean; + s2 += dev * dev; + s4 += dev * dev * dev * dev; + } + var m2 = s2 / n; + var m4 = s4 / n; + + if (unbiased) { + var v = s2 / (n - 1); + var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3)); + var b = s4 / (v * v); + var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3)); + + return a * b - 3 * c; + } + else { + return m4 / (m2 * m2) - 3; + } +}; + +exports.entropy = function entropy(values, eps) { + if (typeof(eps) === 'undefined') eps = 0; + var sum = 0, l = values.length; + for (var i = 0; i < l; i++) + sum += values[i] * Math.log(values[i] + eps); + return -sum; +}; + +exports.weightedMean = function weightedMean(values, weights) { + var sum = 0, l = values.length; + for (var i = 0; i < l; i++) + sum += values[i] * weights[i]; + return sum; +}; + +exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) { + return Math.sqrt(exports.weightedVariance(values, weights)); +}; + +exports.weightedVariance = function weightedVariance(values, weights) { + var theMean = exports.weightedMean(values, weights); + var vari = 0, l = values.length; + var a = 0, b = 0; + + for (var i = 0; i < l; i++) { + var z = values[i] - theMean; + var w = weights[i]; + + vari += w * (z * z); + b += w; + a += w * w; + } + + return vari * (b / (b * b - a)); +}; + +exports.center = function center(values, inPlace) { + if (typeof(inPlace) === 'undefined') inPlace = false; + + var result = values; + if (!inPlace) + result = values.slice(); + + var theMean = exports.mean(result), l = result.length; + for (var i = 0; i < l; i++) + result[i] -= theMean; +}; + +exports.standardize = function standardize(values, standardDev, inPlace) { + if (typeof(standardDev) === 'undefined') standardDev = exports.standardDeviation(values); + if (typeof(inPlace) === 'undefined') inPlace = false; + var l = values.length; + var result = inPlace ? values : new Array(l); + for (var i = 0; i < l; i++) + result[i] = values[i] / standardDev; + return result; +}; + +exports.cumulativeSum = function cumulativeSum(array) { + var l = array.length; + var result = new Array(l); + result[0] = array[0]; + for (var i = 1; i < l; i++) + result[i] = result[i - 1] + array[i]; + return result; +}; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports) { + +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) + ]; +}; + +module.exports = NodeSquare; + +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function compareNumbers(a, b) { + return a - b; +} + +/** + * Computes the sum of the given values + * @param {Array} values + * @returns {number} + */ +exports.sum = function sum(values) { + var sum = 0; + for (var i = 0; i < values.length; i++) { + sum += values[i]; + } + return sum; +}; + +/** + * Computes the maximum of the given values + * @param {Array} values + * @returns {number} + */ +exports.max = function max(values) { + var max = values[0]; + var l = values.length; + for (var i = 1; i < l; i++) { + if (values[i] > max) max = values[i]; + } + return max; +}; + +/** + * Computes the minimum of the given values + * @param {Array} values + * @returns {number} + */ +exports.min = function min(values) { + var min = values[0]; + var l = values.length; + for (var i = 1; i < l; i++) { + if (values[i] < min) min = values[i]; + } + return min; +}; + +/** + * Computes the min and max of the given values + * @param {Array} values + * @returns {{min: number, max: number}} + */ +exports.minMax = function minMax(values) { + var min = values[0]; + var max = values[0]; + var l = values.length; + for (var i = 1; i < l; i++) { + if (values[i] < min) min = values[i]; + if (values[i] > max) max = values[i]; + } + return { + min: min, + max: max + }; +}; + +/** + * Computes the arithmetic mean of the given values + * @param {Array} values + * @returns {number} + */ +exports.arithmeticMean = function arithmeticMean(values) { + var sum = 0; + var l = values.length; + for (var i = 0; i < l; i++) { + sum += values[i]; + } + return sum / l; +}; + +/** + * {@link arithmeticMean} + */ +exports.mean = exports.arithmeticMean; + +/** + * Computes the geometric mean of the given values + * @param {Array} values + * @returns {number} + */ +exports.geometricMean = function geometricMean(values) { + var mul = 1; + var l = values.length; + for (var i = 0; i < l; i++) { + mul *= values[i]; + } + return Math.pow(mul, 1 / l); +}; + +/** + * Computes the mean of the log of the given values + * If the return value is exponentiated, it gives the same result as the + * geometric mean. + * @param {Array} values + * @returns {number} + */ +exports.logMean = function logMean(values) { + var lnsum = 0; + var l = values.length; + for (var i = 0; i < l; i++) { + lnsum += Math.log(values[i]); + } + return lnsum / l; +}; + +/** + * Computes the weighted grand mean for a list of means and sample sizes + * @param {Array} means - Mean values for each set of samples + * @param {Array} samples - Number of original values for each set of samples + * @returns {number} + */ +exports.grandMean = function grandMean(means, samples) { + var sum = 0; + var n = 0; + var l = means.length; + for (var i = 0; i < l; i++) { + sum += samples[i] * means[i]; + n += samples[i]; + } + return sum / n; +}; + +/** + * Computes the truncated mean of the given values using a given percentage + * @param {Array} values + * @param {number} percent - The percentage of values to keep (range: [0,1]) + * @param {boolean} [alreadySorted=false] + * @returns {number} + */ +exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) { + if (alreadySorted === undefined) alreadySorted = false; + if (!alreadySorted) { + values = [].concat(values).sort(compareNumbers); + } + var l = values.length; + var k = Math.floor(l * percent); + var sum = 0; + for (var i = k; i < (l - k); i++) { + sum += values[i]; + } + return sum / (l - 2 * k); +}; + +/** + * Computes the harmonic mean of the given values + * @param {Array} values + * @returns {number} + */ +exports.harmonicMean = function harmonicMean(values) { + var sum = 0; + var l = values.length; + for (var i = 0; i < l; i++) { + if (values[i] === 0) { + throw new RangeError('value at index ' + i + 'is zero'); + } + sum += 1 / values[i]; + } + return l / sum; +}; + +/** + * Computes the contraharmonic mean of the given values + * @param {Array} values + * @returns {number} + */ +exports.contraHarmonicMean = function contraHarmonicMean(values) { + var r1 = 0; + var r2 = 0; + var l = values.length; + for (var i = 0; i < l; i++) { + r1 += values[i] * values[i]; + r2 += values[i]; + } + if (r2 < 0) { + throw new RangeError('sum of values is negative'); + } + return r1 / r2; +}; + +/** + * Computes the median of the given values + * @param {Array} values + * @param {boolean} [alreadySorted=false] + * @returns {number} + */ +exports.median = function median(values, alreadySorted) { + if (alreadySorted === undefined) alreadySorted = false; + if (!alreadySorted) { + values = [].concat(values).sort(compareNumbers); + } + var l = values.length; + var half = Math.floor(l / 2); + if (l % 2 === 0) { + return (values[half - 1] + values[half]) * 0.5; + } else { + return values[half]; + } +}; + +/** + * Computes the variance of the given values + * @param {Array} values + * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. + * @returns {number} + */ +exports.variance = function variance(values, unbiased) { + if (unbiased === undefined) unbiased = true; + var theMean = exports.mean(values); + var theVariance = 0; + var l = values.length; + + for (var i = 0; i < l; i++) { + var x = values[i] - theMean; + theVariance += x * x; + } + + if (unbiased) { + return theVariance / (l - 1); + } else { + return theVariance / l; + } +}; + +/** + * Computes the standard deviation of the given values + * @param {Array} values + * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. + * @returns {number} + */ +exports.standardDeviation = function standardDeviation(values, unbiased) { + return Math.sqrt(exports.variance(values, unbiased)); +}; + +exports.standardError = function standardError(values) { + return exports.standardDeviation(values) / Math.sqrt(values.length); +}; + +/** + * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76- + * Calculate the standard deviation via the Median of the absolute deviation + * The formula for the standard deviation only holds for Gaussian random variables. + * @returns {{mean: number, stdev: number}} + */ +exports.robustMeanAndStdev = function robustMeanAndStdev(y) { + var mean = 0, stdev = 0; + var length = y.length, i = 0; + for (i = 0; i < length; i++) { + mean += y[i]; + } + mean /= length; + var averageDeviations = new Array(length); + for (i = 0; i < length; i++) + averageDeviations[i] = Math.abs(y[i] - mean); + averageDeviations.sort(compareNumbers); + if (length % 2 === 1) { + stdev = averageDeviations[(length - 1) / 2] / 0.6745; + } else { + stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745; + } + + return { + mean: mean, + stdev: stdev + }; +}; + +exports.quartiles = function quartiles(values, alreadySorted) { + if (typeof (alreadySorted) === 'undefined') alreadySorted = false; + if (!alreadySorted) { + values = [].concat(values).sort(compareNumbers); + } + + var quart = values.length / 4; + var q1 = values[Math.ceil(quart) - 1]; + var q2 = exports.median(values, true); + var q3 = values[Math.ceil(quart * 3) - 1]; + + return {q1: q1, q2: q2, q3: q3}; +}; + +exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) { + return Math.sqrt(exports.pooledVariance(samples, unbiased)); +}; + +exports.pooledVariance = function pooledVariance(samples, unbiased) { + if (typeof (unbiased) === 'undefined') unbiased = true; + var sum = 0; + var length = 0, l = samples.length; + for (var i = 0; i < l; i++) { + var values = samples[i]; + var vari = exports.variance(values); + + sum += (values.length - 1) * vari; + + if (unbiased) + length += values.length - 1; + else + length += values.length; + } + return sum / length; +}; + +exports.mode = function mode(values) { + var l = values.length, + itemCount = new Array(l), + i; + for (i = 0; i < l; i++) { + itemCount[i] = 0; + } + var itemArray = new Array(l); + var count = 0; + + for (i = 0; i < l; i++) { + var index = itemArray.indexOf(values[i]); + if (index >= 0) + itemCount[index]++; + else { + itemArray[count] = values[i]; + itemCount[count] = 1; + count++; + } + } + + var maxValue = 0, maxIndex = 0; + for (i = 0; i < count; i++) { + if (itemCount[i] > maxValue) { + maxValue = itemCount[i]; + maxIndex = i; + } + } + + return itemArray[maxIndex]; +}; + +exports.covariance = function covariance(vector1, vector2, unbiased) { + if (typeof (unbiased) === 'undefined') unbiased = true; + var mean1 = exports.mean(vector1); + var mean2 = exports.mean(vector2); + + if (vector1.length !== vector2.length) + throw 'Vectors do not have the same dimensions'; + + var cov = 0, l = vector1.length; + for (var i = 0; i < l; i++) { + var x = vector1[i] - mean1; + var y = vector2[i] - mean2; + cov += x * y; + } + + if (unbiased) + return cov / (l - 1); + else + return cov / l; +}; + +exports.skewness = function skewness(values, unbiased) { + if (typeof (unbiased) === 'undefined') unbiased = true; + var theMean = exports.mean(values); + + var s2 = 0, s3 = 0, l = values.length; + for (var i = 0; i < l; i++) { + var dev = values[i] - theMean; + s2 += dev * dev; + s3 += dev * dev * dev; + } + var m2 = s2 / l; + var m3 = s3 / l; + + var g = m3 / (Math.pow(m2, 3 / 2.0)); + if (unbiased) { + var a = Math.sqrt(l * (l - 1)); + var b = l - 2; + return (a / b) * g; + } else { + return g; + } +}; + +exports.kurtosis = function kurtosis(values, unbiased) { + if (typeof (unbiased) === 'undefined') unbiased = true; + var theMean = exports.mean(values); + var n = values.length, s2 = 0, s4 = 0; + + for (var i = 0; i < n; i++) { + var dev = values[i] - theMean; + s2 += dev * dev; + s4 += dev * dev * dev * dev; + } + var m2 = s2 / n; + var m4 = s4 / n; + + if (unbiased) { + var v = s2 / (n - 1); + var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3)); + var b = s4 / (v * v); + var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3)); + + return a * b - 3 * c; + } else { + return m4 / (m2 * m2) - 3; + } +}; + +exports.entropy = function entropy(values, eps) { + if (typeof (eps) === 'undefined') eps = 0; + var sum = 0, l = values.length; + for (var i = 0; i < l; i++) + sum += values[i] * Math.log(values[i] + eps); + return -sum; +}; + +exports.weightedMean = function weightedMean(values, weights) { + var sum = 0, l = values.length; + for (var i = 0; i < l; i++) + sum += values[i] * weights[i]; + return sum; +}; + +exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) { + return Math.sqrt(exports.weightedVariance(values, weights)); +}; + +exports.weightedVariance = function weightedVariance(values, weights) { + var theMean = exports.weightedMean(values, weights); + var vari = 0, l = values.length; + var a = 0, b = 0; + + for (var i = 0; i < l; i++) { + var z = values[i] - theMean; + var w = weights[i]; + + vari += w * (z * z); + b += w; + a += w * w; + } + + return vari * (b / (b * b - a)); +}; + +exports.center = function center(values, inPlace) { + if (typeof (inPlace) === 'undefined') inPlace = false; + + var result = values; + if (!inPlace) + result = [].concat(values); + + var theMean = exports.mean(result), l = result.length; + for (var i = 0; i < l; i++) + result[i] -= theMean; +}; + +exports.standardize = function standardize(values, standardDev, inPlace) { + if (typeof (standardDev) === 'undefined') standardDev = exports.standardDeviation(values); + if (typeof (inPlace) === 'undefined') inPlace = false; + var l = values.length; + var result = inPlace ? values : new Array(l); + for (var i = 0; i < l; i++) + result[i] = values[i] / standardDev; + return result; +}; + +exports.cumulativeSum = function cumulativeSum(array) { + var l = array.length; + var result = new Array(l); + result[0] = array[0]; + for (var i = 1; i < l; i++) + result[i] = result[i - 1] + array[i]; + return result; +}; + + +/***/ }), +/* 77 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var eightBits = __webpack_require__(103); + +/** + * Count the number of true values in an array + * @param {Array} arr + * @return {number} + */ +function count(arr) { + var c = 0; + for (var i = 0; i < arr.length; i++) { + c += eightBits[arr[i] & 0xff] + eightBits[(arr[i] >> 8) & 0xff] + eightBits[(arr[i] >> 16) & 0xff] + eightBits[(arr[i] >> 24) & 0xff]; + } + return c; +} + +/** + * Logical AND operation + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ +function and(arr1, arr2) { + var ans = new Array(arr1.length); + for (var i = 0; i < arr1.length; i++) + ans[i] = arr1[i] & arr2[i]; + return ans; +} + +/** + * Logical OR operation + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ +function or(arr1, arr2) { + var ans = new Array(arr1.length); + for (var i = 0; i < arr1.length; i++) + ans[i] = arr1[i] | arr2[i]; + return ans; +} + +/** + * Logical XOR operation + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ +function xor(arr1, arr2) { + var ans = new Array(arr1.length); + for (var i = 0; i < arr1.length; i++) + ans[i] = arr1[i] ^ arr2[i]; + return ans; +} + +/** + * Logical NOT operation + * @param {Array} arr + * @return {Array} + */ +function not(arr) { + var ans = new Array(arr.length); + for (var i = 0; i < ans.length; i++) + ans[i] = ~arr[i]; + return ans; +} + +/** + * Gets the n value of array arr + * @param {Array} arr + * @param {number} n + * @return {boolean} + */ +function getBit(arr, n) { + var index = n >> 5; // Same as Math.floor(n/32) + var mask = 1 << (31 - n % 32); + return Boolean(arr[index] & mask); +} + +/** + * Sets the n value of array arr to the value val + * @param {Array} arr + * @param {number} n + * @param {boolean} val + * @return {Array} + */ +function setBit(arr, n, val) { + var index = n >> 5; // Same as Math.floor(n/32) + var mask = 1 << (31 - n % 32); + if (val) + arr[index] = mask | arr[index]; + else + arr[index] = ~mask & arr[index]; + return arr; +} + +/** + * Translates an array of numbers to a string of bits + * @param {Array} arr + * @returns {string} + */ +function toBinaryString(arr) { + var str = ''; + for (var i = 0; i < arr.length; i++) { + var obj = (arr[i] >>> 0).toString(2); + str += '00000000000000000000000000000000'.substr(obj.length) + obj; + } + return str; +} + +/** + * Creates an array of numbers based on a string of bits + * @param {string} str + * @returns {Array} + */ +function parseBinaryString(str) { + var len = str.length / 32; + var ans = new Array(len); + for (var i = 0; i < len; i++) { + ans[i] = parseInt(str.substr(i*32, 32), 2) | 0; + } + return ans; +} + +/** + * Translates an array of numbers to a hex string + * @param {Array} arr + * @returns {string} + */ +function toHexString(arr) { + var str = ''; + for (var i = 0; i < arr.length; i++) { + var obj = (arr[i] >>> 0).toString(16); + str += '00000000'.substr(obj.length) + obj; + } + return str; +} + +/** + * Creates an array of numbers based on a hex string + * @param {string} str + * @returns {Array} + */ +function parseHexString(str) { + var len = str.length / 8; + var ans = new Array(len); + for (var i = 0; i < len; i++) { + ans[i] = parseInt(str.substr(i*8, 8), 16) | 0; + } + return ans; +} + +/** + * Creates a human readable string of the array + * @param {Array} arr + * @returns {string} + */ +function toDebug(arr) { + var binary = toBinaryString(arr); + var str = ''; + for (var i = 0; i < arr.length; i++) { + str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':'; + for (var j = 0; j < 32; j += 4) { + str += ' ' + binary.substr(i * 32 + j, 4); + } + if (i < arr.length - 1) str += '\n'; + } + return str +} + +module.exports = { + count: count, + and: and, + or: or, + xor: xor, + not: not, + getBit: getBit, + setBit: setBit, + toBinaryString: toBinaryString, + parseBinaryString: parseBinaryString, + toHexString: toHexString, + parseHexString: parseHexString, + toDebug: toDebug +}; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const ConfusionMatrix = __webpack_require__(105); + +const CV = {}; +const combinations = __webpack_require__(104); + +/** + * 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 {constructor} Classifier - The classifier 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. + * @returns {ConfusionMatrix} - The cross-validation confusion matrix + */ +CV.leaveOneOut = function (Classifier, features, labels, classifierOptions) { + 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 Classifier - The classifier 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 + * @returns {ConfusionMatrix} - The cross-validation confusion matrix + */ +CV.leavePOut = function (Classifier, features, labels, classifierOptions, p) { + check(features, labels); + const distinct = getDistinct(labels); + const confusionMatrix = initMatrix(distinct.length, distinct.length); + var i, N = features.length; + var gen = combinations(p, N); + var allIdx = new Array(N); + for (i = 0; i < N; i++) { + allIdx[i] = i; + } + for (const testIdx of gen) { + var trainIdx = allIdx.slice(); + + for (i = testIdx.length - 1; i >= 0; i--) { + trainIdx.splice(testIdx[i], 1); + } + + 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 Classifier - The classifier 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 + * @returns {ConfusionMatrix} - The cross-validation confusion matrix + */ +CV.kFold = function (Classifier, features, labels, classifierOptions, k) { + 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; + } + + var l = Math.floor(N / k); + // create random k-folds + var current = []; + var folds = []; + while (allIdx.length) { + var randi = Math.floor(Math.random() * allIdx.length); + current.push(allIdx[randi]); + allIdx.splice(randi, 1); + if (current.length === l) { + folds.push(current); + current = []; + } + } + if (current.length) folds.push(current); + folds = folds.slice(0, k); + + + for (i = 0; i < folds.length; i++) { + var testIdx = folds[i]; + var trainIdx = []; + for (var j = 0; j < folds.length; j++) { + if (j !== i) trainIdx = trainIdx.concat(folds[j]); + } + + 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) { + var 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) { + var testFeatures = testIdx.map(function (index) { + return features[index]; + }); + var trainFeatures = trainIdx.map(function (index) { + return features[index]; + }); + var testLabels = testIdx.map(function (index) { + return labels[index]; + }); + var trainLabels = trainIdx.map(function (index) { + return labels[index]; + }); + + var classifier = new Classifier(classifierOptions); + classifier.train(trainFeatures, trainLabels); + var predictedLabels = classifier.predict(testFeatures); + for (var i = 0; i < predictedLabels.length; i++) { + confusionMatrix[distinct.indexOf(testLabels[i])][distinct.indexOf(predictedLabels[i])]++; + } +} + +module.exports = CV; + + +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const Matrix = __webpack_require__(0); + +const Layer = __webpack_require__(55); +const OutputLayer = __webpack_require__(152); +const Utils = __webpack_require__(57); +const ACTIVATION_FUNCTIONS = __webpack_require__(56); + +class FeedForwardNeuralNetworks { + + /** + * Create a new Feedforword neural network model. + * @param {object} options + * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers. + * @oaram {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). + * @poram {number} [options.regularization=0.01] - Regularization parameter af the neural net. + * @poram {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 === undefined ? [10] : options.hiddenLayers; + this.iterations = options.iterations === undefined ? 50 : options.iterations; + + this.learningRate = options.learningRate === undefined ? 0.01 : options.learningRate; + //this.momentum = options.momentum === undefined ? 0.1 : options.momentum; + this.regularization = options.regularization === undefined ? 0.01 : options.regularization; + + this.activation = options.activation === undefined ? 'tanh' : options.activation; + this.activationParam = options.activationParam === undefined ? 1 : options.activationParam; + if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) { + this.activation = 'tanh'; + } + } + } + + /** + * 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 = Matrix.checkMatrix(features); + this.dicts = Utils.dictOutputs(labels); + + var inputSize = features.columns; + var outputSize = Object.keys(this.dicts.inputs).length; + + this.buildNetwork(inputSize, outputSize); + + for (var i = 0; i < this.iterations; ++i) { + var probabilities = this.propagate(features); + this.backpropagation(features, labels, probabilities); + } + } + + /** + * Propagate the input(training set) and retrives the probabilities of each class. + * @param {Matrix} X + * @return {Matrix} probabilities of each class. + */ + propagate(X) { + var input = X; + for (var i = 0; i < this.model.length; ++i) { + //console.log(i); + input = this.model[i].forward(input); + } + + // get probabilities + return input.divColumnVector(Utils.sumRow(input)); + } + + /** + * Function that applies the backpropagation algorithm on each layer of the network + * in order to fit the features and labels. + * @param {Matrix} features + * @param {Array} labels + * @param {Matrix} probabilities - probabilities of each class of the feature set. + */ + backpropagation(features, labels, probabilities) { + for (var i = 0; i < probabilities.length; ++i) { + probabilities[i][this.dicts.inputs[labels[i]]] -= 1; + } + + // remember, the last delta doesn't matter + var delta = probabilities; + for (i = this.model.length - 1; i >= 0; --i) { + var a = i > 0 ? this.model[i - 1].a : features; + delta = this.model[i].backpropagation(delta, a); + } + + 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 = 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 JSOM. + * @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); + } +} + +module.exports = FeedForwardNeuralNetworks; + + +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.agnes = __webpack_require__(154); +exports.diana = __webpack_require__(155); +//exports.birch = require('./birch'); +//exports.cure = require('./cure'); +//exports.chameleon = require('./chameleon'); + + +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const utils = __webpack_require__(61); +const init = __webpack_require__(179); +const KMeansResult = __webpack_require__(178); +const squaredDistance = __webpack_require__(1).squared; + +const defaultOptions = { + maxIterations: 100, + tolerance: 1e-6, + withIterations: false, + initialization: 'mostDistant', + distanceFunction: squaredDistance +}; + +/** + * Each step operation for kmeans + * @ignore + * @param {Array>} centers - the K centers in format [x,y,z,...] + * @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 + * @param {Object} [options] - Option object + * @param {Number} iterations - Current number of iterations + * @return {KMeansResult} + */ +function step(centers, data, clusterID, K, options, iterations) { + clusterID = utils.updateClusterID(data, centers, clusterID, options.distanceFunction); + var newCenters = utils.updateCenters(data, clusterID, K); + var converged = utils.converged(newCenters, centers, options.distanceFunction, options.tolerance); + return new KMeansResult(clusterID, newCenters, converged, iterations, options.distanceFunction); +} + +/** + * Generator version for the algorithm + * @ignore + * @param {Array>} centers - the K centers in format [x,y,z,...] + * @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 + * @param {Object} [options] - Option object + */ +function* kmeansGenerator(centers, data, clusterID, K, options) { + var converged = false; + var stepNumber = 0; + var stepResult; + while (!converged && (stepNumber < options.maxIterations)) { + stepResult = step(centers, data, clusterID, K, options, ++stepNumber); + yield stepResult.computeInformation(data); + converged = stepResult.converged; + centers = stepResult.centroids; + } +} + +/** + * 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 {String|Array>} [options.initialization = 'moreDistant'] - K centers in format [x,y,z,...] or a method for initialize the data: + * * `'random'` will choose K random different values. + * * `'mostDistant'` will choose the more distant points to a first random pick + * @returns {KMeansResult} - Cluster identifier for each data dot and centroids with the following fields: + * * `'clusters'`: Array of indexes for the clusters. + * * `'centroids'`: Array with the resulting centroids. + * * `'iterations'`: Number of iterations that took to converge + */ +function kmeans(data, K, options) { + options = Object.assign({}, defaultOptions, options); + + if (K <= 0 || K > data.length || !Number.isInteger(K)) { + throw new Error('K should be a positive integer bigger than the number of points'); + } + + 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 'random': + centers = init.random(data, K); + break; + case 'mostDistant': + centers = init.mostDistant(data, K, utils.calculateDistanceMatrix(data, options.distanceFunction)); + break; + default: + throw new Error('Unknown initialization method: "' + options.initialization + '"'); + } + } + + // infinite loop until convergence + if (options.maxIterations === 0) { + options.maxIterations = Number.MAX_VALUE; + } + + var clusterID = new Array(data.length); + if (options.withIterations) { + return kmeansGenerator(centers, data, clusterID, K, options); + } else { + var converged = false; + var stepNumber = 0; + var stepResult; + while (!converged && (stepNumber < options.maxIterations)) { + stepResult = step(centers, data, clusterID, K, options, ++stepNumber); + converged = stepResult.converged; + centers = stepResult.centroids; + } + return stepResult.computeInformation(data); + } +} + +module.exports = kmeans; + + +/***/ }), +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(181); + +/***/ }), +/* 83 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const errorCalculation = __webpack_require__(182); +const step = __webpack_require__(183); + +const defaultOptions = { + damping: undefined, + gradientDifference: 10e-2, + initialValues: undefined, + maxIterations: 100, + errorTolerance: 10e-3 +}; + +/** + * 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 = undefined] - Levenberg-Marquardt parameter + * @param {number} [options.gradientDifference = 10e-2] - Adjustment for decrease the damping parameter + * @param {Array} [options.initialValues = undefined] - Array of initial parameter values + * @param {number} [options.maxIterations = 100] - Maximum of allowed iterations + * @param {number} [options.errorTolerance = 10e-3] - Minimum uncertainty allowed for each point + * @return {{parameterValues: Array, parameterError: number, iterations: number}} + */ +function levenbergMarquardt(data, parameterizedFunction, options) { + // verify that damping is not undefined + if ((!options) || (!options.damping) || (options.damping <= 0)) { + throw new TypeError('The damping option should be a positive number'); + } + + // assign default values + options = Object.assign({}, defaultOptions, options); + + // fill with default value for initialValues + if (!options.initialValues) { + options.initialValues = new Array(parameterizedFunction.length); + + for (var i = 0; i < parameterizedFunction.length; i++) { + options.initialValues[i] = 1; + } + } + + // check that the data has the correct format + if (!data.x || !data.y) { + throw new TypeError('The data parameter should have a x and y elements'); + } else if ((data.x.constructor !== Array) || (data.x.length < 2) || + (data.y.constructor !== Array) || (data.y.length < 2)) { + throw new TypeError('The data parameter elements should be an array with more than 2 points'); + } + + const dataLen = data.x.length; + if (dataLen !== data.y.length) { + throw new RangeError('The data parameter elements should have the same size'); + } + + // initial parameters + var parameters = options.initialValues; + + // check errorCalculation + var error = errorCalculation(data, parameters, parameterizedFunction); + var converged = error <= options.errorTolerance; + + for (var iteration = 0; (iteration < options.maxIterations) && !converged; iteration++) { + // step function + parameters = step(data, parameters, options.damping, options.gradientDifference, parameterizedFunction); + + // reevaluate errorCalculation + error = errorCalculation(data, parameters, parameterizedFunction); + converged = error <= options.errorTolerance; + } + + + // return example + return { + parameterValues: parameters, + parameterError: error, + iterations: iteration + }; +} + +module.exports = levenbergMarquardt; + + +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = exports = __webpack_require__(65).NaiveBayes; +exports.separateClasses = __webpack_require__(65).separateClasses; + + +/***/ }), +/* 85 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var LM = __webpack_require__(107); +var math = LM.Matrix.algebra; +var Matrix = __webpack_require__(0); + +/** + * 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 + * @param c Constant parameters(Not used) + * @returns {*} + */ +function sumOfLorentzians(t,p,c){ + var nL = p.length/3,factor,i, j,p2, cols = t.rows; + var result = Matrix.zeros(t.length,1); + + for(i=0;imaxY) + maxY = y[i]; + } + } + else{ + //It is a colum matrix + if(typeof x[0] === "object"){ + for(i=0;imaxY) + maxY = y[i][0]; + } + } + } -module.exports = function czekanowskiSimilarity(a, b) { - var up = 0; - var down = 0; - for (var i = 0; i < a.length; i++) { - up += Math.min(a[i], b[i]); - down += a[i] + b[i]; + //} } - return 2 * up / down; -}; - - -/***/ }), -/* 31 */ -/***/ (function(module, exports) { - -module.exports = function tanimoto(a, b, bitvector) { - if (bitvector) { - var inter = 0, - union = 0; - for (var j = 0; j < a.length; j++) { - inter += a[j] && b[j]; - union += a[j] || b[j]; + else{ + //Looks like a column wise matrix [[x],[y]] + var nbPoints = nbSeries; + //if(nbPoints<3) + // throw new SizeException(nbPoints); + //else { + t = new Array(nbPoints);//new Matrix(nbPoints, 1); + y_data = new Array(nbPoints);//new Matrix(nbPoints, 1); + for (i = 0; i < nbPoints; i++) { + t[i] = xy[i][0]; + y_data[i] = xy[i][1]; + if(y_data[i]>maxY) + maxY = y_data[i]; } - if (union === 0) - return 1; - return inter / union; + //} } - else { - var ii = a.length, - p = 0, - q = 0, - m = 0; - for (var i = 0; i < ii ; i++) { - p += a[i]; - q += b[i]; - m += Math.min(a[i],b[i]); + for (i = 0; i < nbPoints; i++) { + y_data[i]/=maxY; + } + if(threshold){ + for (i = nbPoints-1; i >=0; i--) { + if(y_data[i]0) + return [(new Matrix([t])).transpose(),(new Matrix([y_data])).transpose(),maxY]; + return null; +} + +function sizeException(nbPoints) { + return new RangeError("Not enough points to perform the optimization: "+nbPoints +"< 3"); +} +module.exports.optimizeSingleLorentzian = optimizeSingleLorentzian; +module.exports.optimizeLorentzianSum = optimizeLorentzianSum; +module.exports.optimizeSingleGaussian = optimizeSingleGaussian; +module.exports.optimizeGaussianSum = optimizeGaussianSum; +module.exports.singleGaussian = singleGaussian; +module.exports.singleLorentzian = singleLorentzian; +module.exports.optimizeGaussianTrain = optimizeGaussianTrain; +module.exports.optimizeLorentzianTrain = optimizeLorentzianTrain; /***/ }), -/* 32 */ +/* 86 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var Matrix = __webpack_require__(0); +const Matrix = __webpack_require__(0); +const EVD = Matrix.DC.EVD; +const SVD = Matrix.DC.SVD; +const Stat = __webpack_require__(2).matrix; +const mean = Stat.mean; +const stdev = Stat.standardDeviation; -var Utils = __webpack_require__(34); -const ACTIVATION_FUNCTIONS = __webpack_require__(33); +const defaultOptions = { + isCovarianceMatrix: false, + center: true, + scale: false +}; -class Layer { - /** - * 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; +/** + * Creates new PCA (Principal Component Analysis) from the dataset + * @param {Matrix} dataset - dataset or covariance matrix + * @param {Object} options + * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix + * @param {boolean} [options.center=true] - should the data be centered (subtract the mean) + * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation) + * */ +class PCA { + constructor(dataset, options) { + if (dataset === true) { + const model = options; + this.center = model.center; + this.scale = model.scale; + this.means = model.means; + this.stdevs = model.stdevs; + this.U = Matrix.checkMatrix(model.U); + this.S = model.S; + return; + } - var selectedFunction = ACTIVATION_FUNCTIONS[options.activation]; - var params = selectedFunction.activation.length; + options = Object.assign({}, defaultOptions, options); - 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.center = false; + this.scale = false; + this.means = null; + this.stdevs = null; - this.activationFunction = function (i, j) { - this[i][j] = actFunction(this[i][j]); - }; - this.derivate = function (i, j) { - this[i][j] = derFunction(this[i][j]); - }; + if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset + this._computeFromCovarianceMatrix(dataset); + return; + } - if (options.model) { - // load model - this.W = Matrix.checkMatrix(options.W); - this.b = Matrix.checkMatrix(options.b); + var useCovarianceMatrix; + if (typeof options.useCovarianceMatrix === 'boolean') { + useCovarianceMatrix = options.useCovarianceMatrix; + } else { + useCovarianceMatrix = dataset.length > dataset[0].length; + } + if (useCovarianceMatrix) { // user provided a dataset but wants us to compute and use the covariance matrix + dataset = this._adjust(dataset, options); + const covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1); + this._computeFromCovarianceMatrix(covarianceMatrix); } else { - // default constructor + dataset = this._adjust(dataset, options); + var svd = new SVD(dataset, { + computeLeftSingularVectors: false, + computeRightSingularVectors: true, + autoTranspose: true + }); - this.W = Matrix.rand(this.inputSize, this.outputSize); - this.b = Matrix.zeros(1, this.outputSize); + this.U = svd.rightSingularVectors; - this.W.apply(function (i, j) { - this[i][j] /= Math.sqrt(options.inputSize); - }); + const singularValues = svd.diagonal; + const eigenvalues = new Array(singularValues.length); + for (var i = 0; i < singularValues.length; i++) { + eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1); + } + this.S = eigenvalues; + } + } + + /** + * Load a PCA model from JSON + * @param {Object} model + * @return {PCA} + */ + static load(model) { + if (model.name !== 'PCA') + throw new RangeError('Invalid model: ' + model.name); + return new PCA(true, model); + } + + /** + * Project the dataset into the PCA space + * @param {Matrix} dataset + * @return {Matrix} dataset projected in the PCA space + */ + predict(dataset) { + dataset = new Matrix(dataset); + + if (this.center) { + dataset.subRowVector(this.means); + if (this.scale) { + dataset.divRowVector(this.stdevs); + } } + + return dataset.mmul(this.U); } /** - * propagate the given input through the current layer. - * @param {Matrix} X - input. - * @return {Matrix} output at the current layer. + * Returns the proportion of variance for each component + * @return {[number]} */ - forward(X) { - var z = X.mmul(this.W).addRowVector(this.b); - z.apply(this.activationFunction); - this.a = z.clone(); - return z; + getExplainedVariance() { + var sum = 0; + for (var i = 0; i < this.S.length; i++) { + sum += this.S[i]; + } + return this.S.map(value => value / sum); } /** - * 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. + * Returns the cumulative proportion of variance + * @return {[number]} */ - backpropagation(delta, a) { - this.dW = a.transposeView().mmul(delta); - this.db = Utils.sumCol(delta); - - var aCopy = a.clone(); - return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate)); + getCumulativeVariance() { + var explained = this.getExplainedVariance(); + for (var i = 1; i < explained.length; i++) { + explained[i] += explained[i - 1]; + } + return explained; } /** - * Function that updates the weights at the current layer with the derivatives. + * Returns the Eigenvectors of the covariance matrix + * @returns {Matrix} */ - 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)); + getEigenvectors() { + return this.U; } /** - * Export the current layer to JSON. - * @return {object} model + * Returns the Eigenvalues (on the diagonal) + * @returns {[number]} */ - 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 - }; + getEigenvalues() { + return this.S; } /** - * Creates a new Layer with the given model. - * @param {object} model - * @return {Layer} + * Returns the standard deviations of the principal components + * @returns {[number]} */ - static load(model) { - if (model.model !== 'Layer') { - throw new RangeError('the current model is not a Layer model'); - } - return new Layer(model); - } - -} - -module.exports = Layer; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -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; + getStandardDeviations() { + return this.S.map(x => Math.sqrt(x)); } - return val; -} -function softExponentialPrime(val, param) { - if (param < 0) { - return 1 / (1 - param * (param + val)); - } else { - return Math.exp(param * val); + /** + * Returns the loadings matrix + * @return {Matrix} + */ + getLoadings() { + return this.U.transpose(); } -} -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 + /** + * Export the current model to a JSON object + * @return {Object} model + */ + toJSON() { + return { + name: 'PCA', + center: this.center, + scale: this.scale, + means: this.means, + stdevs: this.stdevs, + U: this.U, + S: this.S, + }; } -}; - -module.exports = ACTIVATION_FUNCTIONS; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + _adjust(dataset, options) { + this.center = !!options.center; + this.scale = !!options.scale; -var Matrix = __webpack_require__(0); + dataset = new Matrix(dataset); -/** - * Retrieves the sum at each row of the given matrix. - * @param {Matrix} matrix - * @return {Matrix} - */ -function sumRow(matrix) { - var sum = Matrix.zeros(matrix.rows, 1); - for (var i = 0; i < matrix.rows; ++i) { - for (var j = 0; j < matrix.columns; ++j) { - sum[i][0] += matrix[i][j]; + if (this.center) { + const means = mean(dataset); + const stdevs = this.scale ? stdev(dataset, means, true) : null; + this.means = means; + dataset.subRowVector(means); + if (this.scale) { + for (var i = 0; i < stdevs.length; i++) { + if (stdevs[i] === 0) { + throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i); + } + } + this.stdevs = stdevs; + dataset.divRowVector(stdevs); + } } - } - return sum; -} -/** - * Retrieves the sum at each column of the given matrix. - * @param {Matrix} matrix - * @return {Matrix} - */ -function sumCol(matrix) { - var sum = Matrix.zeros(1, matrix.columns); - for (var i = 0; i < matrix.rows; ++i) { - for (var j = 0; j < matrix.columns; ++j) { - sum[0][j] += matrix[i][j]; - } + return dataset; } - return sum; -} -/** - * 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 = {}, outputs = {}, l = array.length, index = 0; - for (var i = 0; i < l; i += 1) { - if (inputs[array[i]] === undefined) { - inputs[array[i]] = index; - outputs[index] = array[i]; - index++; + _computeFromCovarianceMatrix(dataset) { + const evd = new EVD(dataset, {assumeSymmetric: true}); + this.U = evd.eigenvectorMatrix; + for (var i = 0; i < this.U.length; i++) { + this.U[i].reverse(); } + this.S = evd.realEigenvalues.reverse(); } - - return { - inputs: inputs, - outputs: outputs - }; } -module.exports = { - dictOutputs: dictOutputs, - sumCol: sumCol, - sumRow: sumRow -}; +module.exports = PCA; /***/ }), -/* 35 */ +/* 87 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var Cluster = __webpack_require__(10); -var util = __webpack_require__(167); - -function ClusterLeaf (index) { - Cluster.call(this); - this.index = index; - this.distance = 0; - this.children = []; -} - -util.inherits(ClusterLeaf, Cluster); - -module.exports = ClusterLeaf; +const measures = __webpack_require__(197); +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'); + } + const rows = prediction.length; + const columns = prediction[0].length; + const isDistance = !options.max; -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { + const predP = []; -"use strict"; + 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] + }); + } + } + } + if (isDistance) { + predP.sort((a, b) => a.pred - b.pred); + } else { + predP.sort((a, b) => b.pred - a.pred); + } + + const cutoffs = this.cutoffs = [isDistance ? Number.MIN_VALUE : Number.MAX_VALUE]; + const fp = this.fp = [0]; + const tp = this.tp = [0]; -const nearestVector = __webpack_require__(147); + var nPos = 0; + var nNeg = 0; -/** - * Calculates the distance matrix for a given array of points - * @ignore - * @param {Array>} data - the [x,y,z,...] points to cluster - * @param {Function} distance - Distance function to use between the points - * @return {Array>} - matrix with the distance values - */ -function calculateDistanceMatrix(data, distance) { - var distanceMatrix = new Array(data.length); - for (var i = 0; i < data.length; ++i) { - for (var j = i; j < data.length; ++j) { - if (!distanceMatrix[i]) { - distanceMatrix[i] = new Array(data.length); + var currentPred = predP[0].pred; + var nTp = 0; + var nFp = 0; + for (var i = 0; i < predP.length; i++) { + if (predP[i].pred !== currentPred) { + cutoffs.push(currentPred); + fp.push(nFp); + tp.push(nTp); + currentPred = predP[i].pred; } - if (!distanceMatrix[j]) { - distanceMatrix[j] = new Array(data.length); + if (predP[i].targ) { + nPos++; + nTp++; + } else { + nNeg++; + nFp++; } - const dist = distance(data[i], data[j]); - distanceMatrix[i][j] = dist; - distanceMatrix[j][i] = dist; } - } - return distanceMatrix; -} + cutoffs.push(currentPred); + fp.push(nFp); + tp.push(nTp); -/** - * 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 - * @returns {Array} the cluster identifier for each data dot - */ -function updateClusterID(data, centers, clusterID, distance) { - for (var i = 0; i < data.length; i++) { - clusterID[i] = nearestVector(centers, data[i], {distanceFunction: distance}); - } - return clusterID; -} + 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); -/** - * Update the center values based in the new configurations of the clusters - * @ignore - * @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 - * @returns {Array} he K centers in format [x,y,z,...] - */ -function updateCenters(data, clusterID, K) { - const nDim = data[0].length; + for (var i = 0; i < l; i++) { + fn[i] = nPos - tp[i]; + tn[i] = nNeg - fp[i]; - // creates empty centers with 0 size - var centers = new Array(K); - var centersLen = new Array(K); - for (var i = 0; i < K; i++) { - centers[i] = new Array(nDim); - centersLen[i] = 0; - for (var j = 0; j < nDim; j++) { - centers[i][j] = 0; + nPosPred[i] = tp[i] + fp[i]; + nNegPred[i] = tn[i] + fn[i]; } + + this.nPos = nPos; + this.nNeg = nNeg; + this.nSamples = nPos + nNeg; } - // add the value for all dimensions of the point - for (var l = 0; l < data.length; l++) { - centersLen[clusterID[l]]++; - for (var dim = 0; dim < nDim; dim++) { - centers[clusterID[l]][dim] += data[l][dim]; + /** + * Computes a measure from the prediction object. + * + * Many measures are available and can be combined : + * To create a ROC curve, you need fpr and tpr + * To create a DET curve, you need fnr and fpr + * To create a Lift chart, you need rpp and lift + * + * Possible measures are : threshold (Threshold), acc (Accuracy), err (Error rate), + * fpr (False positive rate), tpr (True positive rate), fnr (False negative rate), tnr (True negative rate), ppv (Positive predictive value), + * npv (Negative predictive value), pcfall (Prediction-conditioned fallout), pcmiss (Prediction-conditioned miss), lift (Lift value), rpp (Rate of positive predictions), rnp (Rate of negative predictions) + * + * @param measure - The short name of the measure + * + * @return [number] + */ + getMeasure(measure) { + if (typeof measure !== 'string') { + throw new Error('No measure specified'); + } + if (!measures[measure]) { + throw new Error(`The specified measure (${measure}) does not exist`); } + return measures[measure](this); } - // divides by length - for (var id = 0; id < K; id++) { - for (var d = 0; d < nDim; d++) { - centers[id][d] /= centersLen[id]; + /** + * Returns the area under the ROC curve + */ + getAURC() { + const l = this.cutoffs.length; + const x = new Array(l); + const y = new Array(l); + for (var i = 0; i < l; i++) { + x[i] = this.fp[i] / this.nNeg; + y[i] = this.tp[i] / this.nPos; + } + var auc = 0; + for (i = 1; i < l; i++) { + auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]); } + return auc; } - 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} - */ -function converged(centers, oldCenters, distanceFunction, tolerance) { - for (var i = 0; i < centers.length; i++) { - if (distanceFunction(centers[i], oldCenters[i]) > tolerance) { - return false; + /** + * Returns the area under the DET curve + */ + getAUDC() { + const l = this.cutoffs.length; + const x = new Array(l); + const y = new Array(l); + for (var i = 0; i < l; i++) { + x[i] = this.fn[i] / this.nPos; + y[i] = this.fp[i] / this.nNeg; + } + var auc = 0; + for (i = 1; i < l; i++) { + auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]); } + return auc; } - return true; -} -exports.updateClusterID = updateClusterID; -exports.updateCenters = updateCenters; -exports.calculateDistanceMatrix = calculateDistanceMatrix; -exports.converged = converged; + getDistribution(options) { + options = options || {}; + var cutLength = this.cutoffs.length; + var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100; + var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100; + var interval = options.interval || Math.floor(((cutHigh - cutLow) / 20 * 10000000) - 1) / 10000000; // Trick to avoid the precision problem of float numbers + var xLabels = []; + var interValues = []; + var intraValues = []; + var interCumPercent = []; + var intraCumPercent = []; -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { + var nTP = this.tp[cutLength - 1], currentTP = 0; + var nFP = this.fp[cutLength - 1], currentFP = 0; -"use strict"; + for (var i = cutLow, j = (cutLength - 1); i <= cutHigh; i += interval) { + while (this.cutoffs[j] < i) + j--; + xLabels.push(i); -module.exports = abstractMatrix; + var thisTP = nTP - currentTP - this.tp[j]; + var thisFP = nFP - currentFP - this.fp[j]; -var LuDecomposition = __webpack_require__(38); -var arrayUtils = __webpack_require__(16); -var util = __webpack_require__(7); -var MatrixTransposeView = __webpack_require__(146); -var MatrixRowView = __webpack_require__(143); -var MatrixSubView = __webpack_require__(145); -var MatrixSelectionView = __webpack_require__(144); -var MatrixColumnView = __webpack_require__(140); -var MatrixFlipRowView = __webpack_require__(142); -var MatrixFlipColumnView = __webpack_require__(141); + currentTP += thisTP; + currentFP += thisFP; -function abstractMatrix(superCtor) { - if (superCtor === undefined) superCtor = Object; + interValues.push(thisFP); + intraValues.push(thisTP); - /** - * Real matrix - * @class Matrix - * @param {number|Array|Matrix} nRows - Number of rows of the new matrix, - * 2D array containing the data or Matrix instance to clone - * @param {number} [nColumns] - Number of columns of the new matrix - */ - class Matrix extends superCtor { - static get [Symbol.species]() { - return this; + interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100); + intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100); } - /** - * Constructs a Matrix with the chosen dimensions from a 1D array - * @param {number} newRows - Number of rows - * @param {number} newColumns - Number of columns - * @param {Array} newData - A 1D array containing data for the matrix - * @return {Matrix} - The new matrix - */ - static from1DArray(newRows, newColumns, newData) { - var length = newRows * newColumns; - if (length !== newData.length) { - throw new RangeError('Data length does not match given dimensions'); - } - var newMatrix = new this(newRows, newColumns); - for (var row = 0; row < newRows; row++) { - for (var column = 0; column < newColumns; column++) { - newMatrix.set(row, column, newData[row * newColumns + column]); - } - } - return newMatrix; - } + return { + xLabels: xLabels, + interValues: interValues, + intraValues: intraValues, + interCumPercent: interCumPercent, + intraCumPercent: intraCumPercent + }; + } +} - /** - * Creates a row vector, a matrix with only one row. - * @param {Array} newData - A 1D array containing data for the vector - * @return {Matrix} - The new matrix - */ - static rowVector(newData) { - var vector = new this(1, newData.length); - for (var i = 0; i < newData.length; i++) { - vector.set(0, i, newData[i]); - } - return vector; - } +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' +}; - /** - * Creates a column vector, a matrix with only one column. - * @param {Array} newData - A 1D array containing data for the vector - * @return {Matrix} - The new matrix - */ - static columnVector(newData) { - var vector = new this(newData.length, 1); - for (var i = 0; i < newData.length; i++) { - vector.set(i, 0, newData[i]); - } - return vector; - } +module.exports = Performance; - /** - * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns). - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @return {Matrix} - The new matrix - */ - static empty(rows, columns) { - return new this(rows, columns); - } - /** - * Creates a matrix with the given dimensions. Values will be set to zero. - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @return {Matrix} - The new matrix - */ - static zeros(rows, columns) { - return this.empty(rows, columns).fill(0); - } +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Creates a matrix with the given dimensions. Values will be set to one. - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @return {Matrix} - The new matrix - */ - static ones(rows, columns) { - return this.empty(rows, columns).fill(1); - } +module.exports = exports = __webpack_require__(199); +exports.Utils = __webpack_require__(27); +exports.OPLS = __webpack_require__(198); - /** - * Creates a matrix with the given dimensions. Values will be randomly set. - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @param {function} [rng=Math.random] - Random number generator - * @return {Matrix} The new matrix - */ - static rand(rows, columns, rng) { - if (rng === undefined) rng = Math.random; - var matrix = this.empty(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - matrix.set(i, j, rng()); - } - } - return matrix; - } - /** - * Creates a matrix with the given dimensions. Values will be random integers. - * @param {number} rows - Number of rows - * @param {number} columns - Number of columns - * @param {number} [maxValue=1000] - Maximum value - * @param {function} [rng=Math.random] - Random number generator - * @return {Matrix} The new matrix - */ - static randInt(rows, columns, maxValue, rng) { - if (maxValue === undefined) maxValue = 1000; - if (rng === undefined) rng = Math.random; - var matrix = this.empty(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - var value = Math.floor(rng() * maxValue); - matrix.set(i, j, value); - } - } - return matrix; - } +/***/ }), +/* 89 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0. - * @param {number} rows - Number of rows - * @param {number} [columns=rows] - Number of columns - * @param {number} [value=1] - Value to fill the diagonal with - * @return {Matrix} - The new identity matrix - */ - static eye(rows, columns, value) { - if (columns === undefined) columns = rows; - if (value === undefined) value = 1; - var min = Math.min(rows, columns); - var matrix = this.zeros(rows, columns); - for (var i = 0; i < min; i++) { - matrix.set(i, i, value); - } - return matrix; - } +"use strict"; - /** - * Creates a diagonal matrix based on the given array. - * @param {Array} data - Array containing the data for the diagonal - * @param {number} [rows] - Number of rows (Default: data.length) - * @param {number} [columns] - Number of columns (Default: rows) - * @return {Matrix} - The new diagonal matrix - */ - static diag(data, rows, columns) { - var l = data.length; - if (rows === undefined) rows = l; - if (columns === undefined) columns = rows; - var min = Math.min(l, rows, columns); - var matrix = this.zeros(rows, columns); - for (var i = 0; i < min; i++) { - matrix.set(i, i, data[i]); - } - return matrix; - } - /** - * Returns a matrix whose elements are the minimum between matrix1 and matrix2 - * @param {Matrix} matrix1 - * @param {Matrix} matrix2 - * @return {Matrix} - */ - static min(matrix1, matrix2) { - matrix1 = this.checkMatrix(matrix1); - matrix2 = this.checkMatrix(matrix2); - var rows = matrix1.rows; - var columns = matrix1.columns; - var result = new this(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); - } - } - return result; - } +exports.SimpleLinearRegression = exports.SLR = __webpack_require__(34); +exports.PolynomialRegression = __webpack_require__(68); +exports.ExponentialRegression = __webpack_require__(202); +exports.PowerRegression = __webpack_require__(215); - /** - * Returns a matrix whose elements are the maximum between matrix1 and matrix2 - * @param {Matrix} matrix1 - * @param {Matrix} matrix2 - * @return {Matrix} - */ - static max(matrix1, matrix2) { - matrix1 = this.checkMatrix(matrix1); - matrix2 = this.checkMatrix(matrix2); - var rows = matrix1.rows; - var columns = matrix1.columns; - var result = new this(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); - } - } - return result; - } +exports.NonLinearRegression = exports.NLR = { + PotentialRegression: __webpack_require__(243) +}; +exports.KernelRidgeRegression = exports.KRR = __webpack_require__(241); +//exports.MultipleLinearRegression = exports.MLR = require('./regression/multiple-linear-regression'); +//exports.MultivariateLinearRegression = exports.MVLR = require('./regression/multivariate-linear-regression'); +exports.PolinomialFitting2D = __webpack_require__(242); - /** - * Check that the provided value is a Matrix and tries to instantiate one if not - * @param {*} value - The value to check - * @return {Matrix} - */ - static checkMatrix(value) { - return Matrix.isMatrix(value) ? value : new this(value); - } +// robust regressions +exports.TheilSenRegression = __webpack_require__(229); +exports.RobustPolynomialRegression = __webpack_require__(228); - /** - * Returns true if the argument is a Matrix, false otherwise - * @param {*} value - The value to check - * @return {boolean} - */ - static isMatrix(value) { - return (value != null) && (value.klass === 'Matrix'); - } - /** - * @prop {number} size - The number of elements in the matrix. - */ - get size() { - return this.rows * this.columns; - } +/***/ }), +/* 90 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Applies a callback for each element of the matrix. The function is called in the matrix (this) context. - * @param {function} callback - Function that will be called with two parameters : i (row) and j (column) - * @return {Matrix} this - */ - apply(callback) { - if (typeof callback !== 'function') { - throw new TypeError('callback must be a function'); - } - var ii = this.rows; - var jj = this.columns; - for (var i = 0; i < ii; i++) { - for (var j = 0; j < jj; j++) { - callback.call(this, i, j); - } - } - return this; - } +//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007 +var extend = __webpack_require__(21); +var stat = __webpack_require__(245); - /** - * Returns a new 1D array filled row by row with the matrix values - * @return {Array} - */ - to1DArray() { - var array = new Array(this.size); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - array[i * this.columns + j] = this.get(i, j); - } - } - return array; - } +var defaultOptions = { + windowSize: 9, + derivative: 0, + polynomial: 3, +}; - /** - * Returns a 2D array containing a copy of the data - * @return {Array} - */ - to2DArray() { - var copy = new Array(this.rows); - for (var i = 0; i < this.rows; i++) { - copy[i] = new Array(this.columns); - for (var j = 0; j < this.columns; j++) { - copy[i][j] = this.get(i, j); - } - } - return copy; - } - /** - * @return {boolean} true if the matrix has one row - */ - isRowVector() { - return this.rows === 1; - } +function SavitzkyGolay(data, h, options) { + options = extend({}, defaultOptions, options); - /** - * @return {boolean} true if the matrix has one column - */ - isColumnVector() { - return this.columns === 1; - } + 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)') - /** - * @return {boolean} true if the matrix has one row or one column - */ - isVector() { - return (this.rows === 1) || (this.columns === 1); - } - /** - * @return {boolean} true if the matrix has the same number of rows and columns - */ - isSquare() { - return this.rows === this.columns; - } + if (options.windowSize>data.length) + throw new RangeError('Window size is higher than the data length '+options.windowSize+">"+data.length); + if ((options.derivative < 0) || !(Number.isInteger(options.derivative))) + throw new RangeError('Derivative should be a positive integer'); + if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial))) + throw new RangeError('Polynomial should be a positive integer'); + if (options.polynomial >= 6) + console.warn('You should not use polynomial grade higher than 5 if you are' + + ' not sure that your data arises from such a model. Possible polynomial oscillation problems'); - /** - * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal - */ - isSymmetric() { - if (this.isSquare()) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j <= i; j++) { - if (this.get(i, j) !== this.get(j, i)) { - return false; - } - } - } - return true; - } - return false; - } + var windowSize = options.windowSize; - /** - * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1 - * @abstract - * @param {number} rowIndex - Index of the row - * @param {number} columnIndex - Index of the column - * @param {number} value - The new value for the element - * @return {Matrix} this - */ - set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars - throw new Error('set method is unimplemented'); + var half = Math.floor(windowSize/2); + var np = data.length; + var ans = new Array(np); + var weights = fullWeights(windowSize,options.polynomial,options.derivative); + var hs = 0; + var constantH = true; + if( Object.prototype.toString.call( h ) === '[object Array]' ) { + constantH = false; + } + else{ + hs = Math.pow(h, options.derivative); + } + //console.log("Constant h: "+constantH); + //For the borders + for(var i=0;i=0 && i < h.length-1){ + hs+= (h[i+1]-h[i]); + count++; } + } + return Math.pow(hs/count,derivative); +} - /** - * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of - * rows of the matrix, and colRep times the number of columns of the matrix - * @param {number} rowRep - Number of times the rows should be repeated - * @param {number} colRep - Number of times the columns should be re - * @return {Matrix} - * @example - * var matrix = new Matrix([[1,2]]); - * matrix.repeat(2); // [[1,2],[1,2]] - */ - repeat(rowRep, colRep) { - rowRep = rowRep || 1; - colRep = colRep || 1; - var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep); - for (var i = 0; i < rowRep; i++) { - for (var j = 0; j < colRep; j++) { - matrix.setSubMatrix(this, this.rows * i, this.columns * j); - } - } - return matrix; +function GramPoly(i,m,k,s){ + var Grampoly = 0; + if(k>0){ + Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) + + s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s); + } + else{ + if(k==0&&s==0){ + Grampoly=1; + } + else{ + Grampoly=0; } + } + //console.log(Grampoly); + return Grampoly; +} - /** - * Fills the matrix with a given value. All elements will be set to this value. - * @param {number} value - New value - * @return {Matrix} this - */ - fill(value) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, value); - } - } - return this; +function GenFact(a,b){ + var gf=1; + if(a>=b){ + for(var j=a-b+1;j<=a;j++){ + gf*=j; } + } + return gf; +} - /** - * Negates the matrix. All elements will be multiplied by (-1) - * @return {Matrix} this - */ - neg() { - return this.mulS(-1); - } +function Weight(i,t,m,n,s){ + var sum=0; + for(var k=0;k<=n;k++){ + //console.log(k); + sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s) + } + return sum; +} - /** - * Returns a new array from the given row index - * @param {number} index - Row index - * @return {Array} - */ - getRow(index) { - util.checkRowIndex(this, index); - var row = new Array(this.columns); - for (var i = 0; i < this.columns; i++) { - row[i] = this.get(index, i); - } - return row; +/** + * + * @param m Number of points + * @param n Polynomial grade + * @param s Derivative + */ +function fullWeights(m,n,s){ + var weights = new Array(m); + var np = Math.floor(m/2); + for(var t=-np;t<=np;t++){ + weights[t+np] = new Array(m); + for(var j=-np;j<=np;j++){ + weights[t+np][j+np]=Weight(j,t,np,n,s); } + } + return weights; +} - /** - * Returns a new row vector from the given row index - * @param {number} index - Row index - * @return {Matrix} - */ - getRowVector(index) { - return this.constructor.rowVector(this.getRow(index)); - } +/*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} data + * @param {number} h + * @param {Object} options + * @returns {Array} + */ +function SavitzkyGolay (data, h, options) { + options = extend({}, defaultOptions, options); + if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize))) + throw new RangeError('Invalid window size (should be odd and at least 5 integer number)'); + if ((options.derivative < 0) || !(Number.isInteger(options.derivative))) + throw new RangeError('Derivative should be a positive integer'); + if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial))) + throw new RangeError('Polynomial should be a positive integer'); + + var C, norm; + var step = Math.floor(options.windowSize / 2); + + if (options.pad === 'pre') { + data = padArray(data, {size: step, value: options.padValue}); + } + + var ans = new Array(data.length - 2*step); + + if ((options.windowSize === 5) && (options.polynomial === 2) && ((options.derivative === 1) || (options.derivative === 2))) { + if (options.derivative === 1) { + C = [-2,-1,0,1,2]; + norm = 10; } - - /** - * Adds the values of a vector to each column - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - addColumnVector(vector) { - vector = util.checkColumnVector(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) + vector[i]); - } - } - return this; + else { + C = [2, -1, -2, -1, 2]; + norm = 7; } - - /** - * Subtracts the values of a vector from each column - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - subColumnVector(vector) { - vector = util.checkColumnVector(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) - vector[i]); - } + } + else { + var J = Matrix.ones(options.windowSize, options.polynomial + 1); + var inic = -(options.windowSize - 1) / 2; + for (var i = 0; i < J.length; i++) { + for (var j = 0; j < J[i].length; j++) { + if ((inic + 1 !== 0) || (j !== 0)) + J[i][j] = Math.pow((inic + i), j); } - return this; } + var Jtranspose = J.transposeView(); + var Jinv = (Jtranspose.mmul(J)).inverse(); + C = Jinv.mmul(Jtranspose); + C = C[options.derivative]; + norm = 1; + } + var det = norm * Math.pow(h, options.derivative); + for (var k = step; k < (data.length - step); k++) { + var d = 0; + for (var l = 0; l < C.length; l++) + d += C[l] * data[l + k - step] / det; + ans[k - step] = d; + } - /** - * Multiplies the values of a vector with each column - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - mulColumnVector(vector) { - vector = util.checkColumnVector(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) * vector[i]); - } - } - return this; - } + if (options.pad === 'post') { + ans = padArray(ans, {size: step, value: options.padValue}); + } - /** - * Divides the values of each column by those of a vector - * @param {Array|Matrix} vector - Array or vector - * @return {Matrix} this - */ - divColumnVector(vector) { - vector = util.checkColumnVector(this, vector); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) / vector[i]); - } - } - return this; - } + return ans; +} - /** - * Multiplies the values of a row with a scalar - * @param {number} index - Row index - * @param {number} value - * @return {Matrix} this - */ - mulRow(index, value) { - util.checkRowIndex(this, index); - for (var i = 0; i < this.columns; i++) { - this.set(index, i, this.get(index, i) * value); - } - return this; - } +module.exports = SavitzkyGolay; - /** - * Multiplies the values of a column with a scalar - * @param {number} index - Column index - * @param {number} value - * @return {Matrix} this - */ - mulColumn(index, value) { - util.checkColumnIndex(this, index); - for (var i = 0; i < this.rows; i++) { - this.set(i, index, this.get(i, index) * value); - } - return this; - } - /** - * Returns the maximum value of the matrix - * @return {number} - */ - max() { - var v = this.get(0, 0); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - if (this.get(i, j) > v) { - v = this.get(i, j); - } - } - } - return v; - } +/***/ }), +/* 92 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Returns the index of the maximum value - * @return {Array} - */ - maxIndex() { - var v = this.get(0, 0); - var idx = [0, 0]; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - if (this.get(i, j) > v) { - v = this.get(i, j); - idx[0] = i; - idx[1] = j; - } - } - } - return idx; - } +"use strict"; - /** - * Returns the minimum value of the matrix - * @return {number} - */ - min() { - var v = this.get(0, 0); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - if (this.get(i, j) < v) { - v = this.get(i, j); - } - } - } - return v; - } - /** - * Returns the index of the minimum value - * @return {Array} - */ - minIndex() { - var v = this.get(0, 0); - var idx = [0, 0]; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - if (this.get(i, j) < v) { - v = this.get(i, j); - idx[0] = i; - idx[1] = j; - } - } - } - return idx; - } +var NodeSquare = __webpack_require__(75), + NodeHexagonal = __webpack_require__(247); - /** - * Returns the maximum value of one row - * @param {number} row - Row index - * @return {number} - */ - maxRow(row) { - util.checkRowIndex(this, row); - var v = this.get(row, 0); - for (var i = 1; i < this.columns; i++) { - if (this.get(row, i) > v) { - v = this.get(row, i); - } - } - return v; - } +var defaultOptions = { + fields: 3, + randomizer: Math.random, + distance: squareEuclidean, + iterations: 10, + learningRate: 0.1, + gridType: 'rect', + torus: true, + method: 'random' +}; - /** - * Returns the index of the maximum value of one row - * @param {number} row - Row index - * @return {Array} - */ - maxRowIndex(row) { - util.checkRowIndex(this, row); - var v = this.get(row, 0); - var idx = [row, 0]; - for (var i = 1; i < this.columns; i++) { - if (this.get(row, i) > v) { - v = this.get(row, i); - idx[1] = i; - } - } - return idx; +function SOM(x, y, options, reload) { + + this.x = x; + this.y = y; + + options = options || {}; + this.options = {}; + for (var i in defaultOptions) { + if (options.hasOwnProperty(i)) { + this.options[i] = options[i]; + } else { + this.options[i] = defaultOptions[i]; } + } + + 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'); + } + + if (this.options.gridType === 'rect') { + this.nodeType = NodeSquare; + this.gridDim = { + x: x, + y: y + }; + } else { + this.nodeType = NodeHexagonal; + var hx = this.x - Math.floor(this.y / 2); + this.gridDim = { + x: hx, + y: this.y, + z: -(0 - hx - this.y) + }; + } - /** - * Returns the minimum value of one row - * @param {number} row - Row index - * @return {number} - */ - minRow(row) { - util.checkRowIndex(this, row); - var v = this.get(row, 0); - for (var i = 1; i < this.columns; i++) { - if (this.get(row, i) < v) { - v = this.get(row, i); - } - } - return v; - } + this.torus = this.options.torus; + this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance'; - /** - * Returns the index of the maximum value of one row - * @param {number} row - Row index - * @return {Array} - */ - minRowIndex(row) { - util.checkRowIndex(this, row); - var v = this.get(row, 0); - var idx = [row, 0]; - for (var i = 1; i < this.columns; i++) { - if (this.get(row, i) < v) { - v = this.get(row, i); - idx[1] = i; - } - } - return idx; - } + this.distance = this.options.distance; - /** - * Returns the maximum value of one column - * @param {number} column - Column index - * @return {number} - */ - maxColumn(column) { - util.checkColumnIndex(this, column); - var v = this.get(0, column); - for (var i = 1; i < this.rows; i++) { - if (this.get(i, column) > v) { - v = this.get(i, column); - } - } - return v; - } + this.maxDistance = getMaxDistance(this.distance, this.numWeights); - /** - * Returns the index of the maximum value of one column - * @param {number} column - Column index - * @return {Array} - */ - maxColumnIndex(column) { - util.checkColumnIndex(this, column); - var v = this.get(0, column); - var idx = [0, column]; - for (var i = 1; i < this.rows; i++) { - if (this.get(i, column) > v) { - v = this.get(i, column); - idx[0] = i; - } - } - return idx; - } + if (reload === true) { // For model loading + this.done = true; + return; + } + if (!(x > 0 && y > 0)) { + throw new Error('x and y must be positive'); + } - /** - * Returns the minimum value of one column - * @param {number} column - Column index - * @return {number} - */ - minColumn(column) { - util.checkColumnIndex(this, column); - var v = this.get(0, column); - for (var i = 1; i < this.rows; i++) { - if (this.get(i, column) < v) { - v = this.get(i, column); - } - } - return v; - } + this.times = { + findBMU: 0, + adjust: 0 + }; - /** - * Returns the index of the minimum value of one column - * @param {number} column - Column index - * @return {Array} - */ - minColumnIndex(column) { - util.checkColumnIndex(this, column); - var v = this.get(0, column); - var idx = [0, column]; - for (var i = 1; i < this.rows; i++) { - if (this.get(i, column) < v) { - v = this.get(i, column); - idx[0] = i; - } - } - return idx; - } + this.randomizer = this.options.randomizer; - /** - * Returns an array containing the diagonal values of the matrix - * @return {Array} - */ - diag() { - var min = Math.min(this.rows, this.columns); - var diag = new Array(min); - for (var i = 0; i < min; i++) { - diag[i] = this.get(i, i); - } - return diag; - } + this.iterationCount = 0; + this.iterations = this.options.iterations; - /** - * Returns the sum by the argument given, if no argument given, - * it returns the sum of all elements of the matrix. - * @param {string} by - sum by 'row' or 'column'. - * @return {Matrix|number} - */ - sum(by) { - switch (by) { - case 'row': - return util.sumByRow(this); - case 'column': - return util.sumByColumn(this); - default: - return util.sumAll(this); - } - } + this.startLearningRate = this.learningRate = this.options.learningRate; - /** - * Returns the mean of all elements of the matrix - * @return {number} - */ - mean() { - return this.sum() / this.size; - } + this.mapRadius = Math.floor(Math.max(x, y) / 2); - /** - * Returns the product of all elements of the matrix - * @return {number} - */ - prod() { - var prod = 1; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - prod *= this.get(i, j); - } + this.algorithmMethod = this.options.method; + + this._initNodes(); + + this.done = false; +} + +SOM.load = function loadModel(model, distance) { + if (model.name === 'SOM') { + var x = model.data.length, + y = model.data[0].length; + if (distance) { + model.options.distance = distance; + } else if (model.options.distance) { + model.options.distance = eval('(' + model.options.distance + ')'); + } + var som = new SOM(x, y, model.options, true); + som.nodes = new Array(x); + for (var i = 0; i < x; i++) { + som.nodes[i] = new Array(y); + for (var j = 0; j < y; j++) { + som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som); } - return prod; } + return som; + } else { + throw new Error('expecting a SOM model'); + } +}; - /** - * Computes the cumulative sum of the matrix elements (in place, row by row) - * @return {Matrix} this - */ - cumulativeSum() { - var sum = 0; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - sum += this.get(i, j); - this.set(i, j, sum); - } - } - return this; +SOM.prototype.export = function exportModel(includeDistance) { + if (!this.done) { + throw new Error('model is not ready yet'); + } + var model = { + name: 'SOM' + }; + model.options = { + fields: this.options.fields, + gridType: this.options.gridType, + torus: this.options.torus + }; + model.data = new Array(this.x); + for (var i = 0; i < this.x; i++) { + model.data[i] = new Array(this.y); + for (var j = 0; j < this.y; j++) { + model.data[i][j] = this.nodes[i][j].weights; } + } + if (includeDistance) { + model.options.distance = this.distance.toString(); + } + return model; +}; - /** - * Computes the dot (scalar) product between the matrix and another - * @param {Matrix} vector2 vector - * @return {number} - */ - dot(vector2) { - if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); - var vector1 = this.to1DArray(); - if (vector1.length !== vector2.length) { - throw new RangeError('vectors do not have the same size'); - } - var dot = 0; - for (var i = 0; i < vector1.length; i++) { - dot += vector1[i] * vector2[i]; +SOM.prototype._initNodes = function initNodes() { + var now = Date.now(), + i, j, k; + this.nodes = new Array(this.x); + for (i = 0; i < this.x; i++) { + this.nodes[i] = new Array(this.y); + for (j = 0; j < this.y; j++) { + var weights = new Array(this.numWeights); + for (k = 0; k < this.numWeights; k++) { + weights[k] = this.randomizer(); } - return dot; + this.nodes[i][j] = new this.nodeType(i, j, weights, this); } + } + this.times.initNodes = Date.now() - now; +}; - /** - * Returns the matrix product between this and other - * @param {Matrix} other - * @return {Matrix} - */ - mmul(other) { - other = this.constructor.checkMatrix(other); - if (this.columns !== other.rows) { - // eslint-disable-next-line no-console - console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); - } +SOM.prototype.setTraining = function setTraining(trainingSet) { + if (this.trainingSet) { + throw new Error('training set has already been set'); + } + var now = Date.now(); + var convertedSet = trainingSet; + var i, l = trainingSet.length; + if (this.extractor) { + convertedSet = new Array(l); + for (i = 0; i < l; i++) { + convertedSet[i] = this.extractor(trainingSet[i]); + } + } + this.numIterations = this.iterations * l; - var m = this.rows; - var n = this.columns; - var p = other.columns; + if (this.algorithmMethod === 'random') { + this.timeConstant = this.numIterations / Math.log(this.mapRadius); + } else { + this.timeConstant = l / Math.log(this.mapRadius); + } + this.trainingSet = convertedSet; + this.times.setTraining = Date.now() - now; +}; - var result = new this.constructor[Symbol.species](m, p); +SOM.prototype.trainOne = function trainOne() { + if (this.done) { - var Bcolj = new Array(n); - for (var j = 0; j < p; j++) { - for (var k = 0; k < n; k++) { - Bcolj[k] = other.get(k, j); - } + return false; - for (var i = 0; i < m; i++) { - var s = 0; - for (k = 0; k < n; k++) { - s += this.get(i, k) * Bcolj[k]; - } + } else if (this.numIterations-- > 0) { - result.set(i, j, s); - } + var neighbourhoodRadius, + trainingValue, + trainingSetFactor; + + if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step + neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant); + trainingValue = getRandomValue(this.trainingSet, this.randomizer); + this._adjust(trainingValue, neighbourhoodRadius); + this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations); + } else { // Get next input vector + trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length); + neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant); + trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length]; + this._adjust(trainingValue, neighbourhoodRadius); + if (((this.iterationCount + 1) % this.trainingSet.length) === 0) { + this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length)); } - return result; } - strassen2x2(other) { - var result = new this.constructor[Symbol.species](2, 2); - const a11 = this.get(0, 0); - const b11 = other.get(0, 0); - const a12 = this.get(0, 1); - const b12 = other.get(0, 1); - const a21 = this.get(1, 0); - const b21 = other.get(1, 0); - const a22 = this.get(1, 1); - const b22 = other.get(1, 1); + this.iterationCount++; - // Compute intermediate values. - const m1 = (a11 + a22) * (b11 + b22); - const m2 = (a21 + a22) * b11; - const m3 = a11 * (b12 - b22); - const m4 = a22 * (b21 - b11); - const m5 = (a11 + a12) * b22; - const m6 = (a21 - a11) * (b11 + b12); - const m7 = (a12 - a22) * (b21 + b22); + return true; - // Combine intermediate values into the output. - const c00 = m1 + m4 - m5 + m7; - const c01 = m3 + m5; - const c10 = m2 + m4; - const c11 = m1 - m2 + m3 + m6; + } else { - result.set(0, 0, c00); - result.set(0, 1, c01); - result.set(1, 0, c10); - result.set(1, 1, c11); - return result; - } + this.done = true; + return false; - strassen3x3(other) { - var result = new this.constructor[Symbol.species](3, 3); + } +}; - const a00 = this.get(0, 0); - const a01 = this.get(0, 1); - const a02 = this.get(0, 2); - const a10 = this.get(1, 0); - const a11 = this.get(1, 1); - const a12 = this.get(1, 2); - const a20 = this.get(2, 0); - const a21 = this.get(2, 1); - const a22 = this.get(2, 2); +SOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) { + var now = Date.now(), + x, y, dist, influence; - 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); + var bmu = this._findBestMatchingUnit(trainingValue); - 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; + var now2 = Date.now(); + this.times.findBMU += now2 - now; - 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; + var radiusLimit = Math.floor(neighbourhoodRadius); + var xMin = bmu.x - radiusLimit, + xMax = bmu.x + radiusLimit, + yMin = bmu.y - radiusLimit, + yMax = bmu.y + radiusLimit; - 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; + for (x = xMin; x <= xMax; x++) { + var theX = x; + if (x < 0) { + theX += this.x; + } else if (x >= this.x) { + theX -= this.x; } - - /** - * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000. - * @param {Matrix} y - * @return {Matrix} - */ - mmulStrassen(y) { - var x = this.clone(); - var r1 = x.rows; - var c1 = x.columns; - var r2 = y.rows; - var c2 = y.columns; - if (c1 !== r2) { - // eslint-disable-next-line no-console - console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`); + for (y = yMin; y <= yMax; y++) { + var theY = y; + if (y < 0) { + theY += this.y; + } else if (y >= this.y) { + theY -= this.y; } - // Put a matrix into the top left of a matrix of zeros. - // `rows` and `cols` are the dimensions of the output matrix. - function embed(mat, rows, cols) { - var r = mat.rows; - var c = mat.columns; - if ((r === rows) && (c === cols)) { - return mat; - } else { - var resultat = Matrix.zeros(rows, cols); - resultat = resultat.setSubMatrix(mat, 0, 0); - return resultat; - } + 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); } + } + } - // Make sure both matrices are the same size. - // This is exclusively for simplicity: - // this algorithm can be implemented with matrices of different sizes. + this.times.adjust += (Date.now() - now2); - var r = Math.max(r1, r2); - var c = Math.max(c1, c2); - x = embed(x, r, c); - y = embed(y, r, c); +}; + +SOM.prototype.train = function train(trainingSet) { + if (!this.done) { + this.setTraining(trainingSet); + while (this.trainOne()) { + } + } +}; + +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 result; +}; - // Our recursive multiplication function. - function blockMult(a, b, rows, cols) { - // For small matrices, resort to naive multiplication. - if (rows <= 512 || cols <= 512) { - return a.mmul(b); // a is equivalent to this - } +SOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) { - // Apply dynamic padding. - if ((rows % 2 === 1) && (cols % 2 === 1)) { - a = embed(a, rows + 1, cols + 1); - b = embed(b, rows + 1, cols + 1); - } else if (rows % 2 === 1) { - a = embed(a, rows + 1, cols); - b = embed(b, rows + 1, cols); - } else if (cols % 2 === 1) { - a = embed(a, rows, cols + 1); - b = embed(b, rows, cols + 1); - } + var bmu, + lowest = Infinity, + dist; - var halfRows = parseInt(a.rows / 2); - var halfCols = parseInt(a.columns / 2); - // Subdivide input matrices. - var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); - var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 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]; + } + } + } - var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); - var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); + return bmu; - var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); - var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); +}; - var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); - var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); +SOM.prototype.predict = function predict(data, computePosition) { + if (typeof data === 'boolean') { + computePosition = data; + data = null; + } + if (!data) { + data = this.trainingSet; + } + if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset + var self = this; + return data.map(function (element) { + return self._predict(element, computePosition); + }); + } else { // predict a single element + return this._predict(data, computePosition); + } +}; - // Compute intermediate values. - var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols); - var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols); - var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols); - var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols); - var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols); - var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols); - var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); +SOM.prototype._predict = function _predict(element, computePosition) { + if (!Array.isArray(element)) { + element = this.extractor(element); + } + var bmu = this._findBestMatchingUnit(element); + var result = [bmu.x, bmu.y]; + if (computePosition) { + result[2] = bmu.getPosition(element); + } + return result; +}; - // Combine intermediate values into the output. - var c11 = Matrix.add(m1, m4); - c11.sub(m5); - c11.add(m7); - var c12 = Matrix.add(m3, m5); - var c21 = Matrix.add(m2, m4); - var c22 = Matrix.sub(m1, m2); - c22.add(m3); - c22.add(m6); +// As seen in http://www.scholarpedia.org/article/Kohonen_network +SOM.prototype.getQuantizationError = function getQuantizationError() { + var fit = this.getFit(), + l = fit.length, + sum = 0; + for (var i = 0; i < l; i++) { + sum += fit[i]; + } + return sum / l; +}; - //Crop output to the desired size (undo dynamic padding). - var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns); - resultat = resultat.setSubMatrix(c11, 0, 0); - resultat = resultat.setSubMatrix(c12, c11.rows, 0); - resultat = resultat.setSubMatrix(c21, 0, c11.columns); - resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns); - return resultat.subMatrix(0, rows - 1, 0, cols - 1); - } - return blockMult(x, y, r, c); - } +SOM.prototype.getFit = function getFit(dataset) { + if (!dataset) { + dataset = this.trainingSet; + } + var l = dataset.length, + bmu, + result = new Array(l); + for (var i = 0; i < l; i++) { + bmu = this._findBestMatchingUnit(dataset[i]); + result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights)); + } + return result; +}; - /** - * Returns a row-by-row scaled matrix - * @param {number} [min=0] - Minimum scaled value - * @param {number} [max=1] - Maximum scaled value - * @return {Matrix} - The scaled matrix - */ - scaleRows(min, max) { - min = min === undefined ? 0 : min; - max = max === undefined ? 1 : max; - if (min >= max) { - throw new RangeError('min should be strictly smaller than max'); +function getConverters(fields) { + var l = fields.length, + normalizers = new Array(l), + denormalizers = new Array(l); + for (var i = 0; i < l; i++) { + normalizers[i] = getNormalizer(fields[i].range); + denormalizers[i] = getDenormalizer(fields[i].range); + } + return { + extractor: function extractor(value) { + var result = new Array(l); + for (var i = 0; i < l; i++) { + result[i] = normalizers[i](value[fields[i].name]); } - var newMatrix = this.constructor.empty(this.rows, this.columns); - for (var i = 0; i < this.rows; i++) { - var scaled = arrayUtils.scale(this.getRow(i), {min, max}); - newMatrix.setRow(i, scaled); + return result; + }, + creator: function creator(value) { + var result = {}; + for (var i = 0; i < l; i++) { + result[fields[i].name] = denormalizers[i](value[i]); } - return newMatrix; + return result; } + }; +} - /** - * Returns a new column-by-column scaled matrix - * @param {number} [min=0] - Minimum scaled value - * @param {number} [max=1] - Maximum scaled value - * @return {Matrix} - The new scaled matrix - * @example - * var matrix = new Matrix([[1,2],[-1,0]]); - * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]] - */ - scaleColumns(min, max) { - min = min === undefined ? 0 : min; - max = max === undefined ? 1 : max; - if (min >= max) { - throw new RangeError('min should be strictly smaller than max'); - } - var newMatrix = this.constructor.empty(this.rows, this.columns); - for (var i = 0; i < this.columns; i++) { - var scaled = arrayUtils.scale(this.getColumn(i), { - min: min, - max: max - }); - newMatrix.setColumn(i, scaled); - } - return newMatrix; - } +function getNormalizer(minMax) { + return function normalizer(value) { + return (value - minMax[0]) / (minMax[1] - minMax[0]); + }; +} + +function getDenormalizer(minMax) { + return function denormalizer(value) { + return (minMax[0] + value * (minMax[1] - minMax[0])); + }; +} +function squareEuclidean(a, b) { + var d = 0; + for (var i = 0, ii = a.length; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]); + } + return d; +} - /** - * Returns the Kronecker product (also known as tensor product) between this and other - * See https://en.wikipedia.org/wiki/Kronecker_product - * @param {Matrix} other - * @return {Matrix} - */ - kroneckerProduct(other) { - other = this.constructor.checkMatrix(other); +function getRandomValue(arr, randomizer) { + return arr[Math.floor(randomizer() * arr.length)]; +} - var m = this.rows; - var n = this.columns; - var p = other.rows; - var q = other.columns; +function getMaxDistance(distance, numWeights) { + var zero = new Array(numWeights), + one = new Array(numWeights); + for (var i = 0; i < numWeights; i++) { + zero[i] = 0; + one[i] = 1; + } + return distance(zero, one); +} - var result = new this.constructor[Symbol.species](m * p, n * q); - for (var i = 0; i < m; i++) { - for (var j = 0; j < n; j++) { - for (var k = 0; k < p; k++) { - for (var l = 0; l < q; l++) { - result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l); - } +module.exports = SOM; + +/***/ }), +/* 93 */ +/***/ (function(module, exports, __webpack_require__) { + +const HashTable = __webpack_require__(42); + +class SparseMatrix { + constructor(rows, columns, options = {}) { + if (rows instanceof SparseMatrix) { // clone + const other = rows; + this._init(other.rows, other.columns, other.elements.clone(), other.threshold); + return; + } + + if (Array.isArray(rows)) { + const matrix = rows; + rows = matrix.length; + options = columns || {}; + columns = matrix[0].length; + this._init(rows, columns, new HashTable(options), options.threshold); + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + var value = matrix[i][j]; + if (this.threshold && Math.abs(value) < this.threshold) value = 0; + if (value !== 0) { + this.elements.set(i * columns + j, matrix[i][j]); } } } - return result; + } else { + this._init(rows, columns, new HashTable(options), options.threshold); } + } - /** - * Transposes the matrix and returns a new one containing the result - * @return {Matrix} - */ - transpose() { - var result = new this.constructor[Symbol.species](this.columns, this.rows); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - result.set(j, i, this.get(i, j)); - } - } - return result; + _init(rows, columns, elements, threshold) { + this.rows = rows; + this.columns = columns; + this.elements = elements; + this.threshold = threshold || 0; + } + + static eye(rows = 1, columns = rows) { + const min = Math.min(rows, columns); + const matrix = new SparseMatrix(rows, columns, {initialCapacity: min}); + for (var i = 0; i < min; i++) { + matrix.set(i, i, 1); } + return matrix; + } - /** - * Sorts the rows (in place) - * @param {function} compareFunction - usual Array.prototype.sort comparison function - * @return {Matrix} this - */ - sortRows(compareFunction) { - if (compareFunction === undefined) compareFunction = compareNumbers; - for (var i = 0; i < this.rows; i++) { - this.setRow(i, this.getRow(i).sort(compareFunction)); + clone() { + return new SparseMatrix(this); + } + + to2DArray() { + const copy = new Array(this.rows); + for (var i = 0; i < this.rows; i++) { + copy[i] = new Array(this.columns); + for (var j = 0; j < this.columns; j++) { + copy[i][j] = this.get(i, j); } - return this; } + return copy; + } - /** - * Sorts the columns (in place) - * @param {function} compareFunction - usual Array.prototype.sort comparison function - * @return {Matrix} this - */ - sortColumns(compareFunction) { - if (compareFunction === undefined) compareFunction = compareNumbers; - for (var i = 0; i < this.columns; i++) { - this.setColumn(i, this.getColumn(i).sort(compareFunction)); + isSquare() { + return this.rows === this.columns; + } + + 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 this; + return v; + }); + return symmetric; + } + + get cardinality() { + return this.elements.size; + } + + get size() { + return this.rows * this.columns; + } + + get(row, column) { + return this.elements.get(row * this.columns + column); + } + + set(row, column, value) { + if (this.threshold && Math.abs(value) < this.threshold) value = 0; + if (value === 0) { + this.elements.remove(row * this.columns + column); + } else { + this.elements.set(row * this.columns + column, value); } + return this; + } + + mmul(other) { + if (this.columns !== other.rows) + 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 v2; + }); + return v1; + }); + return result; + } - /** - * Returns a subset of the matrix - * @param {number} startRow - First row index - * @param {number} endRow - Last row index - * @param {number} startColumn - First column index - * @param {number} endColumn - Last column index - * @return {Matrix} - */ - subMatrix(startRow, endRow, startColumn, endColumn) { - util.checkRange(this, startRow, endRow, startColumn, endColumn); - var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1); - for (var i = startRow; i <= endRow; i++) { - for (var j = startColumn; j <= endColumn; j++) { - newMatrix[i - startRow][j - startColumn] = this.get(i, j); + 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; + } + + forEachNonZero(callback) { + this.elements.forEachPair((key, value) => { + const i = (key / this.columns) | 0; + const j = key % this.columns; + let r = callback(i, j, value); + if (r === false) return false; // stop iteration + if (this.threshold && Math.abs(r) < this.threshold) r = 0; + if (r !== value) { + if (r === 0) { + this.elements.remove(key, true); + } else { + this.elements.set(key, r); } } - return newMatrix; + return true; + }); + this.elements.maybeShrinkCapacity(); + return this; + } + + 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}; + } + + setThreshold(newThreshold) { + if (newThreshold !== 0 && newThreshold !== this.threshold) { + this.threshold = newThreshold; + this.forEachNonZero((i, j, v) => v); } + return this; + } +} + +SparseMatrix.prototype.klass = 'Matrix'; + +SparseMatrix.identity = SparseMatrix.eye; +SparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct; + +module.exports = SparseMatrix; + +/* + 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%(); +}) +`; - /** - * Returns a subset of the matrix based on an array of row indices - * @param {Array} indices - Array containing the row indices - * @param {number} [startColumn = 0] - First column index - * @param {number} [endColumn = this.columns-1] - Last column index - * @return {Matrix} - */ - subMatrixRow(indices, startColumn, endColumn) { - if (startColumn === undefined) startColumn = 0; - if (endColumn === undefined) endColumn = this.columns - 1; - if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) { - throw new RangeError('Argument out of range'); - } +var operators = [ + // Arithmetic operators + ['+', 'add'], + ['-', 'sub', 'subtract'], + ['*', 'mul', 'multiply'], + ['/', 'div', 'divide'], + ['%', 'mod', 'modulus'], + // Bitwise operators + ['&', 'and'], + ['|', 'or'], + ['^', 'xor'], + ['<<', 'leftShift'], + ['>>', 'signPropagatingRightShift'], + ['>>>', 'rightShift', 'zeroFillRightShift'] +]; - var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1); - for (var i = 0; i < indices.length; i++) { - for (var j = startColumn; j <= endColumn; j++) { - if (indices[i] < 0 || indices[i] >= this.rows) { - throw new RangeError('Row index out of range: ' + indices[i]); - } - newMatrix.set(i, j - startColumn, this.get(indices[i], j)); - } - } - return newMatrix; - } +for (var operator of operators) { + for (var i = 1; i < operator.length; i++) { + SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]})); + SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]})); + SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]})); - /** - * Returns a subset of the matrix based on an array of column indices - * @param {Array} indices - Array containing the column indices - * @param {number} [startRow = 0] - First row index - * @param {number} [endRow = this.rows-1] - Last row index - * @return {Matrix} - */ - subMatrixColumn(indices, startRow, endRow) { - if (startRow === undefined) startRow = 0; - if (endRow === undefined) endRow = this.rows - 1; - if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) { - throw new RangeError('Argument out of range'); - } + SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]})); + } +} - var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length); - for (var i = 0; i < indices.length; i++) { - for (var j = startRow; j <= endRow; j++) { - if (indices[i] < 0 || indices[i] >= this.columns) { - throw new RangeError('Column index out of range: ' + indices[i]); - } - newMatrix.set(j - startRow, i, this.get(j, indices[i])); - } - } - return newMatrix; - } +var methods = [ + ['~', 'not'] +]; - /** - * Set a part of the matrix to the given sub-matrix - * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values. - * @param {number} startRow - The index of the first row to set - * @param {number} startColumn - The index of the first column to set - * @return {Matrix} - */ - setSubMatrix(matrix, startRow, startColumn) { - matrix = this.constructor.checkMatrix(matrix); - var endRow = startRow + matrix.rows - 1; - var endColumn = startColumn + matrix.columns - 1; - util.checkRange(this, startRow, endRow, startColumn, endColumn); - for (var i = 0; i < matrix.rows; i++) { - for (var j = 0; j < matrix.columns; j++) { - this[startRow + i][startColumn + j] = matrix.get(i, j); - } - } - return this; - } +[ + '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]); +}); - /** - * Return a new matrix based on a selection of rows and columns - * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once. - * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once. - * @return {Matrix} The new matrix - */ - selection(rowIndices, columnIndices) { - var indices = util.checkIndices(this, rowIndices, columnIndices); - var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length); - for (var i = 0; i < indices.row.length; i++) { - var rowIndex = indices.row[i]; - for (var j = 0; j < indices.column.length; j++) { - var columnIndex = indices.column[j]; - newMatrix[i][j] = this.get(rowIndex, columnIndex); - } - } - return newMatrix; - } +for (var method of methods) { + for (var i = 1; i < method.length; i++) { + SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, {name: method[i], method: method[0]})); + SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, {name: method[i]})); + } +} - /** - * Returns the trace of the matrix (sum of the diagonal elements) - * @return {number} - */ - trace() { - var min = Math.min(this.rows, this.columns); - var trace = 0; - for (var i = 0; i < min; i++) { - trace += this.get(i, i); - } - return trace; - } +function fillTemplateFunction(template, values) { + for (var i in values) { + template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]); + } + return template; +} - /* - Matrix views - */ - /** - * Returns a view of the transposition of the matrix - * @return {MatrixTransposeView} - */ - transposeView() { - return new MatrixTransposeView(this); - } +/***/ }), +/* 94 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Returns a view of the row vector with the given index - * @param {number} row - row index of the vector - * @return {MatrixRowView} - */ - rowView(row) { - util.checkRowIndex(this, row); - return new MatrixRowView(this, row); - } +"use strict"; - /** - * Returns a view of the column vector with the given index - * @param {number} column - column index of the vector - * @return {MatrixColumnView} - */ - columnView(column) { - util.checkColumnIndex(this, column); - return new MatrixColumnView(this, column); - } +const Kernel = __webpack_require__(20); +const stat = __webpack_require__(2).array; - /** - * Returns a view of the matrix flipped in the row axis - * @return {MatrixFlipRowView} - */ - flipRowView() { - return new MatrixFlipRowView(this); - } +var defaultOptions = { + C: 1, + tol: 1e-4, + maxPasses: 10, + maxIterations: 10000, + kernel: 'linear', + alphaTol: 1e-6, + random: Math.random, + whitening: true +}; - /** - * Returns a view of the matrix flipped in the column axis - * @return {MatrixFlipColumnView} - */ - flipColumnView() { - return new MatrixFlipColumnView(this); - } +/** + * Simplified version of the Sequential Minimal Optimization algorithm for training + * support vector machines + * @param {{Object}} options - SVM options + * @param {Number} [options.C=1] - regularization parameter + * @param {Number} [options.tol=1e-4] - numerical tolerance + * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors + * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing + * @param {Number} [options.maxIterations=10000] - max number of iterations + * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels} + * @param {Function} [options.random=Math.random] - custom random number generator + * @constructor + */ +function SVM(options) { + this.options = Object.assign({}, defaultOptions, options); - /** - * Returns a view of a submatrix giving the index boundaries - * @param {number} startRow - first row index of the submatrix - * @param {number} endRow - last row index of the submatrix - * @param {number} startColumn - first column index of the submatrix - * @param {number} endColumn - last column index of the submatrix - * @return {MatrixSubView} - */ - subMatrixView(startRow, endRow, startColumn, endColumn) { - return new MatrixSubView(this, startRow, endRow, startColumn, endColumn); - } + this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions); + this.b = 0; +} - /** - * Returns a view of the cross of the row indices and the column indices - * @example - * // resulting vector is [[2], [2]] - * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1]) - * @param {Array} rowIndices - * @param {Array} columnIndices - * @return {MatrixSelectionView} - */ - selectionView(rowIndices, columnIndices) { - return new MatrixSelectionView(this, rowIndices, columnIndices); +/** + * Train the SVM model + * @param {Array >} features - training data features + * @param {Array } labels - training data labels in the domain {1,-1} + */ +SVM.prototype.train = function (features, labels) { + if (features.length !== labels.length) { + throw new Error('Features and labels should have the same length'); + } + if (features.length < 2) { + throw new Error('Cannot train with less than 2 observations'); + } + this._trained = false; + this._loaded = false; + this.N = labels.length; + this.D = features[0].length; + if (this.options.whitening) { + this.X = new Array(this.N); + for (var i = 0; i < this.N; i++) { + this.X[i] = new Array(this.D); } + this.minMax = new Array(this.D); + // Apply normalization and keep normalization parameters + for (var j = 0; j < this.D; j++) { + var d = new Array(this.N); + for (i = 0; i < this.N; i++) { + d[i] = features[i][j]; + } + this.minMax[j] = stat.minMax(d); + for (i = 0; i < this.N; i++) { + this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); + } + } + } else { + this.X = features; + } + this.Y = labels; + this.b = 0; + this.W = undefined; + var kernel = this.kernel.compute(this.X); + var m = labels.length; + var alpha = new Array(m).fill(0); + this.alphas = alpha; + for (var a = 0; a < m; a++) + alpha[a] = 0; - /** - * Calculates and returns the determinant of a matrix as a Number - * @example - * new Matrix([[1,2,3], [4,5,6]]).det() - * @return {number} - */ - det() { - if (this.isSquare()) { - var a, b, c, d; - if (this.columns === 2) { - // 2 x 2 matrix - a = this.get(0, 0); - b = this.get(0, 1); - c = this.get(1, 0); - d = this.get(1, 1); - - return a * d - (b * c); - } else if (this.columns === 3) { - // 3 x 3 matrix - var subMatrix0, subMatrix1, subMatrix2; - subMatrix0 = this.selectionView([1, 2], [1, 2]); - subMatrix1 = this.selectionView([1, 2], [0, 2]); - subMatrix2 = this.selectionView([1, 2], [0, 1]); - a = this.get(0, 0); - b = this.get(0, 1); - c = this.get(0, 2); + var b1 = 0, + b2 = 0, + iter = 0, + passes = 0, + Ei = 0, + Ej = 0, + ai = 0, + aj = 0, + L = 0, + H = 0, + eta = 0; - return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det(); - } else { - // general purpose determinant using the LU decomposition - return new LuDecomposition(this).determinant; + while (passes < this.options.maxPasses && iter < this.options.maxIterations) { + var numChange = 0; + for (i = 0; i < m; i++) { + Ei = this._marginOnePrecomputed(i, kernel) - labels[i]; + if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) { + j = i; + while (j === i) j = Math.floor(this.options.random() * m); + Ej = this._marginOnePrecomputed(j, kernel) - labels[j]; + ai = alpha[i]; + aj = alpha[j]; + if (labels[i] === labels[j]) { + L = Math.max(0, ai + aj - this.options.C); + H = Math.min(this.options.C, ai + aj); + } else { + L = Math.max(0, aj - ai); + H = Math.min(this.options.C, this.options.C + aj + ai); } + if (Math.abs(L - H) < 1e-4) continue; - } else { - throw Error('Determinant can only be calculated for a square matrix.'); + eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j]; + if (eta >= 0) continue; + var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta; + if (newaj > H) + newaj = H; + else if (newaj < L) + newaj = L; + if (Math.abs(aj - newaj) < 10e-4) continue; + alpha[j] = newaj; + alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj); + b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j]; + b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j]; + this.b = (b1 + b2) / 2; + if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1; + if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2; + numChange += 1; } } + iter++; + if (numChange === 0) + passes += 1; + else + passes = 0; + } + if (iter === this.options.maxIterations) { + throw new Error('max iterations reached'); } - Matrix.prototype.klass = 'Matrix'; + this.iterations = iter; - /** - * @private - * Check that two matrices have the same dimensions - * @param {Matrix} matrix - * @param {Matrix} otherMatrix - */ - function checkDimensions(matrix, otherMatrix) { // eslint-disable-line no-unused-vars - if (matrix.rows !== otherMatrix.rows || - matrix.columns !== otherMatrix.columns) { - throw new RangeError('Matrices dimensions must be equal'); + // Compute the weights (useful for fast decision on new test instances when linear SVM) + if (this.options.kernel === 'linear') { + this.W = new Array(this.D); + for (var r = 0; r < this.D; r++) { + this.W[r] = 0; + for (var w = 0; w < m; w++) + this.W[r] += labels[w] * alpha[w] * this.X[w][r]; } } - function compareNumbers(a, b) { - return a - b; + // Keep only support vectors + // It will compute decision on new test instances faster + // We also keep the index of the support vectors + // in the original data + var nX = []; + var nY = []; + var nAlphas = []; + this._supportVectorIdx = []; + for (i = 0; i < this.N; i++) { + if (this.alphas[i] > this.options.alphaTol) { + nX.push(this.X[i]); + nY.push(labels[i]); + nAlphas.push(this.alphas[i]); + this._supportVectorIdx.push(i); + + } } + this.X = nX; + this.Y = nY; + this.N = nX.length; + this.alphas = nAlphas; - /* - Synonyms - */ - Matrix.random = Matrix.rand; - Matrix.diagonal = Matrix.diag; - Matrix.prototype.diagonal = Matrix.prototype.diag; - Matrix.identity = Matrix.eye; - Matrix.prototype.negate = Matrix.prototype.neg; - Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct; - Matrix.prototype.determinant = Matrix.prototype.det; + // A flag to say this SVM has been trained + this._trained = true; +}; - /* - Add dynamically instance and static methods for mathematical operations - */ +/** + * Get prediction ({-1,1}) given one observation's features. + * @private + * @param p The observation's features. + * @returns {number} Classification result ({-1,1}) + */ +SVM.prototype.predictOne = function (p) { + var margin = this.marginOne(p); + return margin > 0 ? 1 : -1; +}; - var inplaceOperator = ` -(function %name%(value) { - if (typeof value === 'number') return this.%name%S(value); - return this.%name%M(value); -}) -`; +/** + * Predict the classification outcome of a trained svm given one or several observations' features. + * @param {Array} features - The observation(s)' features + * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation + * is given + */ +SVM.prototype.predict = function (features) { + if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first'); + if (Array.isArray(features) && Array.isArray(features[0])) { + return features.map(this.predictOne.bind(this)); + } else { + return this.predictOne(features); + } +}; - var inplaceOperatorScalar = ` -(function %name%S(value) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) %op% value); +/** + * Get margin given one observation's features + * @private + * @param {Array} features - Features + * @returns {Number} - The computed margin + */ +SVM.prototype.marginOne = function (features, noWhitening) { + // Apply normalization + if (this.options.whitening && !noWhitening) { + features = this._applyWhitening(features); + } + var ans = this.b, i; + if (this.options.kernel === 'linear' && this.W) { + // Use weights, it's faster + for (i = 0; i < this.W.length; i++) { + ans += this.W[i] * features[i]; + } + } else { + for (i = 0; i < this.N; i++) { + ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0]; } } - return this; -}) -`; + return ans; +}; + + +/** + * Get a margin using the precomputed kernel. Much faster than normal margin computation + * @private + * @param {Number} index - Train data index + * @param {Array< Array >} kernel - The precomputed kernel + * @returns {number} Computed margin + * @private + */ +SVM.prototype._marginOnePrecomputed = function (index, kernel) { + var ans = this.b, i; + for (i = 0; i < this.N; i++) { + ans += this.alphas[i] * this.Y[i] * kernel[index][i]; + } + return ans; +}; + + +/** + * Returns the margin of one or several observations given its features + * @param {Array >|Array} features - Features from on or several observations. + * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if + * only one observation's features given + */ +SVM.prototype.margin = function (features) { + if (Array.isArray(features)) { + return features.map(this.marginOne.bind(this)); + } else { + return this.marginOne(features); + } +}; - var inplaceOperatorMatrix = ` -(function %name%M(matrix) { - matrix = this.constructor.checkMatrix(matrix); - checkDimensions(this, matrix); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); - } +/** + * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances + * created from {@link #SVM.load load} if linear kernel + * @returns {Array} The indices in the training vector of the support vectors + */ +SVM.prototype.supportVectors = function () { + if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first'); + if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them'); + return this._supportVectorIdx; +}; + +/** + * Create a SVM instance from a saved model + * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON} + * @returns {SVM} Instance of svm classifier + */ +SVM.load = function (model) { + this._loaded = true; + this._trained = false; + var svm = new SVM(model.options); + if (model.options.kernel === 'linear') { + svm.W = model.W.slice(); + svm.D = svm.W.length; + } else { + svm.X = model.X.slice(); + svm.Y = model.Y.slice(); + svm.alphas = model.alphas.slice(); + svm.N = svm.X.length; + svm.D = svm.X[0].length; } - return this; -}) -`; + svm.minMax = model.minMax; + svm.b = model.b; + svm._loaded = true; + svm._trained = false; + return svm; +}; - var staticOperator = ` -(function %name%(matrix, value) { - var newMatrix = new this[Symbol.species](matrix); - return newMatrix.%name%(value); -}) -`; +/** + * Export the minimal object that enables to reload the model + * @returns {Object} Model object that can be reused with {@link #SVM.load load} + */ +SVM.prototype.toJSON = function () { + if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first'); + var model = {}; + model.options = Object.assign({}, this.options); + model.b = this.b; + model.minMax = this.minMax; + if (model.options.kernel === 'linear') { + model.W = this.W.slice(); + } else { + // Exporting non-linear models is heavier + model.X = this.X.slice(); + model.Y = this.Y.slice(); + model.alphas = this.alphas.slice(); + } + return model; +}; - var inplaceMethod = ` -(function %name%() { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, %method%(this.get(i, j))); - } +SVM.prototype._applyWhitening = function (features) { + if (!this.minMax) throw new Error('Could not apply whitening'); + var whitened = new Array(features.length); + for (var j = 0; j < features.length; j++) { + whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); } - return this; -}) -`; + return whitened; +}; - var staticMethod = ` -(function %name%(matrix) { - var newMatrix = new this[Symbol.species](matrix); - return newMatrix.%name%(); -}) -`; +module.exports = SVM; - var inplaceMethodWithArgs = ` -(function %name%(%args%) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, %method%(this.get(i, j), %args%)); - } - } - return this; -}) -`; - var staticMethodWithArgs = ` -(function %name%(matrix, %args%) { - var newMatrix = new this[Symbol.species](matrix); - return newMatrix.%name%(%args%); -}) -`; +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; - var inplaceMethodWithOneArgScalar = ` -(function %name%S(value) { - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, %method%(this.get(i, j), value)); - } - } - return this; -}) -`; - var inplaceMethodWithOneArgMatrix = ` -(function %name%M(matrix) { - matrix = this.constructor.checkMatrix(matrix); - checkDimensions(this, matrix); - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); - } - } - return this; -}) -`; - var inplaceMethodWithOneArg = ` -(function %name%(value) { - if (typeof value === 'number') return this.%name%S(value); - return this.%name%M(value); -}) -`; +Object.defineProperty(exports, "__esModule", { + value: true +}); - var staticMethodWithOneArg = staticMethodWithArgs; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); - var operators = [ - // Arithmetic operators - ['+', 'add'], - ['-', 'sub', 'subtract'], - ['*', 'mul', 'multiply'], - ['/', 'div', 'divide'], - ['%', 'mod', 'modulus'], - // Bitwise operators - ['&', 'and'], - ['|', 'or'], - ['^', 'xor'], - ['<<', 'leftShift'], - ['>>', 'signPropagatingRightShift'], - ['>>>', 'rightShift', 'zeroFillRightShift'] - ]; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var i; +var LOOP = 8; +var FLOAT_MUL = 1 / 16777216; - for (var operator of operators) { - var inplaceOp = eval(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]})); - var inplaceOpS = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]})); - var inplaceOpM = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]})); - var staticOp = eval(fillTemplateFunction(staticOperator, {name: operator[1]})); - for (i = 1; i < operator.length; i++) { - Matrix.prototype[operator[i]] = inplaceOp; - Matrix.prototype[operator[i] + 'S'] = inplaceOpS; - Matrix.prototype[operator[i] + 'M'] = inplaceOpM; - Matrix[operator[i]] = staticOp; - } - } +function multiply_uint32(n, m) { + n >>>= 0; + m >>>= 0; + var nlo = n & 0xffff; + var nhi = n - nlo; + return (nhi * m >>> 0) + nlo * m >>> 0; +} - var methods = [ - ['~', 'not'] - ]; +var XSadd = (function () { + function XSadd() { + var seed = arguments.length <= 0 || arguments[0] === undefined ? Date.now() : arguments[0]; - [ - '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]); - }); + _classCallCheck(this, XSadd); - for (var method of methods) { - var inplaceMeth = eval(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]})); - var staticMeth = eval(fillTemplateFunction(staticMethod, {name: method[1]})); - for (i = 1; i < method.length; i++) { - Matrix.prototype[method[i]] = inplaceMeth; - Matrix[method[i]] = staticMeth; - } + this.state = new Uint32Array(4); + this.init(seed); } - var methodsWithArgs = [ - ['Math.pow', 1, 'pow'] - ]; - - for (var methodWithArg of methodsWithArgs) { - var args = 'arg0'; - for (i = 1; i < methodWithArg[1]; i++) { - args += `, arg${i}`; - } - if (methodWithArg[1] !== 1) { - var inplaceMethWithArgs = eval(fillTemplateFunction(inplaceMethodWithArgs, { - name: methodWithArg[2], - method: methodWithArg[0], - args: args - })); - var staticMethWithArgs = eval(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args})); - for (i = 2; i < methodWithArg.length; i++) { - Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs; - Matrix[methodWithArg[i]] = staticMethWithArgs; - } - } else { - var tmplVar = { - name: methodWithArg[2], - args: args, - method: methodWithArg[0] - }; - var inplaceMethod2 = eval(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar)); - var inplaceMethodS = eval(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar)); - var inplaceMethodM = eval(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar)); - var staticMethod2 = eval(fillTemplateFunction(staticMethodWithOneArg, tmplVar)); - for (i = 2; i < methodWithArg.length; i++) { - Matrix.prototype[methodWithArg[i]] = inplaceMethod2; - Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM; - Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS; - Matrix[methodWithArg[i]] = staticMethod2; + _createClass(XSadd, [{ + key: "init", + value: function init(seed) { + this.state[0] = seed; + this.state[1] = 0; + this.state[2] = 0; + this.state[3] = 0; + for (var i = 1; i < LOOP; i++) { + this.state[i & 3] ^= i + multiply_uint32(1812433253, this.state[i - 1 & 3] ^ this.state[i - 1 & 3] >>> 30 >>> 0) >>> 0; + } + period_certification(this); + for (var i = 0; i < LOOP; i++) { + next_state(this); } } - } - function fillTemplateFunction(template, values) { - for (var value in values) { - template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]); + /** + * Returns a 32-bit integer r (0 <= r < 2^32) + */ + }, { + key: "getUint32", + value: function getUint32() { + next_state(this); + return this.state[3] + this.state[2] >>> 0; } - return template; - } - - return Matrix; -} - - -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + /** + * Returns a floating point number r (0.0 <= r < 1.0) + */ + }, { + key: "getFloat", + value: function getFloat() { + return (this.getUint32() >>> 8) * FLOAT_MUL; + } + }, { + key: "random", + get: function get() { + if (!this._random) { + this._random = this.getFloat.bind(this); + } + return this._random; + } + }]); + return XSadd; +})(); -var Matrix = __webpack_require__(3); +exports["default"] = XSadd; -// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs -function LuDecomposition(matrix) { - if (!(this instanceof LuDecomposition)) { - return new LuDecomposition(matrix); +function period_certification(xsadd) { + if (xsadd.state[0] === 0 && xsadd.state[1] === 0 && xsadd.state[2] === 0 && xsadd.state[3] === 0) { + xsadd.state[0] = 88; // X + xsadd.state[1] = 83; // S + xsadd.state[2] = 65; // A + xsadd.state[3] = 68; // D } +} - matrix = Matrix.Matrix.checkMatrix(matrix); - - var lu = matrix.clone(), - rows = lu.rows, - columns = lu.columns, - pivotVector = new Array(rows), - pivotSign = 1, - i, j, k, p, s, t, v, - LUrowi, LUcolj, kmax; - - for (i = 0; i < rows; i++) { - pivotVector[i] = i; - } +var sh1 = 15; +var sh2 = 18; +var sh3 = 11; +function next_state(xsadd) { + var t = xsadd.state[0]; + t ^= t << sh1; + t ^= t >>> sh2; + t ^= xsadd.state[3] << sh3; + xsadd.state[0] = xsadd.state[1]; + xsadd.state[1] = xsadd.state[2]; + xsadd.state[2] = xsadd.state[3]; + xsadd.state[3] = t; +} +module.exports = exports["default"]; - LUcolj = new Array(rows); - for (j = 0; j < columns; j++) { +/***/ }), +/* 96 */ +/***/ (function(module, exports) { - for (i = 0; i < rows; i++) { - LUcolj[i] = lu[i][j]; - } +(function(undefined) { + 'use strict'; + + // Node.js usage: + // + // var Picker = require('RandomSelection').Picker; + // var greetingPicker = new Picker(['hello', 'hi', 'howdy']); + // var greeting = greetingPicker.pick(); + + // Our namespace. Exported members will be attached to this. + var ns; + + // Set our namespace based on whether we are running in Node.js or the browser. + if (typeof module !== 'undefined' && module.exports) { + // We are running in Node. + ns = module.exports; + } + else { + // We are running in the browser. + // `this` is the `window`. + // Use window.RandomSelection as our namespace. + ns = this.RandomSelection = {}; + } + + // Gets a shallow copy of the given array. + function clone(arr) { + var newArr = []; + for (var i=0; i Math.abs(LUcolj[p])) { - p = i; - } - } +/***/ }), +/* 97 */ +/***/ (function(module, exports, __webpack_require__) { - if (p !== j) { - for (k = 0; k < columns; k++) { - t = lu[p][k]; - lu[p][k] = lu[j][k]; - lu[j][k] = t; - } +"use strict"; - v = pivotVector[p]; - pivotVector[p] = pivotVector[j]; - pivotVector[j] = v; - pivotSign = -pivotSign; - } +// Root packages - if (j < rows && lu[j][j] !== 0) { - for (i = j + 1; i < rows; i++) { - lu[i][j] /= lu[j][j]; - } - } - } +exports.ArrayUtils = exports.AU = __webpack_require__(13); +exports.BitArray = __webpack_require__(77); +exports.HashTable = __webpack_require__(42); +exports.Matrix = __webpack_require__(0); +exports.PadArray = __webpack_require__(43); +exports.Regression = __webpack_require__(89); +exports.binarySearch = __webpack_require__(39); +exports.numSort = __webpack_require__(44); - this.LU = lu; - this.pivotVector = pivotVector; - this.pivotSign = pivotSign; -} +// Math packages +var Math = exports.Math = {}; -LuDecomposition.prototype = { - isSingular: function () { - var data = this.LU, - col = data.columns; - for (var j = 0; j < col; j++) { - if (data[j][j] === 0) { - return true; - } - } - return false; - }, - get determinant() { - var data = this.LU; - if (!data.isSquare()) { - throw new Error('Matrix must be square'); - } - var determinant = this.pivotSign, col = data.columns; - for (var j = 0; j < col; j++) { - determinant *= data[j][j]; - } - return determinant; - }, - get lowerTriangularMatrix() { - var data = this.LU, - rows = data.rows, - columns = data.columns, - X = new Matrix.Matrix(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - if (i > j) { - X[i][j] = data[i][j]; - } else if (i === j) { - X[i][j] = 1; - } else { - X[i][j] = 0; - } - } - } - return X; - }, - get upperTriangularMatrix() { - var data = this.LU, - rows = data.rows, - columns = data.columns, - X = new Matrix.Matrix(rows, columns); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - if (i <= j) { - X[i][j] = data[i][j]; - } else { - X[i][j] = 0; - } - } - } - return X; - }, - get pivotPermutationVector() { - return this.pivotVector.slice(); - }, - solve: function (value) { - value = Matrix.Matrix.checkMatrix(value); +var distance = __webpack_require__(41); +Math.Distance = distance.distance; +Math.Similarity = distance.similarity; +Math.DistanceMatrix = __webpack_require__(40); +Math.SG = __webpack_require__(91); +Math.SGG = __webpack_require__(90); +Math.Matrix = exports.Matrix; +Math.SparseMatrix = __webpack_require__(93); +Math.Kernel = __webpack_require__(20); - var lu = this.LU, - rows = lu.rows; +// Statistics packages +var Stat = exports.Stat = {}; - if (rows !== value.rows) { - throw new Error('Invalid matrix dimensions'); - } - if (this.isSingular()) { - throw new Error('LU matrix is singular'); - } +Stat.array = __webpack_require__(2).array; +Stat.matrix = __webpack_require__(2).matrix; +Stat.PCA = __webpack_require__(86); +Stat.Performance = __webpack_require__(87); - var count = value.columns; - var X = value.subMatrixRow(this.pivotVector, 0, count - 1); - var columns = lu.columns; - var i, j, k; +// Math packages +var Optimization = exports.Optimization = {}; - for (k = 0; k < columns; k++) { - for (i = k + 1; i < columns; i++) { - for (j = 0; j < count; j++) { - X[i][j] -= X[k][j] * lu[i][k]; - } - } - } - for (k = columns - 1; k >= 0; k--) { - for (j = 0; j < count; j++) { - X[k][j] /= lu[k][k]; - } - for (i = 0; i < k; i++) { - for (j = 0; j < count; j++) { - X[i][j] -= X[k][j] * lu[i][k]; - } - } - } - return X; - } -}; +Optimization.BellOptimizer = __webpack_require__(85); +Optimization.LevenbergMarquardt = __webpack_require__(83); -module.exports = LuDecomposition; +// Random number generation +var RNG = exports.RNG = {}; +RNG.XSadd = __webpack_require__(95); + +// Supervised learning +var SL = exports.SL = {}; + +SL.CV = __webpack_require__(78); +SL.CrossValidation = SL.CV; // Alias +SL.SVM = __webpack_require__(94); +SL.KNN = __webpack_require__(82); +SL.NaiveBayes = __webpack_require__(84); +SL.PLS = __webpack_require__(88); + +// Clustering +var Clust = exports.Clust = {}; +Clust.kmeans = __webpack_require__(81); +Clust.hclust = __webpack_require__(80); + +// Neural networks +var NN = exports.NN = exports.nn = {}; + +NN.SOM = __webpack_require__(92); +NN.FNN = __webpack_require__(79); /***/ }), -/* 39 */ +/* 98 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +module.exports = __webpack_require__(99); -var Matrix = __webpack_require__(0); -var Stat = __webpack_require__(2); +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports.NaiveBayes = NaiveBayes; -module.exports.separateClasses = separateClasses; +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Generated by CoffeeScript 1.8.0 +(function() { + var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; -/** - * Constructor for the Naive Bayes classifier, the parameters here is just for loading purposes. - * - * @param reload - * @param model - * @constructor - */ -function NaiveBayes(reload, model) { - if(reload) { - this.means = model.means; - this.calculateProbabilities = model.calculateProbabilities; + floor = Math.floor, min = Math.min; + + + /* + Default comparison function to be used + */ + + defaultCmp = function(x, y) { + if (x < y) { + return -1; } -} + if (x > y) { + return 1; + } + return 0; + }; -/** - * 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 trainingSet - * @param trainingLabels - */ -NaiveBayes.prototype.train = function (trainingSet, trainingLabels) { - var C1 = Math.sqrt(2*Math.PI); // constant to precalculate the squared root - if(!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet); - else trainingSet = trainingSet.clone(); - if(trainingSet.rows !== trainingLabels.length) - throw new RangeError("the size of the training set and the training labels must be the same."); + /* + 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. + */ - 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 = Stat.matrix.mean(separatedClasses[i]); - var std = Stat.matrix.standardDeviation(separatedClasses[i], means); + insort = function(a, x, lo, hi, cmp) { + var mid; + if (lo == null) { + lo = 0; + } + if (cmp == null) { + cmp = defaultCmp; + } + if (lo < 0) { + throw new Error('lo must be non-negative'); + } + if (hi == null) { + hi = a.length; + } + while (lo < hi) { + mid = floor((lo + hi) / 2); + if (cmp(x, a[mid]) < 0) { + hi = mid; + } else { + lo = mid + 1; + } + } + return ([].splice.apply(a, [lo, lo - lo].concat(x)), x); + }; - var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows); - calculateProbabilities[i] = new Array(means.length + 1); - calculateProbabilities[i][0] = logPriorProbability; - for(var j = 1; j < means.length + 1; ++j) { - var currentStd = std[j - 1]; - calculateProbabilities[i][j] = [(1 / (C1 * currentStd)), -2*currentStd*currentStd]; - } + /* + Push item onto heap, maintaining the heap invariant. + */ - this.means[i] = means; + heappush = function(array, item, cmp) { + if (cmp == null) { + cmp = defaultCmp; + } + 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; + } + lastelt = array.pop(); + if (array.length) { + returnitem = array[0]; + array[0] = lastelt; + _siftup(array, 0, cmp); + } else { + returnitem = lastelt; + } + 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) + */ + + heapreplace = function(array, item, cmp) { + var returnitem; + if (cmp == null) { + cmp = defaultCmp; + } + returnitem = array[0]; + array[0] = item; + _siftup(array, 0, cmp); + return returnitem; + }; + + + /* + Fast version of a heappush followed by a heappop. + */ + + heappushpop = function(array, item, cmp) { + var _ref; + if (cmp == null) { + cmp = defaultCmp; + } + if (array.length && cmp(array[0], item) < 0) { + _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; + _siftup(array, 0, cmp); + } + return item; + }; + + + /* + Transform list into a heap, in-place, in O(array.length) time. + */ + + heapify = function(array, cmp) { + var i, _i, _j, _len, _ref, _ref1, _results, _results1; + if (cmp == null) { + cmp = defaultCmp; + } + _ref1 = (function() { + _results1 = []; + for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); } + return _results1; + }).apply(this).reverse(); + _results = []; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + i = _ref1[_i]; + _results.push(_siftup(array, i, cmp)); + } + return _results; + }; + + + /* + Update the position of the given item in the heap. + This function should be called every time the item is being modified. + */ + + updateItem = function(array, item, cmp) { + var pos; + if (cmp == null) { + cmp = defaultCmp; } + pos = array.indexOf(item); + if (pos === -1) { + return; + } + _siftdown(array, 0, pos, cmp); + return _siftup(array, pos, cmp); + }; - this.calculateProbabilities = calculateProbabilities; -}; - -/** - * function that predicts each row of the dataset (must be a matrix). - * - * @param dataset - * @returns {Array} - */ -NaiveBayes.prototype.predict = function (dataset) { - if(dataset[0].length === this.calculateProbabilities[0].length) - throw new RangeError('the dataset must have the same features as the training set'); - var predictions = new Array(dataset.length); + /* + Find the n largest elements in a dataset. + */ - for(var i = 0; i < predictions.length; ++i) { - predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities); + nlargest = function(array, n, cmp) { + var elem, result, _i, _len, _ref; + if (cmp == null) { + cmp = defaultCmp; } + result = array.slice(0, n); + if (!result.length) { + return result; + } + heapify(result, cmp); + _ref = array.slice(n); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + heappushpop(result, elem, cmp); + } + return result.sort(cmp).reverse(); + }; - return predictions; -}; - -/** - * Function the retrieves a prediction with one case. - * - * @param currentCase - * @param mean - Precalculated means of each class trained - * @param classes - Precalculated value of each class (Prior probability and probability function of each feature) - * @returns {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 - 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]); - } + /* + Find the n smallest elements in a dataset. + */ - currentProbability = Math.exp(currentProbability); - if(currentProbability > maxProbability) { - maxProbability = currentProbability; - predictedClass = i; + nsmallest = function(array, n, cmp) { + var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; + if (cmp == null) { + cmp = defaultCmp; + } + if (n * 10 <= array.length) { + result = array.slice(0, n).sort(cmp); + if (!result.length) { + return result; + } + los = result[result.length - 1]; + _ref = array.slice(n); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + elem = _ref[_i]; + if (cmp(elem, los) < 0) { + insort(result, elem, 0, null, cmp); + result.pop(); + los = result[result.length - 1]; } + } + return result; + } + heapify(array, cmp); + _results = []; + for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { + _results.push(heappop(array, cmp)); } + return _results; + }; - return predictedClass; -} + _siftdown = function(array, startpos, pos, cmp) { + var newitem, parent, parentpos; + if (cmp == null) { + cmp = defaultCmp; + } + newitem = array[pos]; + while (pos > startpos) { + parentpos = (pos - 1) >> 1; + parent = array[parentpos]; + if (cmp(newitem, parent) < 0) { + array[pos] = parent; + pos = parentpos; + continue; + } + break; + } + return array[pos] = newitem; + }; -/** - * Function that export the NaiveBayes model. - * @returns {{modelName: string, means: *, calculateProbabilities: *}} - */ -NaiveBayes.prototype.export = function () { - return { - modelName: "NaiveBayes", - means: this.means, - calculateProbabilities: this.calculateProbabilities - }; -}; + _siftup = function(array, pos, cmp) { + var childpos, endpos, newitem, rightpos, startpos; + if (cmp == null) { + cmp = defaultCmp; + } + endpos = array.length; + startpos = pos; + newitem = array[pos]; + childpos = 2 * pos + 1; + while (childpos < endpos) { + rightpos = childpos + 1; + if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { + childpos = rightpos; + } + array[pos] = array[childpos]; + pos = childpos; + childpos = 2 * pos + 1; + } + array[pos] = newitem; + return _siftdown(array, startpos, pos, cmp); + }; -/** - * Function that create a Naive Bayes classifier with the given model. - * @param model - * @returns {NaiveBayes} - */ -NaiveBayes.load = function (model) { - if(model.modelName !== 'NaiveBayes') - throw new RangeError("The given model is invalid!"); + Heap = (function() { + Heap.push = heappush; - return new NaiveBayes(true, model); -}; + Heap.pop = heappop; -/** - * function that retrieves the probability of the feature given the class. - * @param value - value of the feature. - * @param mean - mean of the feature for the given class. - * @param C1 - precalculated value of (1 / (sqrt(2*pi) * std)). - * @param C2 - precalculated value of (2 * std^2) for the denominator of the exponential. - * @returns {number} - */ -function calculateLogProbability(value, mean, C1, C2) { - var value = value - mean; - return Math.log(C1 * Math.exp((value * value) / C2)) -} + Heap.replace = heapreplace; -/** - * Function that retuns an array of matrices of the cases that belong to each class. - * @param X - dataset - * @param y - predictions - * @returns {Array} - */ -function separateClasses(X, y) { - var features = X.columns; + Heap.pushpop = heappushpop; - var classes = 0; - var totalPerClasses = new Array(100); // max upperbound of classes - for (var i = 0; i < y.length; i++) { - if(totalPerClasses[y[i]] === undefined) { - totalPerClasses[y[i]] = 0; - classes++; - } - totalPerClasses[y[i]]++; - } - var separatedClasses = new Array(classes); - var currentIndex = new Array(classes); - for(i = 0; i < classes; ++i) { - separatedClasses[i] = new 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]]++; - } - return separatedClasses; -} + Heap.heapify = heapify; + Heap.updateItem = updateItem; -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { + Heap.nlargest = nlargest; -"use strict"; + Heap.nsmallest = nsmallest; + function Heap(cmp) { + this.cmp = cmp != null ? cmp : defaultCmp; + this.nodes = []; + } -/** - * Function that return a constants of the M degree polynomial that - * fit the given points, this constants is given from lower to higher - * order of the polynomial. - * - * @param {Vector} X - Vector of the x positions of the points. - * @param {Vector} Y - Vector of the y positions of the points. - * @param {Number|BigNumber} M - Degree of the polynomial. - * @param {Vector} constants - Vector of constants of the function. - * Created by acastillo on 5/12/16. - */ + Heap.prototype.push = function(x) { + return heappush(this.nodes, x, this.cmp); + }; -const maybeToPrecision = __webpack_require__(6).maybeToPrecision; -const BaseRegression = __webpack_require__(4); -const Matrix = __webpack_require__(0); + Heap.prototype.pop = function() { + return heappop(this.nodes, this.cmp); + }; + Heap.prototype.peek = function() { + return this.nodes[0]; + }; -class PolynomialRegression extends BaseRegression { - /** - * @constructor - * @param x: Independent variable - * @param y: Dependent variable - * @param M: Maximum degree of the polynomial - * @param options - */ - constructor(x, y, M, options) { - super(); - let opt = options || {}; - if (x === true) { // reloading model - this.coefficients = y.coefficients; - this.powers = y.powers; - this.M = y.M; - if (y.quality) { - this.quality = y.quality; - } - } else { - var n = x.length; - if (n !== y.length) { - throw new RangeError('input and output array have a different length'); - } + Heap.prototype.contains = function(x) { + return this.nodes.indexOf(x) !== -1; + }; - let powers; - if (Array.isArray(M)) { - powers = M; - M = powers.length; - } else { - M++; - powers = new Array(M); - for (k = 0; k < M; k++) { - powers[k] = k; - } - } - var F = new Matrix(n, M); - var Y = new Matrix([y]); - var k, i; - for (k = 0; k < M; k++) { - for (i = 0; i < n; i++) { - if (powers[k] === 0) { - F[i][k] = 1; - } else { - F[i][k] = Math.pow(x[i], powers[k]); - } - } - } + Heap.prototype.replace = function(x) { + return heapreplace(this.nodes, x, this.cmp); + }; - var FT = F.transposeView(); - var A = FT.mmul(F); - var B = FT.mmul(Y.transposeView()); + Heap.prototype.pushpop = function(x) { + return heappushpop(this.nodes, x, this.cmp); + }; - this.coefficients = A.solve(B).to1DArray(); - this.powers = powers; - this.M = M - 1; - if (opt.computeQuality) { - this.quality = this.modelQuality(x, y); - } - } - } + Heap.prototype.heapify = function() { + return heapify(this.nodes, this.cmp); + }; - _predict(x) { - var y = 0; - for (var k = 0; k < this.powers.length; k++) { - y += this.coefficients[k] * Math.pow(x, this.powers[k]); - } - return y; - } + Heap.prototype.updateItem = function(x) { + return updateItem(this.nodes, x, this.cmp); + }; - toJSON() { - var out = {name: 'polynomialRegression', - coefficients: this.coefficients, - powers: this.powers, - M: this.M - }; + Heap.prototype.clear = function() { + return this.nodes = []; + }; - if (this.quality) { - out.quality = this.quality; - } - return out; - } + Heap.prototype.empty = function() { + return this.nodes.length === 0; + }; - toString(precision) { - return this._toFormula(precision, false); - } + Heap.prototype.size = function() { + return this.nodes.length; + }; - toLaTeX(precision) { - return this._toFormula(precision, true); - } + Heap.prototype.clone = function() { + var heap; + heap = new Heap(); + heap.nodes = this.nodes.slice(0); + return heap; + }; - _toFormula(precision, isLaTeX) { - var sup = '^'; - var closeSup = ''; - var times = ' * '; - if (isLaTeX) { - sup = '^{'; - closeSup = '}'; - times = ''; - } + Heap.prototype.toArray = function() { + return this.nodes.slice(0); + }; - var fn = '', str; - for (var 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; - } - } + Heap.prototype.insert = Heap.prototype.push; - 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); - } + Heap.prototype.top = Heap.prototype.peek; - return 'f(x) = ' + fn; - } + Heap.prototype.front = Heap.prototype.peek; - static load(json) { - if (json.name !== 'polynomialRegression') { - throw new TypeError('not a polynomial regression model'); - } - return new PolynomialRegression(true, json); + Heap.prototype.has = Heap.prototype.contains; + + Heap.prototype.copy = Heap.prototype.clone; + + return Heap; + + })(); + + (function(root, factory) { + if (true) { + return !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else if (typeof exports === 'object') { + return module.exports = factory(); + } else { + return root.Heap = factory(); } -} + })(this, function() { + return Heap; + }); -module.exports = PolynomialRegression; +}).call(this); /***/ }), -/* 41 */ +/* 100 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -function compareNumbers(a, b) { - return a - b; -} - +const Stat = __webpack_require__(2).array; /** - * Computes the sum of the given values - * @param {Array} values - * @returns {number} + * Function that returns an array of points given 1D array as follows: + * + * [x1, y1, .. , x2, y2, ..] + * + * And receive the number of dimensions of each point. + * @param array + * @param dimensions + * @returns {Array} - Array of points. */ -exports.sum = function sum(values) { - var sum = 0; - for (var i = 0; i < values.length; i++) { - sum += values[i]; +function coordArrayToPoints(array, dimensions) { + if(array.length % dimensions !== 0) { + throw new RangeError('Dimensions number must be accordance with the size of the array.'); } - return sum; -}; -/** - * Computes the maximum of the given values - * @param {Array} values - * @returns {number} - */ -exports.max = function max(values) { - var max = -Infinity; - var l = values.length; - for (var i = 0; i < l; i++) { - if (values[i] > max) max = values[i]; + var length = array.length / dimensions; + var pointsArr = new Array(length); + + var k = 0; + for(var i = 0; i < array.length; i += dimensions) { + var point = new Array(dimensions); + for(var j = 0; j < dimensions; ++j) { + point[j] = array[i + j]; + } + + pointsArr[k] = point; + k++; } - return max; -}; + + return pointsArr; +} + /** - * Computes the minimum of the given values - * @param {Array} values - * @returns {number} + * Function that given an array as follows: + * [x1, y1, .. , x2, y2, ..] + * + * Returns an array as follows: + * [[x1, x2, ..], [y1, y2, ..], [ .. ]] + * + * And receives the number of dimensions of each coordinate. + * @param array + * @param dimensions + * @returns {Array} - Matrix of coordinates */ -exports.min = function min(values) { - var min = Infinity; - var l = values.length; - for (var i = 0; i < l; i++) { - if (values[i] < min) min = values[i]; +function coordArrayToCoordMatrix(array, dimensions) { + if(array.length % dimensions !== 0) { + throw new RangeError('Dimensions number must be accordance with the size of the array.'); } - return min; -}; -/** - * Computes the min and max of the given values - * @param {Array} values - * @returns {{min: number, max: number}} - */ -exports.minMax = function minMax(values) { - var min = Infinity; - var max = -Infinity; - var l = values.length; - for (var i = 0; i < l; i++) { - if (values[i] < min) min = values[i]; - if (values[i] > max) max = values[i]; + var coordinatesArray = new Array(dimensions); + var points = array.length / dimensions; + for (var i = 0; i < coordinatesArray.length; i++) { + coordinatesArray[i] = new Array(points); } - return { - min: min, - max: max - }; -}; -/** - * Computes the arithmetic mean of the given values - * @param {Array} values - * @returns {number} - */ -exports.arithmeticMean = function arithmeticMean(values) { - var sum = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - sum += values[i]; + for(i = 0; i < array.length; i += dimensions) { + for(var j = 0; j < dimensions; ++j) { + var currentPoint = Math.floor(i / dimensions); + coordinatesArray[j][currentPoint] = array[i + j]; + } } - return sum / l; -}; + + return coordinatesArray; +} /** - * {@link arithmeticMean} + * Function that receives a coordinate matrix as follows: + * [[x1, x2, ..], [y1, y2, ..], [ .. ]] + * + * Returns an array of coordinates as follows: + * [x1, y1, .. , x2, y2, ..] + * + * @param coordMatrix + * @returns {Array} */ -exports.mean = exports.arithmeticMean; +function coordMatrixToCoordArray(coordMatrix) { + var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length); + var k = 0; + for(var i = 0; i < coordMatrix[0].length; ++i) { + for(var j = 0; j < coordMatrix.length; ++j) { + coodinatesArray[k] = coordMatrix[j][i]; + ++k; + } + } + + return coodinatesArray; +} /** - * Computes the geometric mean of the given values - * @param {Array} values - * @returns {number} + * Tranpose a matrix, this method is for coordMatrixToPoints and + * pointsToCoordMatrix, that because only transposing the matrix + * you can change your representation. + * + * @param matrix + * @returns {Array} */ -exports.geometricMean = function geometricMean(values) { - var mul = 1; - var l = values.length; - for (var i = 0; i < l; i++) { - mul *= values[i]; +function transpose(matrix) { + var resultMatrix = new Array(matrix[0].length); + for(var i = 0; i < resultMatrix.length; ++i) { + resultMatrix[i] = new Array(matrix.length); } - return Math.pow(mul, 1 / l); -}; -/** - * Computes the mean of the log of the given values - * If the return value is exponentiated, it gives the same result as the - * geometric mean. - * @param {Array} values - * @returns {number} - */ -exports.logMean = function logMean(values) { - var lnsum = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - lnsum += Math.log(values[i]); + for (i = 0; i < matrix.length; ++i) { + for(var j = 0; j < matrix[0].length; ++j) { + resultMatrix[j][i] = matrix[i][j]; + } } - return lnsum / l; -}; + + return resultMatrix; +} /** - * Computes the weighted grand mean for a list of means and sample sizes - * @param {Array} means - Mean values for each set of samples - * @param {Array} samples - Number of original values for each set of samples - * @returns {number} + * Function that transform an array of points into a coordinates array + * as follows: + * [x1, y1, .. , x2, y2, ..] + * + * @param points + * @returns {Array} */ -exports.grandMean = function grandMean(means, samples) { - var sum = 0; - var n = 0; - var l = means.length; - for (var i = 0; i < l; i++) { - sum += samples[i] * means[i]; - n += samples[i]; +function pointsToCoordArray(points) { + var coodinatesArray = new Array(points.length * points[0].length); + var k = 0; + for(var i = 0; i < points.length; ++i) { + for(var j = 0; j < points[0].length; ++j) { + coodinatesArray[k] = points[i][j]; + ++k; + } } - return sum / n; -}; + + return coodinatesArray; +} /** - * Computes the truncated mean of the given values using a given percentage - * @param {Array} values - * @param {number} percent - The percentage of values to keep (range: [0,1]) - * @param {boolean} [alreadySorted=false] - * @returns {number} + * Apply the dot product between the smaller vector and a subsets of the + * largest one. + * + * @param firstVector + * @param secondVector + * @returns {Array} each dot product of size of the difference between the + * larger and the smallest one. */ -exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) { - if (alreadySorted === undefined) alreadySorted = false; - if (!alreadySorted) { - values = values.slice().sort(compareNumbers); - } - var l = values.length; - var k = Math.floor(l * percent); - var sum = 0; - for (var i = k; i < (l - k); i++) { - sum += values[i]; +function applyDotProduct(firstVector, secondVector) { + var largestVector, smallestVector; + if(firstVector.length <= secondVector.length) { + smallestVector = firstVector; + largestVector = secondVector; + } else { + smallestVector = secondVector; + largestVector = firstVector; } - return sum / (l - 2 * k); -}; -/** - * Computes the harmonic mean of the given values - * @param {Array} values - * @returns {number} - */ -exports.harmonicMean = function harmonicMean(values) { - var sum = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - if (values[i] === 0) { - throw new RangeError('value at index ' + i + 'is zero'); + var difference = largestVector.length - smallestVector.length + 1; + var dotProductApplied = new Array(difference); + + for (var i = 0; i < difference; ++i) { + var sum = 0; + for (var j = 0; j < smallestVector.length; ++j) { + sum += smallestVector[j] * largestVector[i + j]; } - sum += 1 / values[i]; + dotProductApplied[i] = sum; } - return l / sum; -}; + return dotProductApplied; +} /** - * Computes the contraharmonic mean of the given values - * @param {Array} values - * @returns {number} + * To scale the input array between the specified min and max values. The operation is performed inplace + * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling + * will multiply the input array by min/min(input) or max/max(input) + * @param input + * @param options + * @returns {*} */ -exports.contraHarmonicMean = function contraHarmonicMean(values) { - var r1 = 0; - var r2 = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - r1 += values[i] * values[i]; - r2 += values[i]; +function scale(input, options){ + var y; + if(options.inPlace){ + y = input; } - if (r2 < 0) { - throw new RangeError('sum of values is negative'); + else{ + y = new Array(input.length); } - return r1 / r2; + const max = options.max; + const min = options.min; + if(typeof max === "number"){ + if(typeof min === "number"){ + var minMax = Stat.minMax(input); + var factor = (max - min)/(minMax.max-minMax.min); + for(var i=0;i< y.length;i++){ + y[i]=(input[i]-minMax.min)*factor+min; + } + } + else{ + var currentMin = Stat.max(input); + var factor = max/currentMin; + for(var i=0;i< y.length;i++){ + y[i] = input[i]*factor; + } + } + } + else{ + if(typeof min === "number"){ + var currentMin = Stat.min(input); + var factor = min/currentMin; + for(var i=0;i< y.length;i++){ + y[i] = input[i]*factor; + } + } + } + return y; +} + +module.exports = { + coordArrayToPoints: coordArrayToPoints, + coordArrayToCoordMatrix: coordArrayToCoordMatrix, + coordMatrixToCoordArray: coordMatrixToCoordArray, + coordMatrixToPoints: transpose, + pointsToCoordArray: pointsToCoordArray, + pointsToCoordMatrix: transpose, + applyDotProduct: applyDotProduct, + scale:scale }; + + +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + /** - * Computes the median of the given values - * @param {Array} values - * @param {boolean} [alreadySorted=false] - * @returns {number} + * + * Function that returns a Number array of equally spaced numberOfPoints + * containing a representation of intensities of the spectra arguments x + * and y. + * + * The options parameter contains an object in the following form: + * from: starting point + * to: last point + * numberOfPoints: number of points between from and to + * variant: "slot" or "smooth" - smooth is the default option + * + * The slot variant consist that each point in the new array is calculated + * averaging the existing points between the slot that belongs to the current + * value. The smooth variant is the same but takes the integral of the range + * of the slot and divide by the step size between two points in the new array. + * + * @param x - sorted increasing x values + * @param y + * @param options + * @returns {Array} new array with the equally spaced data. + * */ -exports.median = function median(values, alreadySorted) { - if (alreadySorted === undefined) alreadySorted = false; - if (!alreadySorted) { - values = values.slice().sort(compareNumbers); +function getEquallySpacedData(x, y, options) { + if (x.length>1 && x[0]>x[1]) { + x=x.slice().reverse(); + y=y.slice().reverse(); } - var l = values.length; - var half = Math.floor(l / 2); - if (l % 2 === 0) { - return (values[half - 1] + values[half]) * 0.5; - } else { - return values[half]; + + var xLength = x.length; + if(xLength !== y.length) + throw new RangeError("the x and y vector doesn't have the same size."); + + if (options === undefined) options = {}; + + var from = options.from === undefined ? x[0] : options.from + if (isNaN(from) || !isFinite(from)) { + throw new RangeError("'From' value must be a number"); + } + var to = options.to === undefined ? x[x.length - 1] : options.to; + if (isNaN(to) || !isFinite(to)) { + throw new RangeError("'To' value must be a number"); } -}; - -/** - * Computes the variance of the given values - * @param {Array} values - * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. - * @returns {number} - */ -exports.variance = function variance(values, unbiased) { - if (unbiased === undefined) unbiased = true; - var theMean = exports.mean(values); - var theVariance = 0; - var l = values.length; - for (var i = 0; i < l; i++) { - var x = values[i] - theMean; - theVariance += x * x; + var reverse = from > to; + if(reverse) { + var temp = from; + from = to; + to = temp; } - if (unbiased) { - return theVariance / (l - 1); - } else { - return theVariance / l; + var numberOfPoints = options.numberOfPoints === undefined ? 100 : options.numberOfPoints; + if (isNaN(numberOfPoints) || !isFinite(numberOfPoints)) { + throw new RangeError("'Number of points' value must be a number"); } -}; + if(numberOfPoints < 1) + throw new RangeError("the number of point must be higher than 1"); + + var algorithm = options.variant === "slot" ? "slot" : "smooth"; // default value: smooth + + var output = algorithm === "slot" ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints); + + return reverse ? output.reverse() : output; +} /** - * Computes the standard deviation of the given values - * @param {Array} values - * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n. - * @returns {number} + * function that retrieves the getEquallySpacedData with the variant "smooth" + * + * @param x + * @param y + * @param from - Initial point + * @param to - Final point + * @param numberOfPoints + * @returns {Array} - Array of y's equally spaced with the variant "smooth" */ -exports.standardDeviation = function standardDeviation(values, unbiased) { - return Math.sqrt(exports.variance(values, unbiased)); -}; +function getEquallySpacedSmooth(x, y, from, to, numberOfPoints) { + var xLength = x.length; -exports.standardError = function standardError(values) { - return exports.standardDeviation(values) / Math.sqrt(values.length); -}; + var step = (to - from) / (numberOfPoints - 1); + var halfStep = step / 2; -exports.quartiles = function quartiles(values, alreadySorted) { - if (typeof(alreadySorted) === 'undefined') alreadySorted = false; - if (!alreadySorted) { - values = values.slice(); - values.sort(compareNumbers); - } + var start = from - halfStep; + var output = new Array(numberOfPoints); - var quart = values.length / 4; - var q1 = values[Math.ceil(quart) - 1]; - var q2 = exports.median(values, true); - var q3 = values[Math.ceil(quart * 3) - 1]; + var initialOriginalStep = x[1] - x[0]; + var lastOriginalStep = x[x.length - 1] - x[x.length - 2]; - return {q1: q1, q2: q2, q3: q3}; -}; + // Init main variables + var min = start; + var max = start + step; -exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) { - return Math.sqrt(exports.pooledVariance(samples, unbiased)); -}; + var previousX = Number.MIN_VALUE; + var previousY = 0; + var nextX = x[0] - initialOriginalStep; + var nextY = 0; -exports.pooledVariance = function pooledVariance(samples, unbiased) { - if (typeof(unbiased) === 'undefined') unbiased = true; - var sum = 0; - var length = 0, l = samples.length; - for (var i = 0; i < l; i++) { - var values = samples[i]; - var vari = exports.variance(values); + var currentValue = 0; + var slope = 0; + var intercept = 0; + var sumAtMin = 0; + var sumAtMax = 0; - sum += (values.length - 1) * vari; + var i = 0; // index of input + var j = 0; // index of output - if (unbiased) - length += values.length - 1; - else - length += values.length; + function getSlope(x0, y0, x1, y1) { + return (y1 - y0) / (x1 - x0); } - return sum / length; -}; -exports.mode = function mode(values) { - var l = values.length, - itemCount = new Array(l), - i; - for (i = 0; i < l; i++) { - itemCount[i] = 0; - } - var itemArray = new Array(l); - var count = 0; + main: while(true) { + while (nextX - max >= 0) { + // no overlap with original point, just consume current value + var add = integral(0, max - previousX, slope, previousY); + sumAtMax = currentValue + add; - for (i = 0; i < l; i++) { - var index = itemArray.indexOf(values[i]); - if (index >= 0) - itemCount[index]++; - else { - itemArray[count] = values[i]; - itemCount[count] = 1; - count++; - } - } + output[j] = (sumAtMax - sumAtMin) / step; + j++; - var maxValue = 0, maxIndex = 0; - for (i = 0; i < count; i++) { - if (itemCount[i] > maxValue) { - maxValue = itemCount[i]; - maxIndex = i; + if (j === numberOfPoints) + break main; + + min = max; + max += step; + sumAtMin = sumAtMax; } - } - return itemArray[maxIndex]; -}; + if(previousX <= min && min <= nextX) { + add = integral(0, min - previousX, slope, previousY); + sumAtMin = currentValue + add; + } -exports.covariance = function covariance(vector1, vector2, unbiased) { - if (typeof(unbiased) === 'undefined') unbiased = true; - var mean1 = exports.mean(vector1); - var mean2 = exports.mean(vector2); + currentValue += integral(previousX, nextX, slope, intercept); - if (vector1.length !== vector2.length) - throw "Vectors do not have the same dimensions"; + previousX = nextX; + previousY = nextY; - var cov = 0, l = vector1.length; - for (var i = 0; i < l; i++) { - var x = vector1[i] - mean1; - var y = vector2[i] - mean2; - cov += x * y; + if (i < xLength) { + nextX = x[i]; + nextY = y[i]; + i++; + } else if (i === xLength) { + nextX += lastOriginalStep; + nextY = 0; + } + // updating parameters + slope = getSlope(previousX, previousY, nextX, nextY); + intercept = -slope*previousX + previousY; } - if (unbiased) - return cov / (l - 1); - else - return cov / l; -}; + return output; +} -exports.skewness = function skewness(values, unbiased) { - if (typeof(unbiased) === 'undefined') unbiased = true; - var theMean = exports.mean(values); +/** + * function that retrieves the getEquallySpacedData with the variant "slot" + * + * @param x + * @param y + * @param from - Initial point + * @param to - Final point + * @param numberOfPoints + * @returns {Array} - Array of y's equally spaced with the variant "slot" + */ +function getEquallySpacedSlot(x, y, from, to, numberOfPoints) { + var xLength = x.length; - var s2 = 0, s3 = 0, l = values.length; - for (var i = 0; i < l; i++) { - var dev = values[i] - theMean; - s2 += dev * dev; - s3 += dev * dev * dev; - } - var m2 = s2 / l; - var m3 = s3 / l; + var step = (to - from) / (numberOfPoints - 1); + var halfStep = step / 2; + var lastStep = x[x.length - 1] - x[x.length - 2]; - var g = m3 / (Math.pow(m2, 3 / 2.0)); - if (unbiased) { - var a = Math.sqrt(l * (l - 1)); - var b = l - 2; - return (a / b) * g; - } - else { - return g; - } -}; + var start = from - halfStep; + var output = new Array(numberOfPoints); -exports.kurtosis = function kurtosis(values, unbiased) { - if (typeof(unbiased) === 'undefined') unbiased = true; - var theMean = exports.mean(values); - var n = values.length, s2 = 0, s4 = 0; + // Init main variables + var min = start; + var max = start + step; - for (var i = 0; i < n; i++) { - var dev = values[i] - theMean; - s2 += dev * dev; - s4 += dev * dev * dev * dev; - } - var m2 = s2 / n; - var m4 = s4 / n; + var previousX = -Number.MAX_VALUE; + var previousY = 0; + var nextX = x[0]; + var nextY = y[0]; + var frontOutsideSpectra = 0; + var backOutsideSpectra = true; - if (unbiased) { - var v = s2 / (n - 1); - var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3)); - var b = s4 / (v * v); - var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3)); + var currentValue = 0; + + // for slot algorithm + var currentPoints = 0; + + var i = 1; // index of input + var j = 0; // index of output + + main: while(true) { + if (previousX>=nextX) throw (new Error('x must be an increasing serie')); + while (previousX - max > 0) { + // no overlap with original point, just consume current value + if(backOutsideSpectra) { + currentPoints++; + backOutsideSpectra = false; + } - return a * b - 3 * c; - } - else { - return m4 / (m2 * m2) - 3; - } -}; + output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints; + j++; -exports.entropy = function entropy(values, eps) { - if (typeof(eps) === 'undefined') eps = 0; - var sum = 0, l = values.length; - for (var i = 0; i < l; i++) - sum += values[i] * Math.log(values[i] + eps); - return -sum; -}; + if (j === numberOfPoints) + break main; -exports.weightedMean = function weightedMean(values, weights) { - var sum = 0, l = values.length; - for (var i = 0; i < l; i++) - sum += values[i] * weights[i]; - return sum; -}; + min = max; + max += step; + currentValue = 0; + currentPoints = 0; + } -exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) { - return Math.sqrt(exports.weightedVariance(values, weights)); -}; + if(previousX > min) { + currentValue += previousY; + currentPoints++; + } -exports.weightedVariance = function weightedVariance(values, weights) { - var theMean = exports.weightedMean(values, weights); - var vari = 0, l = values.length; - var a = 0, b = 0; + if(previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) + currentPoints--; - for (var i = 0; i < l; i++) { - var z = values[i] - theMean; - var w = weights[i]; + previousX = nextX; + previousY = nextY; - vari += w * (z * z); - b += w; - a += w * w; + if (i < xLength) { + nextX = x[i]; + nextY = y[i]; + i++; + } else { + nextX += lastStep; + nextY = 0; + frontOutsideSpectra++; + } } - return vari * (b / (b * b - a)); -}; + return output; +} +/** + * Function that calculates the integral of the line between two + * x-coordinates, given the slope and intercept of the line. + * + * @param x0 + * @param x1 + * @param slope + * @param intercept + * @returns {number} integral value. + */ +function integral(x0, x1, slope, intercept) { + return (0.5 * slope * x1 * x1 + intercept * x1) - (0.5 * slope * x0 * x0 + intercept * x0); +} -exports.center = function center(values, inPlace) { - if (typeof(inPlace) === 'undefined') inPlace = false; +exports.getEquallySpacedData = getEquallySpacedData; +exports.integral = integral; - var result = values; - if (!inPlace) - result = values.slice(); +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { - var theMean = exports.mean(result), l = result.length; - for (var i = 0; i < l; i++) - result[i] -= theMean; -}; +"use strict"; -exports.standardize = function standardize(values, standardDev, inPlace) { - if (typeof(standardDev) === 'undefined') standardDev = exports.standardDeviation(values); - if (typeof(inPlace) === 'undefined') inPlace = false; - var l = values.length; - var result = inPlace ? values : new Array(l); - for (var i = 0; i < l; i++) - result[i] = values[i] / standardDev; - return result; -}; -exports.cumulativeSum = function cumulativeSum(array) { - var l = array.length; - var result = new Array(l); - result[0] = array[0]; - for (var i = 1; i < l; i++) - result[i] = result[i - 1] + array[i]; +exports.SNV = SNV; +var Stat = __webpack_require__(2).array; + +/** + * Function that applies the standard normal variate (SNV) to an array of values. + * + * @param data - Array of values. + * @returns {Array} - applied the SNV. + */ +function SNV(data) { + var mean = Stat.mean(data); + var std = Stat.standardDeviation(data); + var result = data.slice(); + for (var i = 0; i < data.length; i++) { + result[i] = (result[i] - mean) / std; + } return result; -}; +} /***/ }), -/* 42 */ +/* 103 */ /***/ (function(module, exports) { -function NodeSquare(x, y, weights, som) { - this.x = x; - this.y = y; - this.weights = weights; - this.som = som; - this.neighbors = {}; -} +// auxiliary file to create the 256 look at table elements -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]); +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; +} -NodeSquare.prototype.getDistance = function getDistance(otherNode) { - return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y)); -}; +module.exports = ans; -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)); +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const defaultOptions = { + mode: 'index' }; -NodeSquare.prototype.getNeighbors = function getNeighbors(xy) { - if (!this.neighbors[xy]) { - this.neighbors[xy] = new Array(2); +module.exports = function *(M, N, options) { + options = Object.assign({}, defaultOptions, 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; - // 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]; - } + // init a and b + for (var i = 0; i < N; i++) { + a[i] = i; + if (i < N - M) b[i] = 0; + else b[i] = 1; + } - // 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; + // 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; + } + + 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 { - x = this.x; - y = w; + if (i === p[0]) { + return 0; + } else { + p[j] = p[i]; + z = p[i] - 1; + p[i] = 0; + x = j - 1; + y = i - 1; + } } - this.neighbors[xy][1] = this.som.nodes[x][y]; } + return 1; } - 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; + if (options.mode === 'index') { + yield c.slice(); + while (twiddle()) { + c[z] = a[x]; + yield c.slice(); + } + } else if (options.mode === 'mask') { + yield b.slice(); + while (twiddle()) { + b[x] = 1; + b[y] = 0; + yield b.slice(); } } else { - bestNeighbor = neighbors[1]; - direction = 1; + throw new Error('Invalid mode'); } - var simA = 1 - distance(element, this.weights), - simB = 1 - distance(element, bestNeighbor.weights); - var factor = ((simA - simB) / (2 - simA - simB)); - return 0.5 + 0.5 * factor * direction; -}; - -NodeSquare.prototype.getPosition = function getPosition(element) { - return [ - this.getPos('x', element), - this.getPos('y', element) - ]; }; -module.exports = NodeSquare; /***/ }), -/* 43 */ +/* 105 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var eightBits = __webpack_require__(68); - -/** - * Count the number of true values in an array - * @param {Array} arr - * @return {number} - */ -function count(arr) { - var c = 0; - for (var i = 0; i < arr.length; i++) { - c += eightBits[arr[i] & 0xff] + eightBits[(arr[i] >> 8) & 0xff] + eightBits[(arr[i] >> 16) & 0xff] + eightBits[(arr[i] >> 24) & 0xff]; - } - return c; -} - -/** - * Logical AND operation - * @param {Array} arr1 - * @param {Array} arr2 - * @return {Array} - */ -function and(arr1, arr2) { - var ans = new Array(arr1.length); - for (var i = 0; i < arr1.length; i++) - ans[i] = arr1[i] & arr2[i]; - return ans; -} - -/** - * Logical OR operation - * @param {Array} arr1 - * @param {Array} arr2 - * @return {Array} - */ -function or(arr1, arr2) { - var ans = new Array(arr1.length); - for (var i = 0; i < arr1.length; i++) - ans[i] = arr1[i] | arr2[i]; - return ans; -} - -/** - * Logical XOR operation - * @param {Array} arr1 - * @param {Array} arr2 - * @return {Array} - */ -function xor(arr1, arr2) { - var ans = new Array(arr1.length); - for (var i = 0; i < arr1.length; i++) - ans[i] = arr1[i] ^ arr2[i]; - return ans; -} - -/** - * Logical NOT operation - * @param {Array} arr - * @return {Array} - */ -function not(arr) { - var ans = new Array(arr.length); - for (var i = 0; i < ans.length; i++) - ans[i] = ~arr[i]; - return ans; -} - -/** - * Gets the n value of array arr - * @param {Array} arr - * @param {number} n - * @return {boolean} - */ -function getBit(arr, n) { - var index = n >> 5; // Same as Math.floor(n/32) - var mask = 1 << (31 - n % 32); - return Boolean(arr[index] & mask); -} - -/** - * Sets the n value of array arr to the value val - * @param {Array} arr - * @param {number} n - * @param {boolean} val - * @return {Array} - */ -function setBit(arr, n, val) { - var index = n >> 5; // Same as Math.floor(n/32) - var mask = 1 << (31 - n % 32); - if (val) - arr[index] = mask | arr[index]; - else - arr[index] = ~mask & arr[index]; - return arr; -} - /** - * Translates an array of numbers to a string of bits - * @param {Array} arr - * @returns {string} + * ConfusionMatrix class */ -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 str; -} +class ConfusionMatrix { + /** + * Constructor + * @param {Array} matrix - The confusion matrix, a 2D Array + * @param {Array} labels - Labels of the confusion matrix, a 1D Array + */ + constructor(matrix, labels) { + if (matrix.length !== matrix[0].length) { + throw new Error('Confusion matrix must be square'); + } + if (labels.length !== matrix.length) { + throw new Error('Confusion matrix and labels should have the same length'); + } + this.labels = labels; + this.matrix = matrix; -/** - * Creates an array of numbers based on a string of bits - * @param {string} str - * @returns {Array} - */ -function parseBinaryString(str) { - var len = str.length / 32; - var ans = new Array(len); - for (var i = 0; i < len; i++) { - ans[i] = parseInt(str.substr(i*32, 32), 2) | 0; } - return ans; -} -/** - * Translates an array of numbers to a hex string - * @param {Array} arr - * @returns {string} - */ -function toHexString(arr) { - var str = ''; - for (var i = 0; i < arr.length; i++) { - var obj = (arr[i] >>> 0).toString(16); - str += '00000000'.substr(obj.length) + obj; - } - return str; -} + /** + * Compute the general prediction accuracy + * @returns {number} - The prediction accuracy ([0-1] + */ + get accuracy() { + var correct = 0, incorrect = 0; + for (var i = 0; i < this.matrix.length; i++) { + for (var j = 0; j < this.matrix.length; j++) { + if (i === j) correct += this.matrix[i][j]; + else incorrect += this.matrix[i][j]; + } + } -/** - * Creates an array of numbers based on a hex string - * @param {string} str - * @returns {Array} - */ -function parseHexString(str) { - var len = str.length / 8; - var ans = new Array(len); - for (var i = 0; i < len; i++) { - ans[i] = parseInt(str.substr(i*8, 8), 16) | 0; + return correct / (correct + incorrect); } - return ans; -} -/** - * Creates a human readable string of the array - * @param {Array} arr - * @returns {string} - */ -function toDebug(arr) { - var binary = toBinaryString(arr); - var str = ''; - for (var i = 0; i < arr.length; i++) { - str += '0000'.substr((i * 32).toString(16).length) + (i * 32).toString(16) + ':'; - for (var j = 0; j < 32; j += 4) { - str += ' ' + binary.substr(i * 32 + j, 4); + /** + * Compute the number of predicted observations + * @returns {number} - The number of predicted observations + */ + get nbPredicted() { + var predicted = 0; + for (var i = 0; i < this.matrix.length; i++) { + for (var j = 0; j < this.matrix.length; j++) { + predicted += this.matrix[i][j]; + } } - if (i < arr.length - 1) str += '\n'; + return predicted; } - return str } -module.exports = { - count: count, - and: and, - or: or, - xor: xor, - not: not, - getBit: getBit, - setBit: setBit, - toBinaryString: toBinaryString, - parseBinaryString: parseBinaryString, - toHexString: toHexString, - parseHexString: parseHexString, - toDebug: toDebug -}; +module.exports = ConfusionMatrix; /***/ }), -/* 44 */ +/* 106 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - - -const ConfusionMatrix = __webpack_require__(70); - -const CV = {}; -const combinations = __webpack_require__(69); - /** - * 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 {constructor} Classifier - The classifier 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. - * @returns {ConfusionMatrix} - The cross-validation confusion matrix + * Created by acastillo on 8/5/15. */ -CV.leaveOneOut = function (Classifier, features, labels, classifierOptions) { - return CV.leavePOut(Classifier, features, labels, classifierOptions, 1); -}; +var Matrix = __webpack_require__(0); +var math = __webpack_require__(45); + +var DEBUG = false; +/** Levenberg Marquardt curve-fitting: minimize sum of weighted squared residuals + ---------- INPUT VARIABLES ----------- + func = function of n independent variables, 't', and m parameters, 'p', + returning the simulated model: y_hat = func(t,p,c) + p = n-vector of initial guess of parameter values + t = m-vectors or matrix of independent variables (used as arg to func) + y_dat = m-vectors or matrix of data to be fit by func(t,p) + weight = weighting vector for least squares fit ( weight >= 0 ) ... + inverse of the standard measurement errors + Default: sqrt(d.o.f. / ( y_dat' * y_dat )) + dp = fractional increment of 'p' for numerical derivatives + dp(j)>0 central differences calculated + dp(j)<0 one sided 'backwards' differences calculated + dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed + Default: 0.001; + p_min = n-vector of lower bounds for parameter values + p_max = n-vector of upper bounds for parameter values + c = an optional matrix of values passed to func(t,p,c) + opts = vector of algorithmic parameters + parameter defaults meaning + opts(1) = prnt 3 >1 intermediate results; >2 plots + opts(2) = MaxIter 10*Npar maximum number of iterations + opts(3) = epsilon_1 1e-3 convergence tolerance for gradient + opts(4) = epsilon_2 1e-3 convergence tolerance for parameters + opts(5) = epsilon_3 1e-3 convergence tolerance for Chi-square + opts(6) = epsilon_4 1e-2 determines acceptance of a L-M step + opts(7) = lambda_0 1e-2 initial value of L-M paramter + opts(8) = lambda_UP_fac 11 factor for increasing lambda + opts(9) = lambda_DN_fac 9 factor for decreasing lambda + opts(10) = Update_Type 1 1: Levenberg-Marquardt lambda update + 2: Quadratic update + 3: Nielsen's lambda update equations + ---------- OUTPUT VARIABLES ----------- + p = least-squares optimal estimate of the parameter values + X2 = Chi squared criteria + sigma_p = asymptotic standard error of the parameters + sigma_y = asymptotic standard error of the curve-fit + corr = correlation matrix of the parameters + R_sq = R-squared cofficient of multiple determination + cvg_hst = convergence history -/** - * 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 Classifier - The classifier 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 - * @returns {ConfusionMatrix} - The cross-validation confusion matrix + Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. 22 Sep 2013 + modified from: http://octave.sourceforge.net/optim/function/leasqr.html + using references by + Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15. + Sam Roweis http://www.cs.toronto.edu/~roweis/notes/lm.pdf + Manolis Lourakis http://www.ics.forth.gr/~lourakis/levmar/levmar.pdf + Hans Nielson http://www2.imm.dtu.dk/~hbn/publ/TR9905.ps + Mathworks optimization toolbox reference manual + K. Madsen, H.B., Nielsen, and O. Tingleff + http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf */ -CV.leavePOut = function (Classifier, features, labels, classifierOptions, p) { - check(features, labels); - const distinct = getDistinct(labels); - const confusionMatrix = initMatrix(distinct.length, distinct.length); - var i, N = features.length; - var gen = combinations(p, N); - var allIdx = new Array(N); - for (i = 0; i < N; i++) { - allIdx[i] = i; - } - for (const testIdx of gen) { - var trainIdx = allIdx.slice(); +var LM = { - for (i = testIdx.length - 1; i >= 0; i--) { - trainIdx.splice(testIdx[i], 1); - } + optimize: function(func,p,t,y_dat,weight,dp,p_min,p_max,c,opts){ - validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct); - } + var tensor_parameter = 0; // set to 1 of parameter is a tensor - return new ConfusionMatrix(confusionMatrix, distinct); -}; + var iteration = 0; // iteration counter + //func_calls = 0; // running count of function evaluations -/** - * 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 Classifier - The classifier 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 - * @returns {ConfusionMatrix} - The cross-validation confusion matrix - */ -CV.kFold = function (Classifier, features, labels, classifierOptions, k) { - 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; - } + if((typeof p[0])!="object"){ + for(var i=0;i< p.length;i++){ + p[i]=[p[i]]; + } - var l = Math.floor(N / k); - // create random k-folds - var current = []; - var folds = []; - while (allIdx.length) { - var randi = Math.floor(Math.random() * allIdx.length); - current.push(allIdx[randi]); - allIdx.splice(randi, 1); - if (current.length === l) { - folds.push(current); - current = []; } - } - if (current.length) folds.push(current); - folds = folds.slice(0, k); - + //p = p(:); y_dat = y_dat(:); // make column vectors + var i,k; + var eps = 2^-52; + var Npar = p.length;//length(p); // number of parameters + var Npnt = y_dat.length;//length(y_dat); // number of data points + var p_old = Matrix.zeros(Npar,1); // previous set of parameters + var y_old = Matrix.zeros(Npnt,1); // previous model, y_old = y_hat(t;p_old) + var X2 = 1e-2/eps; // a really big initial Chi-sq value + var X2_old = 1e-2/eps; // a really big initial Chi-sq value + var J = Matrix.zeros(Npnt,Npar); - for (i = 0; i < folds.length; i++) { - var testIdx = folds[i]; - var trainIdx = []; - for (var j = 0; j < folds.length; j++) { - if (j !== i) trainIdx = trainIdx.concat(folds[j]); - } - validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct); - } + if (t.length != y_dat.length) { + console.log('lm.m error: the length of t must equal the length of y_dat'); - return new ConfusionMatrix(confusionMatrix, distinct); -}; + length_t = t.length; + length_y_dat = y_dat.length; + var X2 = 0, corr = 0, sigma_p = 0, sigma_y = 0, R_sq = 0, cvg_hist = 0; + if (!tensor_parameter) { + return; + } + } -function check(features, labels) { - if (features.length !== labels.length) { - throw new Error('features and labels should have the same length'); - } -} + weight = weight||Math.sqrt((Npnt-Npar+1)/(math.multiply(math.transpose(y_dat),y_dat))); + dp = dp || 0.001; + p_min = p_min || math.multiply(Math.abs(p),-100); + p_max = p_max || math.multiply(Math.abs(p),100); + c = c || 1; + // Algorithmic Paramters + //prnt MaxIter eps1 eps2 epx3 eps4 lam0 lamUP lamDN UpdateType + opts = opts ||[ 3,10*Npar, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 1 ]; -function initMatrix(rows, columns) { - return new Array(rows).fill(0).map(() => new Array(columns).fill(0)); -} + var prnt = opts[0]; // >1 intermediate results; >2 plots + var MaxIter = opts[1]; // maximum number of iterations + var epsilon_1 = opts[2]; // convergence tolerance for gradient + var epsilon_2 = opts[3]; // convergence tolerance for parameter + var epsilon_3 = opts[4]; // convergence tolerance for Chi-square + var epsilon_4 = opts[5]; // determines acceptance of a L-M step + var lambda_0 = opts[6]; // initial value of damping paramter, lambda + var lambda_UP_fac = opts[7]; // factor for increasing lambda + var lambda_DN_fac = opts[8]; // factor for decreasing lambda + var Update_Type = opts[9]; // 1: Levenberg-Marquardt lambda update + // 2: Quadratic update + // 3: Nielsen's lambda update equations -function getDistinct(arr) { - var s = new Set(); - for (let i = 0; i < arr.length; i++) { - s.add(arr[i]); - } - return Array.from(s); -} + if ( tensor_parameter && prnt == 3 ) prnt = 2; -function validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct) { - var testFeatures = testIdx.map(function (index) { - return features[index]; - }); - var trainFeatures = trainIdx.map(function (index) { - return features[index]; - }); - var testLabels = testIdx.map(function (index) { - return labels[index]; - }); - var trainLabels = trainIdx.map(function (index) { - return labels[index]; - }); - var classifier = new Classifier(classifierOptions); - classifier.train(trainFeatures, trainLabels); - var predictedLabels = classifier.predict(testFeatures); - for (var i = 0; i < predictedLabels.length; i++) { - confusionMatrix[distinct.indexOf(testLabels[i])][distinct.indexOf(predictedLabels[i])]++; - } -} + if(!dp.length || dp.length == 1){ + var dp_array = new Array(Npar); + for(var i=0;i 2; + //this is a big step + // --- Are parameters [p+h] much better than [p] ? + var hidx = new Array(idx.length); + for(k=0;k epsilon_4 ) { // it IS significantly better + //console.log("Here"); + dX2 = X2 - X2_old; + X2_old = X2; + p_old = p; + y_old = y_hat; + p = p_try; // accept p_try - /** - * Create a new Feedforword neural network model. - * @param {object} options - * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers. - * @oaram {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). - * @poram {number} [options.regularization=0.01] - Regularization parameter af the neural net. - * @poram {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); + result = this.lm_matx(func, t, p_old, y_old, dX2, J, p, y_dat, weight_sq, dp, c); + JtWJ = result.JtWJ,JtWdy=result.JtWdy,X2=result.Chi_sq,y_hat=result.y_hat,J=result.J; + // decrease lambda ==> Gauss-Newton method - for (var i = 0; i < this.model.length - 1; ++i) { - this.model[i] = Layer.load(options.layers[i]); + switch (Update_Type) { + case 1: // Levenberg + lambda = Math.max(lambda / lambda_DN_fac, 1.e-7); + break; + case 2: // Quadratic + lambda = Math.max(lambda / (1 + alpha), 1.e-7); + break; + case 3: // Nielsen + lambda = math.multiply(Math.max(1 / 3, 1 - (2 * rho - 1) ^ 3),lambda); + nu = 2; + break; + } } - this.model[this.model.length - 1] = OutputLayer.load(options.layers[this.model.length - 1]); - } else { - // default constructor - this.hiddenLayers = options.hiddenLayers === undefined ? [10] : options.hiddenLayers; - this.iterations = options.iterations === undefined ? 50 : options.iterations; - - this.learningRate = options.learningRate === undefined ? 0.01 : options.learningRate; - //this.momentum = options.momentum === undefined ? 0.1 : options.momentum; - this.regularization = options.regularization === undefined ? 0.01 : options.regularization; + else { // it IS NOT better + X2 = X2_old; // do not accept p_try + if (iteration%(2 * Npar)==0) { // rank-1 update of Jacobian + result = this.lm_matx(func, t, p_old, y_old, -1, J, p, y_dat, weight_sq, dp, c); + JtWJ = result.JtWJ,JtWdy=result.JtWdy,dX2=result.Chi_sq,y_hat=result.y_hat,J=result.J; + } - this.activation = options.activation === undefined ? 'tanh' : options.activation; - this.activationParam = options.activationParam === undefined ? 1 : options.activationParam; - if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) { - this.activation = 'tanh'; + // increase lambda ==> gradient descent method + switch (Update_Type) { + case 1: // Levenberg + lambda = Math.min(lambda * lambda_UP_fac, 1.e7); + break; + case 2: // Quadratic + lambda = lambda + Math.abs((X2_try - X2) / 2 / alpha); + break; + case 3: // Nielsen + lambda = lambda * nu; + nu = 2 * nu; + break; + } } - } - } - - /** - * 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 - }); - } + }// --- End of Main Loop - // 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 + // --- convergence achieved, find covariance and confidence intervals + + // equal weights for paramter error analysis + weight_sq = math.multiply(math.multiply(math.transpose(delta_y),delta_y), Matrix.ones(Npnt,1)); + + weight_sq.apply(function(i,j){ + weight_sq[i][j] = (Npnt-Nfit+1)/weight_sq[i][j]; }); - } + //console.log(weight_sq); + result = this.lm_matx(func,t,p_old,y_old,-1,J,p,y_dat,weight_sq,dp,c); + JtWJ = result.JtWJ,JtWdy=result.JtWdy,X2=result.Chi_sq,y_hat=result.y_hat,J=result.J; - /** - * Train the neural net with the given features and labels. - * @param {Matrix|Array} features - * @param {Matrix|Array} labels - */ - train(features, labels) { - features = Matrix.checkMatrix(features); - this.dicts = Utils.dictOutputs(labels); + /*if nargout > 2 // standard error of parameters + covar = inv(JtWJ); + sigma_p = sqrt(diag(covar)); + end - var inputSize = features.columns; - var outputSize = Object.keys(this.dicts.inputs).length; + if nargout > 3 // standard error of the fit + // sigma_y = sqrt(diag(J * covar * J')); // slower version of below + sigma_y = zeros(Npnt,1); + for i=1:Npnt + sigma_y(i) = J(i,:) * covar * J(i,:)'; + end + sigma_y = sqrt(sigma_y); + end - this.buildNetwork(inputSize, outputSize); + if nargout > 4 // parameter correlation matrix + corr = covar ./ [sigma_p*sigma_p']; + end - for (var i = 0; i < this.iterations; ++i) { - var probabilities = this.propagate(features); - this.backpropagation(features, labels, probabilities); - } - } + if nargout > 5 // coefficient of multiple determination + R_sq = corrcoef([y_dat y_hat]); + R_sq = R_sq(1,2).^2; + end - /** - * Propagate the input(training set) and retrives the probabilities of each class. - * @param {Matrix} X - * @return {Matrix} probabilities of each class. - */ - propagate(X) { - var input = X; - for (var i = 0; i < this.model.length; ++i) { - //console.log(i); - input = this.model[i].forward(input); - } + if nargout > 6 // convergence history + cvg_hst = cvg_hst(1:iteration,:); + end*/ - // get probabilities - return input.divColumnVector(Utils.sumRow(input)); - } + // endfunction # ---------------------------------------------------------- LM - /** - * Function that applies the backpropagation algorithm on each layer of the network - * in order to fit the features and labels. - * @param {Matrix} features - * @param {Array} labels - * @param {Matrix} probabilities - probabilities of each class of the feature set. - */ - backpropagation(features, labels, probabilities) { - for (var i = 0; i < probabilities.length; ++i) { - probabilities[i][this.dicts.inputs[labels[i]]] -= 1; - } + return { p:p, X2:X2}; + }, - // 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); - } + lm_FD_J:function(func,t,p,y,dp,c) { + // J = lm_FD_J(func,t,p,y,{dp},{c}) + // + // partial derivatives (Jacobian) dy/dp for use with lm.m + // computed via Finite Differences + // Requires n or 2n function evaluations, n = number of nonzero values of dp + // -------- INPUT VARIABLES --------- + // func = function of independent variables, 't', and parameters, 'p', + // returning the simulated model: y_hat = func(t,p,c) + // t = m-vector of independent variables (used as arg to func) + // p = n-vector of current parameter values + // y = func(t,p,c) n-vector initialised by user before each call to lm_FD_J + // dp = fractional increment of p for numerical derivatives + // dp(j)>0 central differences calculated + // dp(j)<0 one sided differences calculated + // dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed + // Default: 0.001; + // c = optional vector of constants passed to y_hat = func(t,p,c) + //---------- OUTPUT VARIABLES ------- + // J = Jacobian Matrix J(i,j)=dy(i)/dp(j) i=1:n; j=1:m - for (i = 0; i < this.model.length; ++i) { - this.model[i].update(); - } - } + // Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. November 2005 + // modified from: ftp://fly.cnuce.cnr.it/pub/software/octave/leasqr/ + // Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15. - /** - * Predict the output given the feature set. - * @param {Array|Matrix} features - * @return {Array} - */ - predict(features) { - features = Matrix.checkMatrix(features); - var outputs = new Array(features.rows); - var probabilities = this.propagate(features); - for (var i = 0; i < features.rows; ++i) { - outputs[i] = this.dicts.outputs[probabilities.maxRowIndex(i)[1]]; - } + var m = y.length; // number of data points + var n = p.length; // number of parameters - return outputs; - } + dp = dp || math.multiply( Matrix.ones(n, 1), 0.001); - /** - * Export the current model to JSOM. - * @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) - }; + var ps = p.clone();//JSON.parse(JSON.stringify(p)); + //var ps = $.extend(true, [], p); + var J = new Matrix(m,n), del =new Array(n); // initialize Jacobian to Zero - for (var i = 0; i < this.model.length; ++i) { - model.layers[i] = this.model[i].toJSON(); - } + for (var j = 0;j < n; j++) { + //console.log(j+" "+dp[j]+" "+p[j]+" "+ps[j]+" "+del[j]); + del[j] = dp[j]*(1+Math.abs(p[j][0])); // parameter perturbation + p[j] = [ps[j][0]+del[j]]; // perturb parameter p(j) + //console.log(j+" "+dp[j]+" "+p[j]+" "+ps[j]+" "+del[j]); - return model; - } + if (del[j] != 0){ + y1 = func(t, p, c); + //func_calls = func_calls + 1; + if (dp[j][0] < 0) { // backwards difference + //J(:,j) = math.dotDivide(math.subtract(y1, y),del[j]);//. / del[j]; + //console.log(del[j]); + //console.log(y); + var column = math.dotDivide(math.subtract(y1, y),del[j]); + for(var k=0;k< m;k++){ + J[k][j]=column[k][0]; + } + //console.log(column); + } + else{ + p[j][0] = ps[j][0] - del[j]; + //J(:,j) = (y1 - feval(func, t, p, c)). / (2. * del[j]); + var column = math.dotDivide(math.subtract(y1,func(t,p,c)),2*del[j]); + for(var k=0;k< m;k++){ + J[k][j]=column[k][0]; + } + + } // central difference, additional func call + } + + p[j] = ps[j]; // restore p(j) - /** - * 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'); } + //console.log("lm_FD_J: "+ JSON.stringify(J)); + return J; - return new FeedForwardNeuralNetworks(model); - } -} + }, -module.exports = FeedForwardNeuralNetworks; + // endfunction # -------------------------------------------------- LM_FD_J + lm_Broyden_J: function(p_old,y_old,J,p,y){ + // J = lm_Broyden_J(p_old,y_old,J,p,y) + // carry out a rank-1 update to the Jacobian matrix using Broyden's equation + //---------- INPUT VARIABLES ------- + // p_old = previous set of parameters + // y_old = model evaluation at previous set of parameters, y_hat(t;p_old) + // J = current version of the Jacobian matrix + // p = current set of parameters + // y = model evaluation at current set of parameters, y_hat(t;p) + //---------- OUTPUT VARIABLES ------- + // J = rank-1 update to Jacobian Matrix J(i,j)=dy(i)/dp(j) i=1:n; j=1:m + //console.log(p+" X "+ p_old) + var h = math.subtract(p, p_old); + //console.log("hhh "+h); + var h_t = math.transpose(h); + h_t.div(math.multiply(h_t,h)); -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { + //console.log(h_t); + //J = J + ( y - y_old - J*h )*h' / (h'*h); // Broyden rank-1 update eq'n + J = math.add(J, math.multiply(math.subtract(y, math.add(y_old,math.multiply(J,h))),h_t)); + return J; + // endfunction # ---------------------------------------------- LM_Broyden_J + }, -exports.agnes = __webpack_require__(118); -exports.diana = __webpack_require__(119); -//exports.birch = require('./birch'); -//exports.cure = require('./cure'); -//exports.chameleon = require('./chameleon'); + lm_matx : function (func,t,p_old,y_old,dX2,J,p,y_dat,weight_sq,dp,c,iteration){ + // [JtWJ,JtWdy,Chi_sq,y_hat,J] = this.lm_matx(func,t,p_old,y_old,dX2,J,p,y_dat,weight_sq,{da},{c}) + // + // Evaluate the linearized fitting matrix, JtWJ, and vector JtWdy, + // and calculate the Chi-squared error function, Chi_sq + // Used by Levenberg-Marquard algorithm, lm.m + // -------- INPUT VARIABLES --------- + // func = function ofpn independent variables, p, and m parameters, p, + // returning the simulated model: y_hat = func(t,p,c) + // t = m-vectors or matrix of independent variables (used as arg to func) + // p_old = n-vector of previous parameter values + // y_old = m-vector of previous model ... y_old = y_hat(t;p_old); + // dX2 = previous change in Chi-squared criteria + // J = m-by-n Jacobian of model, y_hat, with respect to parameters, p + // p = n-vector of current parameter values + // y_dat = n-vector of data to be fit by func(t,p,c) + // weight_sq = square of the weighting vector for least squares fit ... + // inverse of the standard measurement errors + // dp = fractional increment of 'p' for numerical derivatives + // dp(j)>0 central differences calculated + // dp(j)<0 one sided differences calculated + // dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed + // Default: 0.001; + // c = optional vector of constants passed to y_hat = func(t,p,c) + //---------- OUTPUT VARIABLES ------- + // JtWJ = linearized Hessian matrix (inverse of covariance matrix) + // JtWdy = linearized fitting vector + // Chi_sq = Chi-squared criteria: weighted sum of the squared residuals WSSR + // y_hat = model evaluated with parameters 'p' + // J = m-by-n Jacobian of model, y_hat, with respect to parameters, p + + // Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. November 2005 + // modified from: ftp://fly.cnuce.cnr.it/pub/software/octave/leasqr/ + // Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15. -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { + var Npnt = y_dat.length; // number of data points + var Npar = p.length; // number of parameters -"use strict"; + dp = dp || 0.001; -const utils = __webpack_require__(36); -const init = __webpack_require__(131); -const KMeansResult = __webpack_require__(130); -const squaredDistance = __webpack_require__(1).squared; + //var JtWJ = new Matrix.zeros(Npar); + //var JtWdy = new Matrix.zeros(Npar,1); -const defaultOptions = { - maxIterations: 100, - tolerance: 1e-6, - withIterations: false, - initialization: 'mostDistant', - distanceFunction: squaredDistance -}; + var y_hat = func(t,p,c); // evaluate model using parameters 'p' + //func_calls = func_calls + 1; + //console.log(J); + if ( (iteration%(2*Npar))==0 || dX2 > 0 ) { + //console.log("Par"); + J = this.lm_FD_J(func, t, p, y_hat, dp, c); // finite difference + } + else{ + //console.log("ImPar"); + J = this.lm_Broyden_J(p_old, y_old, J, p, y_hat); // rank-1 update + } + //console.log(y_dat); + //console.log(y_hat); + var delta_y = math.subtract(y_dat, y_hat); // residual error between model and data + //console.log(delta_y[0][0]); + //console.log(delta_y.rows+" "+delta_y.columns+" "+JSON.stringify(weight_sq)); + //var Chi_sq = delta_y' * ( delta_y .* weight_sq ); // Chi-squared error criteria + var Chi_sq = math.multiply(math.transpose(delta_y),math.dotMultiply(delta_y,weight_sq)); + //JtWJ = J' * ( J .* ( weight_sq * ones(1,Npar) ) ); + var Jt = math.transpose(J); -/** - * Each step operation for kmeans - * @ignore - * @param {Array>} centers - the K centers in format [x,y,z,...] - * @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 - * @param {Object} [options] - Option object - * @param {Number} iterations - Current number of iterations - * @return {KMeansResult} - */ -function step(centers, data, clusterID, K, options, iterations) { - clusterID = utils.updateClusterID(data, centers, clusterID, options.distanceFunction); - var newCenters = utils.updateCenters(data, clusterID, K); - var converged = utils.converged(newCenters, centers, options.distanceFunction, options.tolerance); - return new KMeansResult(clusterID, newCenters, converged, iterations, options.distanceFunction); -} + //console.log(weight_sq); -/** - * Generator version for the algorithm - * @ignore - * @param {Array>} centers - the K centers in format [x,y,z,...] - * @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 - * @param {Object} [options] - Option object - */ -function* kmeansGenerator(centers, data, clusterID, K, options) { - var converged = false; - var stepNumber = 0; - var stepResult; - while (!converged && (stepNumber < options.maxIterations)) { - stepResult = step(centers, data, clusterID, K, options, ++stepNumber); - yield stepResult.computeInformation(data); - converged = stepResult.converged; - centers = stepResult.centroids; - } -} + var JtWJ = math.multiply(Jt, math.dotMultiply(J,math.multiply(weight_sq, Matrix.ones(1,Npar)))); -/** - * 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 {String|Array>} [options.initialization = 'moreDistant'] - K centers in format [x,y,z,...] or a method for initialize the data: - * * `'random'` will choose K random different values. - * * `'mostDistant'` will choose the more distant points to a first random pick - * @returns {KMeansResult} - Cluster identifier for each data dot and centroids with the following fields: - * * `'clusters'`: Array of indexes for the clusters. - * * `'centroids'`: Array with the resulting centroids. - * * `'iterations'`: Number of iterations that took to converge - */ -function kmeans(data, K, options) { - options = Object.assign({}, defaultOptions, options); + //JtWdy = J' * ( weight_sq .* delta_y ); + var JtWdy = math.multiply(Jt, math.dotMultiply(weight_sq,delta_y)); - if (K <= 0 || K > data.length || !Number.isInteger(K)) { - throw new Error('K should be a positive integer bigger than the number of points'); - } - 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 'random': - centers = init.random(data, K); - break; - case 'mostDistant': - centers = init.mostDistant(data, K, utils.calculateDistanceMatrix(data, options.distanceFunction)); - break; - default: - throw new Error('Unknown initialization method: "' + options.initialization + '"'); - } + return {JtWJ:JtWJ,JtWdy:JtWdy,Chi_sq:Chi_sq,y_hat:y_hat,J:J}; + // endfunction # ------------------------------------------------------ LM_MATX } - // infinite loop until convergence - if (options.maxIterations === 0) { - options.maxIterations = Number.MAX_VALUE; - } - var clusterID = new Array(data.length); - if (options.withIterations) { - return kmeansGenerator(centers, data, clusterID, K, options); - } else { - var converged = false; - var stepNumber = 0; - var stepResult; - while (!converged && (stepNumber < options.maxIterations)) { - stepResult = step(centers, data, clusterID, K, options, ++stepNumber); - converged = stepResult.converged; - centers = stepResult.centroids; - } - return stepResult.computeInformation(data); - } -} -module.exports = kmeans; +}; +module.exports = LM; /***/ }), -/* 49 */ +/* 107 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = __webpack_require__(133); +module.exports = __webpack_require__(106); +module.exports.Matrix = __webpack_require__(0); +module.exports.Matrix.algebra = __webpack_require__(45); + /***/ }), -/* 50 */ +/* 108 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = exports = __webpack_require__(39).NaiveBayes; -exports.separateClasses = __webpack_require__(39).separateClasses; +exports.additiveSymmetric = __webpack_require__(109); +exports.avg = __webpack_require__(110); +exports.bhattacharyya = __webpack_require__(111); +exports.canberra = __webpack_require__(112); +exports.chebyshev = __webpack_require__(113); +exports.clark = __webpack_require__(114); +exports.czekanowski = __webpack_require__(115); +exports.dice = __webpack_require__(46); +exports.divergence = __webpack_require__(116); +exports.euclidean = __webpack_require__(1); +exports.fidelity = __webpack_require__(117); +exports.gower = __webpack_require__(118); +exports.harmonicMean = __webpack_require__(119); +exports.hellinger = __webpack_require__(120); +exports.innerProduct = __webpack_require__(121); +exports.intersection = __webpack_require__(47); +exports.jaccard = __webpack_require__(48); +exports.jeffreys = __webpack_require__(122); +exports.jensenDifference = __webpack_require__(123); +exports.jensenShannon = __webpack_require__(124); +exports.kdivergence = __webpack_require__(125); +exports.kulczynski = __webpack_require__(49); +exports.kullbackLeibler = __webpack_require__(126); +exports.kumarHassebrook = __webpack_require__(127); +exports.kumarJohnson = __webpack_require__(128); +exports.lorentzian = __webpack_require__(129); +exports.manhattan = __webpack_require__(130); +exports.matusita = __webpack_require__(131); +exports.minkowski = __webpack_require__(132); +exports.motyka = __webpack_require__(50); +exports.neyman = __webpack_require__(133); +exports.pearson = __webpack_require__(134); +exports.probabilisticSymmetric = __webpack_require__(135); +exports.ruzicka = __webpack_require__(136); +exports.soergel = __webpack_require__(137); +exports.sorensen = __webpack_require__(138); +exports.squared = __webpack_require__(139); +exports.squaredChord = __webpack_require__(51); +exports.squaredEuclidean = __webpack_require__(1).squared; +exports.taneja = __webpack_require__(140); +exports.tanimoto = __webpack_require__(141); +exports.topsoe = __webpack_require__(142); +exports.tree = __webpack_require__(249); +exports.waveHedges = __webpack_require__(143); /***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +/* 109 */ +/***/ (function(module, exports) { +module.exports = function additiveSymmetric(a, b) { + var i = 0, + ii = a.length, + d = 0; + for (; i < ii; i++) { + d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]); + } + return 2 * d; +}; -var LM = __webpack_require__(17); -var math = LM.Matrix.algebra; -var Matrix = __webpack_require__(0); -/** - * 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 - * @param c Constant parameters(Not used) - * @returns {*} - */ -function sumOfLorentzians(t,p,c){ - var nL = p.length/3,factor,i, j,p2, cols = t.rows; - var result = Matrix.zeros(t.length,1); +/***/ }), +/* 110 */ +/***/ (function(module, exports) { - for(i=0;imaxY) - maxY = y[i]; - } - } - else{ - //It is a colum matrix - if(typeof x[0] === "object"){ - for(i=0;imaxY) - maxY = y[i][0]; - } - } +module.exports = function sorensen(a, b) { + var ii = a.length, + up = 0, + down = 0; + for (var i = 0; i < ii ; i++) { + up += Math.abs(a[i] - b[i]); + down += a[i] + b[i]; + } + return up / down; +}; - } - //} - } - else{ - //Looks like a column wise matrix [[x],[y]] - var nbPoints = nbSeries; - //if(nbPoints<3) - // throw new SizeException(nbPoints); - //else { - t = new Array(nbPoints);//new Matrix(nbPoints, 1); - y_data = new Array(nbPoints);//new Matrix(nbPoints, 1); - for (i = 0; i < nbPoints; i++) { - t[i] = xy[i][0]; - y_data[i] = xy[i][1]; - if(y_data[i]>maxY) - maxY = y_data[i]; - } - //} - } - for (i = 0; i < nbPoints; i++) { - y_data[i]/=maxY; - } - if(threshold){ - for (i = nbPoints-1; i >=0; i--) { - if(y_data[i]0) - return [(new Matrix([t])).transpose(),(new Matrix([y_data])).transpose(),maxY]; - return null; -} + return d; +}; -function sizeException(nbPoints) { - return new RangeError("Not enough points to perform the optimization: "+nbPoints +"< 3"); -} -module.exports.optimizeSingleLorentzian = optimizeSingleLorentzian; -module.exports.optimizeLorentzianSum = optimizeLorentzianSum; -module.exports.optimizeSingleGaussian = optimizeSingleGaussian; -module.exports.optimizeGaussianSum = optimizeGaussianSum; -module.exports.singleGaussian = singleGaussian; -module.exports.singleLorentzian = singleLorentzian; -module.exports.optimizeGaussianTrain = optimizeGaussianTrain; -module.exports.optimizeLorentzianTrain = optimizeLorentzianTrain; +/***/ }), +/* 140 */ +/***/ (function(module, exports) { + +module.exports = function taneja(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii ; i++) { + ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i]))); + } + return ans; +}; + /***/ }), -/* 52 */ +/* 141 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var tanimotoS = __webpack_require__(54); +module.exports = function tanimoto(a, b, bitvector) { + if (bitvector) + return 1 - tanimotoS(a, b, bitvector); + else { + var ii = a.length, + p = 0, + q = 0, + m = 0; + for (var i = 0; i < ii ; i++) { + p += a[i]; + q += b[i]; + m += Math.min(a[i],b[i]); + } + return (p + q - 2 * m) / (p + q - m); + } +}; -const Matrix = __webpack_require__(0); -const EVD = Matrix.DC.EVD; -const SVD = Matrix.DC.SVD; -const Stat = __webpack_require__(2).matrix; -const mean = Stat.mean; -const stdev = Stat.standardDeviation; -const defaultOptions = { - isCovarianceMatrix: false, - center: true, - scale: false -}; +/***/ }), +/* 142 */ +/***/ (function(module, exports) { -/** - * Creates new PCA (Principal Component Analysis) from the dataset - * @param {Matrix} dataset - dataset or covariance matrix - * @param {Object} options - * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix - * @param {boolean} [options.center=true] - should the data be centered (subtract the mean) - * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation) - * */ -class PCA { - constructor(dataset, options) { - if (dataset === true) { - const model = options; - this.center = model.center; - this.scale = model.scale; - this.means = model.means; - this.stdevs = model.stdevs; - this.U = Matrix.checkMatrix(model.U); - this.S = model.S; - return; - } +module.exports = function topsoe(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii ; i++) { + ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i])); + } + return ans; +}; - options = Object.assign({}, defaultOptions, options); - this.center = false; - this.scale = false; - this.means = null; - this.stdevs = null; +/***/ }), +/* 143 */ +/***/ (function(module, exports) { - if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset - this._computeFromCovarianceMatrix(dataset); - return; - } +module.exports = function waveHedges(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii ; i++) { + ans += 1 - (Math.min(a[i], b[i]) / Math.max(a[i], b[i])); + } + return ans; +}; - var useCovarianceMatrix; - if (typeof options.useCovarianceMatrix === 'boolean') { - useCovarianceMatrix = options.useCovarianceMatrix; - } else { - useCovarianceMatrix = dataset.length > dataset[0].length; - } - if (useCovarianceMatrix) { // user provided a dataset but wants us to compute and use the covariance matrix - dataset = this._adjust(dataset, options); - const covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1); - this._computeFromCovarianceMatrix(covarianceMatrix); - } else { - dataset = this._adjust(dataset, options); - var svd = new SVD(dataset, { - computeLeftSingularVectors: false, - computeRightSingularVectors: true, - autoTranspose: true - }); +/***/ }), +/* 144 */ +/***/ (function(module, exports, __webpack_require__) { - this.U = svd.rightSingularVectors; +"use strict"; - const singularValues = svd.diagonal; - const eigenvalues = new Array(singularValues.length); - for (var i = 0; i < singularValues.length; i++) { - eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1); - } - this.S = eigenvalues; - } - } - /** - * Load a PCA model from JSON - * @param {Object} model - * @return {PCA} - */ - static load(model) { - if (model.name !== 'PCA') - throw new RangeError('Invalid model: ' + model.name); - return new PCA(true, model); - } +exports.cosine = __webpack_require__(52); +exports.czekanowski = __webpack_require__(53); +exports.dice = __webpack_require__(145); +exports.intersection = __webpack_require__(146); +exports.jaccard = __webpack_require__(147); +exports.kulczynski = __webpack_require__(148); +exports.motyka = __webpack_require__(149); +exports.pearson = __webpack_require__(150); +exports.squaredChord = __webpack_require__(151); +exports.tanimoto = __webpack_require__(54); - /** - * Project the dataset into the PCA space - * @param {Matrix} dataset - * @return {Matrix} dataset projected in the PCA space - */ - predict(dataset) { - dataset = new Matrix(dataset); - if (this.center) { - dataset.subRowVector(this.means); - if (this.scale) { - dataset.divRowVector(this.stdevs); - } - } +/***/ }), +/* 145 */ +/***/ (function(module, exports, __webpack_require__) { - return dataset.mmul(this.U); - } +var diceD = __webpack_require__(46); - /** - * Returns the proportion of variance for each component - * @return {[number]} - */ - getExplainedVariance() { - var sum = 0; - for (var i = 0; i < this.S.length; i++) { - sum += this.S[i]; - } - return this.S.map(value => value / sum); - } +module.exports = function dice(a, b) { + return 1 - diceD(a,b); +}; - /** - * Returns the cumulative proportion of variance - * @return {[number]} - */ - getCumulativeVariance() { - var explained = this.getExplainedVariance(); - for (var i = 1; i < explained.length; i++) { - explained[i] += explained[i - 1]; - } - return explained; - } - /** - * Returns the Eigenvectors of the covariance matrix - * @returns {Matrix} - */ - getEigenvectors() { - return this.U; - } +/***/ }), +/* 146 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Returns the Eigenvalues (on the diagonal) - * @returns {[number]} - */ - getEigenvalues() { - return this.S; - } +var intersectionD = __webpack_require__(47); - /** - * Returns the standard deviations of the principal components - * @returns {[number]} - */ - getStandardDeviations() { - return this.S.map(x => Math.sqrt(x)); - } +module.exports = function intersection(a, b) { + return 1 - intersectionD(a,b); +}; - /** - * Returns the loadings matrix - * @return {Matrix} - */ - getLoadings() { - return this.U.transpose(); - } - /** - * Export the current model to a JSON object - * @return {Object} model - */ - toJSON() { - return { - name: 'PCA', - center: this.center, - scale: this.scale, - means: this.means, - stdevs: this.stdevs, - U: this.U, - S: this.S, - }; - } +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { - _adjust(dataset, options) { - this.center = !!options.center; - this.scale = !!options.scale; +var jaccardD = __webpack_require__(48); - dataset = new Matrix(dataset); +module.exports = function jaccard(a, b) { + return 1 - jaccardD(a, b); +}; - if (this.center) { - const means = mean(dataset); - const stdevs = this.scale ? stdev(dataset, means, true) : null; - this.means = means; - dataset.subRowVector(means); - if (this.scale) { - for (var i = 0; i < stdevs.length; i++) { - if (stdevs[i] === 0) { - throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i); - } - } - this.stdevs = stdevs; - dataset.divRowVector(stdevs); - } - } - return dataset; - } +/***/ }), +/* 148 */ +/***/ (function(module, exports, __webpack_require__) { - _computeFromCovarianceMatrix(dataset) { - const evd = new EVD(dataset, {assumeSymmetric: true}); - this.U = evd.eigenvectorMatrix; - for (var i = 0; i < this.U.length; i++) { - this.U[i].reverse(); - } - this.S = evd.realEigenvalues.reverse(); - } -} +var kulczynskiD = __webpack_require__(49); -module.exports = PCA; +module.exports = function kulczynski(a, b) { + return 1 / kulczynskiD(a, b); +}; /***/ }), -/* 53 */ +/* 149 */ +/***/ (function(module, exports, __webpack_require__) { + +var motykaD = __webpack_require__(50); + +module.exports = function motyka(a, b) { + return 1 - motykaD(a,b); +}; + + +/***/ }), +/* 150 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const measures = __webpack_require__(148); +var stat=__webpack_require__(2).array; +var cosine=__webpack_require__(52); -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'); - } - const rows = prediction.length; - const columns = prediction[0].length; - const isDistance = !options.max; +module.exports = function pearson(a, b) { + var avgA=stat.mean(a); + var avgB=stat.mean(b); - const predP = []; + var newA=new Array(a.length); + var newB=new Array(b.length); + for (var i=0; i a.pred - b.pred); - } else { - predP.sort((a, b) => b.pred - a.pred); - } - - 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; +/***/ }), +/* 151 */ +/***/ (function(module, exports, __webpack_require__) { - var currentPred = predP[0].pred; - var nTp = 0; - var nFp = 0; - for (var i = 0; i < predP.length; i++) { - if (predP[i].pred !== currentPred) { - cutoffs.push(currentPred); - fp.push(nFp); - tp.push(nTp); - currentPred = predP[i].pred; - } - if (predP[i].targ) { - nPos++; - nTp++; - } else { - nNeg++; - nFp++; - } - } - cutoffs.push(currentPred); - fp.push(nFp); - tp.push(nTp); +var squaredChordD = __webpack_require__(51); + +module.exports = function squaredChord(a, b) { + return 1 - squaredChordD(a, b); +}; - 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]; +/***/ }), +/* 152 */ +/***/ (function(module, exports, __webpack_require__) { - nPosPred[i] = tp[i] + fp[i]; - nNegPred[i] = tn[i] + fn[i]; - } +"use strict"; - 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] - */ - getMeasure(measure) { - if (typeof measure !== 'string') { - throw new Error('No measure specified'); - } - if (!measures[measure]) { - throw new Error(`The specified measure (${measure}) does not exist`); - } - return measures[measure](this); - } +var Layer = __webpack_require__(55); - /** - * Returns the area under the ROC curve - */ - getAURC() { - const l = this.cutoffs.length; - const x = new Array(l); - const y = new Array(l); - for (var i = 0; i < l; i++) { - x[i] = this.fp[i] / this.nNeg; - y[i] = this.tp[i] / this.nPos; - } - var auc = 0; - for (i = 1; i < l; i++) { - auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]); - } - return auc; +class OutputLayer extends Layer { + constructor(options) { + super(options); + + this.activationFunction = function (i, j) { + this[i][j] = Math.exp(this[i][j]); + }; } - /** - * Returns the area under the DET curve - */ - getAUDC() { - const l = this.cutoffs.length; - const x = new Array(l); - const y = new Array(l); - for (var i = 0; i < l; i++) { - x[i] = this.fn[i] / this.nPos; - y[i] = this.fp[i] / this.nNeg; - } - var auc = 0; - for (i = 1; i < l; i++) { - auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]); + static load(model) { + if (model.model !== 'Layer') { + throw new RangeError('the current model is not a Layer model'); } - return auc; + + return new OutputLayer(model); } +} - 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 +module.exports = OutputLayer; - 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; +/***/ }), +/* 153 */ +/***/ (function(module, exports, __webpack_require__) { - for (var i = cutLow, j = (cutLength - 1); i <= cutHigh; i += interval) { - while (this.cutoffs[j] < i) - j--; +const binarySearch = __webpack_require__(39); +const sortAsc = __webpack_require__(44).asc; - xLabels.push(i); +const largestPrime = 0x7fffffff; - var thisTP = nTP - currentTP - this.tp[j]; - var thisFP = nFP - currentFP - this.fp[j]; +const primeNumbers = [ + //chunk #0 + largestPrime, // 2^31-1 - currentTP += thisTP; - currentFP += thisFP; + //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, - interValues.push(thisFP); - intraValues.push(thisTP); + //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, - interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100); - intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100); - } + //chunk #3 + 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341, + 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963, + 2004663929, - return { - xLabels: xLabels, - interValues: interValues, - intraValues: intraValues, - interCumPercent: interCumPercent, - intraCumPercent: intraCumPercent - }; - } -} + //chunk #4 + 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963, + 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463, -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' -}; + //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, -module.exports = Performance; + //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, -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { + //chunk #9 + 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337, + 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741, + 759155483, 1518310967, + + //chunk #10 + 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611, + 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929, + 1600153859, + + //chunk #11 + 13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683, + 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407, + 276172823, 552345671, 1104691373, + + //chunk #12 + 19, 41, 83, 167, 337, 677, + 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, + 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, + 359339171, 718678369, 1437356741, + + //chunk #13 + 53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269, + 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781, + 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943 +]; + +primeNumbers.sort(sortAsc); + +function nextPrime(value) { + let index = binarySearch(primeNumbers, value, sortAsc); + if (index < 0) { + index = ~index; + } + return primeNumbers[index]; +} -module.exports = exports = __webpack_require__(150); -exports.Utils = __webpack_require__(12); -exports.OPLS = __webpack_require__(149); +exports.nextPrime = nextPrime; +exports.largestPrime = largestPrime; /***/ }), -/* 55 */ +/* 154 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -exports.SimpleLinearRegression = exports.SLR = __webpack_require__(13); -exports.NonLinearRegression = exports.NLR = { - PolynomialRegression: __webpack_require__(40), - PotentialRegression: __webpack_require__(154), - ExpRegression: __webpack_require__(151), - PowerRegression: __webpack_require__(155) -}; -exports.KernelRidgeRegression = exports.KRR = __webpack_require__(152); -//exports.MultipleLinearRegression = exports.MLR = require('./regression/multiple-linear-regression'); -//exports.MultivariateLinearRegression = exports.MVLR = require('./regression/multivariate-linear-regression'); -exports.PolinomialFitting2D = __webpack_require__(153); -exports.TheilSenRegression = __webpack_require__(156); +const euclidean = __webpack_require__(1); +const ClusterLeaf = __webpack_require__(58); +const Cluster = __webpack_require__(22); +const distanceMatrix = __webpack_require__(40); + +/** + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {number} + */ +function simpleLink(cluster1, cluster2, disFun) { + var m = 10e100; + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + var d = disFun[cluster1[i]][ cluster2[j]]; + m = Math.min(d, m); + } + } + return m; +} + +/** + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {number} + */ +function completeLink(cluster1, cluster2, disFun) { + var m = -1; + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + var d = disFun[cluster1[i]][ cluster2[j]]; + m = Math.max(d, m); + } + } + return m; +} + +/** + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {number} + */ +function averageLink(cluster1, cluster2, disFun) { + var m = 0; + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + m += disFun[cluster1[i]][ cluster2[j]]; + } + } + return m / (cluster1.length * cluster2.length); +} + +/** + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {*} + */ +function centroidLink(cluster1, cluster2, disFun) { + var dist = new Array(cluster1.length * cluster2.length); + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + dist[i * cluster2.length + j] = (disFun[cluster1[i]][ cluster2[j]]); + } + } + return median(dist); +} +/** + * @private + * @param cluster1 + * @param cluster2 + * @param disFun + * @returns {number} + */ +function wardLink(cluster1, cluster2, disFun) { + return centroidLink(cluster1, cluster2, disFun) + * cluster1.length * cluster2.length / (cluster1.length + cluster2.length); +} -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { +function compareNumbers(a, b) { + return a - b; +} -//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007 -var extend = __webpack_require__(9); -var stat = __webpack_require__(157); +function median(values, alreadySorted) { + if (alreadySorted === undefined) alreadySorted = false; + if (!alreadySorted) { + values = [].concat(values).sort(compareNumbers); + } + var l = values.length; + var half = Math.floor(l / 2); + if (l % 2 === 0) { + return (values[half - 1] + values[half]) * 0.5; + } else { + return values[half]; + } +} var defaultOptions = { - windowSize: 9, - derivative: 0, - polynomial: 3, -}; - - -function SavitzkyGolay(data, h, options) { - options = extend({}, defaultOptions, options); - - if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize))) - throw new RangeError('Invalid window size (should be odd and at least 5 integer number)') + disFunc: euclidean, + kind: 'single', + isDistanceMatrix: false +}; - if (options.windowSize>data.length) - throw new RangeError('Window size is higher than the data length '+options.windowSize+">"+data.length); - if ((options.derivative < 0) || !(Number.isInteger(options.derivative))) - throw new RangeError('Derivative should be a positive integer'); - if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial))) - throw new RangeError('Polynomial should be a positive integer'); - if (options.polynomial >= 6) - console.warn('You should not use polynomial grade higher than 5 if you are' + - ' not sure that your data arises from such a model. Possible polynomial oscillation problems'); +/** + * Continuously merge nodes that have the least dissimilarity + * @param {Array >} distance - Array of points to be clustered + * @param {json} options + * @option isDistanceMatrix: Is the input a distance matrix? + * @constructor + */ +function agnes(data, options) { + options = Object.assign({}, defaultOptions, options); + var len = data.length; + var distance = data;//If source + if (!options.isDistanceMatrix) { + distance = distanceMatrix(data, options.disFunc); + } - var windowSize = options.windowSize; - var half = Math.floor(windowSize/2); - var np = data.length; - var ans = new Array(np); - var weights = fullWeights(windowSize,options.polynomial,options.derivative); - var hs = 0; - var constantH = true; - if( Object.prototype.toString.call( h ) === '[object Array]' ) { - constantH = false; - } - else{ - hs = Math.pow(h, options.derivative); - } - //console.log("Constant h: "+constantH); - //For the borders - for(var i=0;i=0 && i < h.length-1){ - hs+= (h[i+1]-h[i]); - count++; - } + var list = new Array(len); + for (var i = 0; i < distance.length; i++) { + list[i] = new ClusterLeaf(i); } - return Math.pow(hs/count,derivative); -} + var min = 10e5, + d = {}, + dis = 0; -function GramPoly(i,m,k,s){ - var Grampoly = 0; - if(k>0){ - Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) + - s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s); - } - else{ - if(k==0&&s==0){ - Grampoly=1; + while (list.length > 1) { + // calculates the minimum distance + d = {}; + min = 10e5; + for (var j = 0; j < list.length; j++) { + for (var k = j + 1; k < list.length; k++) { + var fdistance, sdistance; + if (list[j] instanceof ClusterLeaf) { + fdistance = [list[j].index]; + } else { + fdistance = new Array(list[j].index.length); + for (var e = 0; e < fdistance.length; e++) { + fdistance[e] = list[j].index[e].index; + } + } + if (list[k] instanceof ClusterLeaf) { + sdistance = [list[k].index]; + } else { + sdistance = new Array(list[k].index.length); + for (var f = 0; f < sdistance.length; f++) { + sdistance[f] = list[k].index[f].index; + } + } + dis = options.kind(fdistance, sdistance, distance).toFixed(4); + if (dis in d) { + d[dis].push([list[j], list[k]]); + } else { + d[dis] = [[list[j], list[k]]]; + } + min = Math.min(dis, min); + } } - else{ - Grampoly=0; + // cluster dots + var dmin = d[min.toFixed(4)]; + var clustered = new Array(dmin.length); + var aux, + count = 0; + while (dmin.length > 0) { + aux = dmin.shift(); + for (var q = 0; q < dmin.length; q++) { + var int = dmin[q].filter(function (n) { + //noinspection JSReferencingMutableVariableFromClosure + return aux.indexOf(n) !== -1; + }); + if (int.length > 0) { + var diff = dmin[q].filter(function (n) { + //noinspection JSReferencingMutableVariableFromClosure + return aux.indexOf(n) === -1; + }); + aux = aux.concat(diff); + dmin.splice(q--, 1); + } + } + clustered[count++] = aux; + } + clustered.length = count; + + for (var ii = 0; ii < clustered.length; ii++) { + var obj = new Cluster(); + obj.children = clustered[ii].concat(); + obj.distance = min; + obj.index = new Array(len); + var indCount = 0; + for (var jj = 0; jj < clustered[ii].length; jj++) { + if (clustered[ii][jj] instanceof ClusterLeaf) { + obj.index[indCount++] = clustered[ii][jj]; + } else { + indCount += clustered[ii][jj].index.length; + obj.index = clustered[ii][jj].index.concat(obj.index); + } + list.splice((list.indexOf(clustered[ii][jj])), 1); + } + obj.index.length = indCount; + list.push(obj); } } - //console.log(Grampoly); - return Grampoly; + return list[0]; } -function GenFact(a,b){ - var gf=1; - if(a>=b){ - for(var j=a-b+1;j<=a;j++){ - gf*=j; +module.exports = agnes; + + +/***/ }), +/* 155 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const euclidean = __webpack_require__(1); +const ClusterLeaf = __webpack_require__(58); +const Cluster = __webpack_require__(22); + +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ +function simpleLink(cluster1, cluster2, disFun) { + var m = 10e100; + for (var i = 0; i < cluster1.length; i++) { + for (var j = i; j < cluster2.length; j++) { + var d = disFun(cluster1[i], cluster2[j]); + m = Math.min(d, m); } } - return gf; + return m; } -function Weight(i,t,m,n,s){ - var sum=0; - for(var k=0;k<=n;k++){ - //console.log(k); - sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s) +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ +function completeLink(cluster1, cluster2, disFun) { + var m = -1; + for (var i = 0; i < cluster1.length; i++) { + for (var j = i; j < cluster2.length; j++) { + var d = disFun(cluster1[i], cluster2[j]); + m = Math.max(d, m); + } } - return sum; + return m; } /** - * - * @param m Number of points - * @param n Polynomial grade - * @param s Derivative + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} */ -function fullWeights(m,n,s){ - var weights = new Array(m); - var np = Math.floor(m/2); - for(var t=-np;t<=np;t++){ - weights[t+np] = new Array(m); - for(var j=-np;j<=np;j++){ - weights[t+np][j+np]=Weight(j,t,np,n,s); +function averageLink(cluster1, cluster2, disFun) { + var m = 0; + for (var i = 0; i < cluster1.length; i++) { + for (var j = 0; j < cluster2.length; j++) { + m += disFun(cluster1[i], cluster2[j]); } } - return weights; + return m / (cluster1.length * cluster2.length); } -/*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>} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ +function centroidLink(cluster1, cluster2, disFun) { + var x1 = 0, + y1 = 0, + x2 = 0, + y2 = 0; + for (var i = 0; i < cluster1.length; i++) { + x1 += cluster1[i][0]; + y1 += cluster1[i][1]; } - - 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; - + for (var j = 0; j < cluster2.length; j++) { + x2 += cluster2[j][0]; + y2 += cluster2[j][1]; + } + x1 /= cluster1.length; + y1 /= cluster1.length; + x2 /= cluster2.length; + y2 /= cluster2.length; + return disFun([x1, y1], [x2, y2]); } - - -function guessWindowSize(data, h){ - console.log("entropy "+entropy(data,h,trendOptions)); - return 5; +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ +function wardLink(cluster1, cluster2, disFun) { + var x1 = 0, + y1 = 0, + x2 = 0, + y2 = 0; + for (var i = 0; i < cluster1.length; i++) { + x1 += cluster1[i][0]; + y1 += cluster1[i][1]; + } + for (var j = 0; j < cluster2.length; j++) { + x2 += cluster2[j][0]; + y2 += cluster2[j][1]; + } + x1 /= cluster1.length; + y1 /= cluster1.length; + x2 /= cluster2.length; + y2 /= cluster2.length; + return disFun([x1, y1], [x2, y2]) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length); } -*/ -module.exports = SavitzkyGolay; - - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var Matrix = __webpack_require__(0); -var padArray = __webpack_require__(20); -var extend = __webpack_require__(9); - -var defaultOptions = { - windowSize: 5, - derivative: 1, - polynomial: 2, - pad: 'none', - padValue: 'replicate' -}; /** - * Savitzky-Golay filter - * @param {Array } data - * @param {number} h - * @param {Object} options - * @returns {Array} + * @private + * Returns the most distant point and his distance + * @param {Array >} splitting - Clusters to split + * @param {Array >} data - Original data + * @param {function} disFun - Distance function + * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant */ -function SavitzkyGolay (data, h, options) { - options = extend({}, defaultOptions, options); - if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize))) - throw new RangeError('Invalid window size (should be odd and at least 5 integer number)'); - if ((options.derivative < 0) || !(Number.isInteger(options.derivative))) - throw new RangeError('Derivative should be a positive integer'); - if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial))) - throw new RangeError('Polynomial should be a positive integer'); - - var C, norm; - var step = Math.floor(options.windowSize / 2); +function diff(splitting, data, disFun) { + var ans = { + d: 0, + p: 0 + }; - if (options.pad === 'pre') { - data = padArray(data, {size: step, value: options.padValue}); + var Ci = new Array(splitting[0].length); + for (var e = 0; e < splitting[0].length; e++) { + Ci[e] = data[splitting[0][e]]; + } + var Cj = new Array(splitting[1].length); + for (var f = 0; f < splitting[1].length; f++) { + Cj[f] = data[splitting[1][f]]; } - var ans = new Array(data.length - 2*step); - - if ((options.windowSize === 5) && (options.polynomial === 2) && ((options.derivative === 1) || (options.derivative === 2))) { - if (options.derivative === 1) { - C = [-2,-1,0,1,2]; - norm = 10; + var dist, ndist; + for (var i = 0; i < Ci.length; i++) { + dist = 0; + for (var j = 0; j < Ci.length; j++) { + if (i !== j) { + dist += disFun(Ci[i], Ci[j]); + } } - else { - C = [2, -1, -2, -1, 2]; - norm = 7; + dist /= (Ci.length - 1); + ndist = 0; + for (var k = 0; k < Cj.length; k++) { + ndist += disFun(Ci[i], Cj[k]); } - } - else { - var J = Matrix.ones(options.windowSize, options.polynomial + 1); - var inic = -(options.windowSize - 1) / 2; - for (var i = 0; i < J.length; i++) { - for (var j = 0; j < J[i].length; j++) { - if ((inic + 1 !== 0) || (j !== 0)) - J[i][j] = Math.pow((inic + i), j); - } + ndist /= Cj.length; + if ((dist - ndist) > ans.d) { + ans.d = (dist - ndist); + ans.p = i; } - var Jtranspose = J.transposeView(); - var Jinv = (Jtranspose.mmul(J)).inverse(); - C = Jinv.mmul(Jtranspose); - C = C[options.derivative]; - norm = 1; - } - var det = norm * Math.pow(h, options.derivative); - for (var k = step; k < (data.length - step); k++) { - var d = 0; - for (var l = 0; l < C.length; l++) - d += C[l] * data[l + k - step] / det; - ans[k - step] = d; - } - - if (options.pad === 'post') { - ans = padArray(ans, {size: step, value: options.padValue}); } - - return ans; -} - -module.exports = SavitzkyGolay; - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var NodeSquare = __webpack_require__(42), - NodeHexagonal = __webpack_require__(159); + return ans; +} var defaultOptions = { - fields: 3, - randomizer: Math.random, - distance: squareEuclidean, - iterations: 10, - learningRate: 0.1, - gridType: 'rect', - torus: true, - method: 'random' + dist: euclidean, + kind: 'single' }; -function SOM(x, y, options, reload) { - - this.x = x; - this.y = y; - - options = options || {}; - this.options = {}; - for (var i in defaultOptions) { - if (options.hasOwnProperty(i)) { - this.options[i] = options[i]; - } else { - this.options[i] = defaultOptions[i]; +/** + * @private + * Intra-cluster distance + * @param {Array} index + * @param {Array} data + * @param {function} disFun + * @returns {number} + */ +function intrDist(index, data, disFun) { + var dist = 0, + count = 0; + for (var i = 0; i < index.length; i++) { + for (var j = i; j < index.length; j++) { + dist += disFun(data[index[i].index], data[index[j].index]); + count++; } } + return dist / count; +} - 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'); +/** + * Splits the higher level clusters + * @param {Array >} data - Array of points to be clustered + * @param {json} options + * @constructor + */ +function diana(data, options) { + options = Object.assign({}, defaultOptions, options); + if (typeof options.kind === 'string') { + switch (options.kind) { + case 'single': + options.kind = simpleLink; + break; + case 'complete': + options.kind = completeLink; + break; + case 'average': + options.kind = averageLink; + break; + case 'centroid': + options.kind = centroidLink; + break; + case 'ward': + options.kind = wardLink; + break; + default: + throw new RangeError('Unknown kind of similarity'); + } + } else if (typeof options.kind !== 'function') { + throw new TypeError('Undefined kind of similarity'); } - - 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) - }; + var tree = new Cluster(); + tree.children = new Array(data.length); + tree.index = new Array(data.length); + for (var ind = 0; ind < data.length; ind++) { + tree.children[ind] = new ClusterLeaf(ind); + tree.index[ind] = new ClusterLeaf(ind); } - this.torus = this.options.torus; - this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance'; - - this.distance = this.options.distance; - - this.maxDistance = getMaxDistance(this.distance, this.numWeights); - - if (reload === true) { // For model loading - this.done = true; - return; - } - if (!(x > 0 && y > 0)) { - throw new Error('x and y must be positive'); + tree.distance = intrDist(tree.index, data, options.dist); + var m, M, clId, + dist, rebel; + var list = [tree]; + while (list.length > 0) { + M = 0; + clId = 0; + for (var i = 0; i < list.length; i++) { + m = 0; + for (var j = 0; j < list[i].length; j++) { + for (var l = (j + 1); l < list[i].length; l++) { + m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m); + } + } + if (m > M) { + M = m; + clId = i; + } + } + M = 0; + if (list[clId].index.length === 2) { + list[clId].children = [list[clId].index[0], list[clId].index[1]]; + list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]); + } else if (list[clId].index.length === 3) { + list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]]; + var d = [ + options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]), + options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index]) + ]; + list[clId].distance = (d[0] + d[1]) / 2; + } else { + var C = new Cluster(); + var sG = new Cluster(); + var splitting = [new Array(list[clId].index.length), []]; + for (var spl = 0; spl < splitting[0].length; spl++) { + splitting[0][spl] = spl; + } + for (var ii = 0; ii < splitting[0].length; ii++) { + dist = 0; + for (var jj = 0; jj < splitting[0].length; jj++) { + if (ii !== jj) { + dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]); + } + } + dist /= (splitting[0].length - 1); + if (dist > M) { + M = dist; + rebel = ii; + } + } + splitting[1] = [rebel]; + splitting[0].splice(rebel, 1); + dist = diff(splitting, data, options.dist); + while (dist.d > 0) { + splitting[1].push(splitting[0][dist.p]); + splitting[0].splice(dist.p, 1); + dist = diff(splitting, data, options.dist); + } + var fData = new Array(splitting[0].length); + C.index = new Array(splitting[0].length); + for (var e = 0; e < fData.length; e++) { + fData[e] = data[list[clId].index[splitting[0][e]].index]; + C.index[e] = list[clId].index[splitting[0][e]]; + C.children[e] = list[clId].index[splitting[0][e]]; + } + var sData = new Array(splitting[1].length); + sG.index = new Array(splitting[1].length); + for (var f = 0; f < sData.length; f++) { + sData[f] = data[list[clId].index[splitting[1][f]].index]; + sG.index[f] = list[clId].index[splitting[1][f]]; + sG.children[f] = list[clId].index[splitting[1][f]]; + } + C.distance = intrDist(C.index, data, options.dist); + sG.distance = intrDist(sG.index, data, options.dist); + list.push(C); + list.push(sG); + list[clId].children = [C, sG]; + } + list.splice(clId, 1); } + return tree; +} - 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; +module.exports = diana; - this.mapRadius = Math.floor(Math.max(x, y) / 2); - this.algorithmMethod = this.options.method; +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { - this._initNodes(); +"use strict"; - this.done = false; -} -SOM.load = function loadModel(model, distance) { - if (model.name === 'SOM') { - var x = model.data.length, - y = model.data[0].length; - if (distance) { - model.options.distance = distance; - } else if (model.options.distance) { - model.options.distance = eval('(' + model.options.distance + ')'); - } - var som = new SOM(x, y, model.options, true); - som.nodes = new Array(x); - for (var i = 0; i < x; i++) { - som.nodes[i] = new Array(y); - for (var j = 0; j < y; j++) { - som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som); - } - } - return som; - } else { - throw new Error('expecting a SOM model'); - } -}; +const squaredEuclidean = __webpack_require__(1).squared; -SOM.prototype.export = function exportModel(includeDistance) { - if (!this.done) { - throw new Error('model is not ready yet'); - } - var model = { - name: 'SOM' - }; - model.options = { - fields: this.options.fields, - gridType: this.options.gridType, - torus: this.options.torus - }; - model.data = new Array(this.x); - for (var i = 0; i < this.x; i++) { - model.data[i] = new Array(this.y); - for (var j = 0; j < this.y; j++) { - model.data[i][j] = this.nodes[i][j].weights; - } - } - if (includeDistance) { - model.options.distance = this.distance.toString(); - } - return model; +const defaultOptions = { + sigma: 1 }; -SOM.prototype._initNodes = function initNodes() { - var now = Date.now(), - i, j, k; - this.nodes = new Array(this.x); - for (i = 0; i < this.x; i++) { - this.nodes[i] = new Array(this.y); - for (j = 0; j < this.y; j++) { - var weights = new Array(this.numWeights); - for (k = 0; k < this.numWeights; k++) { - weights[k] = this.randomizer(); - } - this.nodes[i][j] = new this.nodeType(i, j, weights, this); - } +class GaussianKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + this.divisor = 2 * options.sigma * options.sigma; } - this.times.initNodes = Date.now() - now; -}; -SOM.prototype.setTraining = function setTraining(trainingSet) { - if (this.trainingSet) { - throw new Error('training set has already been set'); - } - var now = Date.now(); - var convertedSet = trainingSet; - var i, l = trainingSet.length; - if (this.extractor) { - convertedSet = new Array(l); - for (i = 0; i < l; i++) { - convertedSet[i] = this.extractor(trainingSet[i]); - } + compute(x, y) { + const distance = squaredEuclidean(x, y); + return Math.exp(-distance / this.divisor); } - this.numIterations = this.iterations * l; +} - if (this.algorithmMethod === 'random') { - this.timeConstant = this.numIterations / Math.log(this.mapRadius); - } else { - this.timeConstant = l / Math.log(this.mapRadius); - } - this.trainingSet = convertedSet; - this.times.setTraining = Date.now() - now; -}; +module.exports = GaussianKernel; -SOM.prototype.trainOne = function trainOne() { - if (this.done) { - return false; +/***/ }), +/* 157 */ +/***/ (function(module, exports, __webpack_require__) { - } else if (this.numIterations-- > 0) { +"use strict"; - var neighbourhoodRadius, - trainingValue, - trainingSetFactor; - if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step - neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant); - trainingValue = getRandomValue(this.trainingSet, this.randomizer); - this._adjust(trainingValue, neighbourhoodRadius); - this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations); - } else { // Get next input vector - trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length); - neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant); - trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length]; - this._adjust(trainingValue, neighbourhoodRadius); - if (((this.iterationCount + 1) % this.trainingSet.length) === 0) { - this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length)); - } +const defaultOptions = { + degree: 1, + constant: 1, + scale: 1 +}; + +class PolynomialKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + + this.degree = options.degree; + this.constant = options.constant; + this.scale = options.scale; + } + + compute(x, y) { + var sum = 0; + for (var i = 0; i < x.length; i++) { + sum += x[i] * y[i]; } + return Math.pow(this.scale * sum + this.constant, this.degree); + } +} - this.iterationCount++; +module.exports = PolynomialKernel; - return true; - } else { +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { - this.done = true; - return false; +"use strict"; - } + +const defaultOptions = { + alpha: 0.01, + constant: -Math.E }; -SOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) { - var now = Date.now(), - x, y, dist, influence; +class SigmoidKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.alpha = options.alpha; + this.constant = options.constant; + } - var bmu = this._findBestMatchingUnit(trainingValue); + compute(x, y) { + var sum = 0; + for (var i = 0; i < x.length; i++) { + sum += x[i] * y[i]; + } + return Math.tanh(this.alpha * sum + this.constant); + } +} - var now2 = Date.now(); - this.times.findBMU += now2 - now; +module.exports = SigmoidKernel; - var radiusLimit = Math.floor(neighbourhoodRadius); - var xMin = bmu.x - radiusLimit, - xMax = bmu.x + radiusLimit, - yMin = bmu.y - radiusLimit, - yMax = bmu.y + radiusLimit; - for (x = xMin; x <= xMax; x++) { - var theX = x; - if (x < 0) { - theX += this.x; - } else if (x >= this.x) { - theX -= this.x; - } - for (y = yMin; y <= yMax; y++) { - var theY = y; - if (y < 0) { - theY += this.y; - } else if (y >= this.y) { - theY -= this.y; - } +/***/ }), +/* 159 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - dist = bmu[this.distanceMethod](this.nodes[theX][theY]); +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(3); - if (dist < neighbourhoodRadius) { - influence = Math.exp(-dist / (2 * neighbourhoodRadius)); - this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence); - } - } +// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs +function CholeskyDecomposition(value) { + if (!(this instanceof CholeskyDecomposition)) { + return new CholeskyDecomposition(value); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + if (!value.isSymmetric()) { + throw new Error('Matrix is not symmetric'); } - this.times.adjust += (Date.now() - now2); + var a = value, + dimension = a.rows, + l = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](dimension, dimension), + positiveDefinite = true, + i, j, k; -}; + for (j = 0; j < dimension; j++) { + var Lrowj = l[j]; + var d = 0; + for (k = 0; k < j; k++) { + var Lrowk = l[k]; + var s = 0; + for (i = 0; i < k; i++) { + s += Lrowk[i] * Lrowj[i]; + } + Lrowj[k] = s = (a[j][k] - s) / l[k][k]; + d = d + s * s; + } -SOM.prototype.train = function train(trainingSet) { - if (!this.done) { - this.setTraining(trainingSet); - while (this.trainOne()) { + d = a[j][j] - d; + + positiveDefinite &= (d > 0); + l[j][j] = Math.sqrt(Math.max(d, 0)); + for (k = j + 1; k < dimension; k++) { + l[j][k] = 0; } } -}; -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; - } + if (!positiveDefinite) { + throw new Error('Matrix is not positive definite'); } - return result; -}; -SOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) { + this.L = l; +} - var bmu, - lowest = Infinity, - dist; +CholeskyDecomposition.prototype = { + get lowerTriangularMatrix() { + return this.L; + }, + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); - 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]; + var l = this.L, + dimension = l.rows; + + if (value.rows !== dimension) { + throw new Error('Matrix dimensions do not match'); + } + + var count = value.columns, + B = value.clone(), + i, j, k; + + for (k = 0; k < dimension; k++) { + for (j = 0; j < count; j++) { + for (i = 0; i < k; i++) { + B[k][j] -= B[i][j] * l[k][i]; + } + B[k][j] /= l[k][k]; + } + } + + for (k = dimension - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + for (i = k + 1; i < dimension; i++) { + B[k][j] -= B[i][j] * l[i][k]; + } + B[k][j] /= l[k][k]; } } + + return B; } +}; + +/* harmony default export */ __webpack_exports__["a"] = (CholeskyDecomposition); + + +/***/ }), +/* 160 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - return bmu; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(25); -}; -SOM.prototype.predict = function predict(data, computePosition) { - if (typeof data === 'boolean') { - computePosition = data; - data = null; - } - if (!data) { - data = this.trainingSet; - } - if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset - var self = this; - return data.map(function (element) { - return self._predict(element, computePosition); - }); - } else { // predict a single element - return this._predict(data, computePosition); - } + +const defaultOptions = { + assumeSymmetric: false }; -SOM.prototype._predict = function _predict(element, computePosition) { - if (!Array.isArray(element)) { - element = this.extractor(element); +// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs +function EigenvalueDecomposition(matrix, options) { + options = Object.assign({}, defaultOptions, options); + if (!(this instanceof EigenvalueDecomposition)) { + return new EigenvalueDecomposition(matrix, options); } - var bmu = this._findBestMatchingUnit(element); - var result = [bmu.x, bmu.y]; - if (computePosition) { - result[2] = bmu.getPosition(element); + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + if (!matrix.isSquare()) { + throw new Error('Matrix is not a square matrix'); } - return result; -}; -// As seen in http://www.scholarpedia.org/article/Kohonen_network -SOM.prototype.getQuantizationError = function getQuantizationError() { - var fit = this.getFit(), - l = fit.length, - sum = 0; - for (var i = 0; i < l; i++) { - sum += fit[i]; - } - return sum / l; -}; + var n = matrix.columns, + V = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + d = new Array(n), + e = new Array(n), + value = matrix, + i, j; -SOM.prototype.getFit = function getFit(dataset) { - if (!dataset) { - dataset = this.trainingSet; - } - var l = dataset.length, - bmu, - result = new Array(l); - for (var i = 0; i < l; i++) { - bmu = this._findBestMatchingUnit(dataset[i]); - result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights)); + var isSymmetric = false; + if (options.assumeSymmetric) { + isSymmetric = true; + } else { + isSymmetric = matrix.isSymmetric(); } - return result; -}; -function getConverters(fields) { - var l = fields.length, - normalizers = new Array(l), - denormalizers = new Array(l); - for (var i = 0; i < l; i++) { - normalizers[i] = getNormalizer(fields[i].range); - denormalizers[i] = getDenormalizer(fields[i].range); - } - return { - extractor: function extractor(value) { - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = normalizers[i](value[fields[i].name]); + if (isSymmetric) { + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = value.get(i, j); } - return result; - }, - creator: function creator(value) { - var result = {}; - for (var i = 0; i < l; i++) { - result[fields[i].name] = denormalizers[i](value[i]); + } + tred2(n, e, d, V); + tql2(n, e, d, V); + } else { + var H = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + ort = new Array(n); + for (j = 0; j < n; j++) { + for (i = 0; i < n; i++) { + H[i][j] = value.get(i, j); } - return result; } - }; -} - -function getNormalizer(minMax) { - return function normalizer(value) { - return (value - minMax[0]) / (minMax[1] - minMax[0]); - }; -} + orthes(n, H, ort, V); + hqr2(n, e, d, V, H); + } -function getDenormalizer(minMax) { - return function denormalizer(value) { - return (minMax[0] + value * (minMax[1] - minMax[0])); - }; + this.n = n; + this.e = e; + this.d = d; + this.V = V; } -function squareEuclidean(a, b) { - var d = 0; - for (var i = 0, ii = a.length; i < ii; i++) { - d += (a[i] - b[i]) * (a[i] - b[i]); +EigenvalueDecomposition.prototype = { + get realEigenvalues() { + return this.d; + }, + get imaginaryEigenvalues() { + return this.e; + }, + get eigenvectorMatrix() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.V)) { + this.V = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.V); + } + return this.V; + }, + get diagonalMatrix() { + var n = this.n, + e = this.e, + d = this.d, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + X[i][j] = 0; + } + X[i][i] = d[i]; + if (e[i] > 0) { + X[i][i + 1] = e[i]; + } else if (e[i] < 0) { + X[i][i - 1] = e[i]; + } + } + return X; } - return d; -} +}; -function getRandomValue(arr, randomizer) { - return arr[Math.floor(randomizer() * arr.length)]; -} +function tred2(n, e, d, V) { -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 f, g, h, i, j, k, + hh, scale; + + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; } - return distance(zero, one); -} -module.exports = SOM; + for (i = n - 1; i > 0; i--) { + scale = 0; + h = 0; + for (k = 0; k < i; k++) { + scale = scale + Math.abs(d[k]); + } -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { + if (scale === 0) { + e[i] = d[i - 1]; + for (j = 0; j < i; j++) { + d[j] = V[i - 1][j]; + V[i][j] = 0; + V[j][i] = 0; + } + } else { + for (k = 0; k < i; k++) { + d[k] /= scale; + h += d[k] * d[k]; + } -const HashTable = __webpack_require__(19); + f = d[i - 1]; + g = Math.sqrt(h); + if (f > 0) { + g = -g; + } -class SparseMatrix { - constructor(rows, columns, options = {}) { - if (rows instanceof SparseMatrix) { // clone - const other = rows; - this._init(other.rows, other.columns, other.elements.clone(), other.threshold); - return; - } + e[i] = scale * g; + h = h - f * g; + d[i - 1] = f - g; + for (j = 0; j < i; j++) { + e[j] = 0; + } - if (Array.isArray(rows)) { - const matrix = rows; - rows = matrix.length; - options = columns || {}; - columns = matrix[0].length; - this._init(rows, columns, new HashTable(options), options.threshold); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - var value = matrix[i][j]; - if (this.threshold && Math.abs(value) < this.threshold) value = 0; - if (value !== 0) { - this.elements.set(i * columns + j, matrix[i][j]); - } + for (j = 0; j < i; j++) { + f = d[j]; + V[j][i] = f; + g = e[j] + V[j][j] * f; + for (k = j + 1; k <= i - 1; k++) { + g += V[k][j] * d[k]; + e[k] += V[k][j] * f; } + e[j] = g; + } + + f = 0; + for (j = 0; j < i; j++) { + e[j] /= h; + f += e[j] * d[j]; + } + + hh = f / (h + h); + for (j = 0; j < i; j++) { + e[j] -= hh * d[j]; + } + + for (j = 0; j < i; j++) { + f = d[j]; + g = e[j]; + for (k = j; k <= i - 1; k++) { + V[k][j] -= (f * e[k] + g * d[k]); + } + d[j] = V[i - 1][j]; + V[i][j] = 0; } - } else { - this._init(rows, columns, new HashTable(options), options.threshold); } + d[i] = h; } - _init(rows, columns, elements, threshold) { - this.rows = rows; - this.columns = columns; - this.elements = elements; - this.threshold = threshold || 0; - } - - static eye(rows = 1, columns = rows) { - const min = Math.min(rows, columns); - const matrix = new SparseMatrix(rows, columns, {initialCapacity: min}); - for (var i = 0; i < min; i++) { - matrix.set(i, i, 1); - } - return matrix; - } + for (i = 0; i < n - 1; i++) { + V[n - 1][i] = V[i][i]; + V[i][i] = 1; + h = d[i + 1]; + if (h !== 0) { + for (k = 0; k <= i; k++) { + d[k] = V[k][i + 1] / h; + } - clone() { - return new SparseMatrix(this); - } - - to2DArray() { - const copy = new Array(this.rows); - for (var i = 0; i < this.rows; i++) { - copy[i] = new Array(this.columns); - for (var j = 0; j < this.columns; j++) { - copy[i][j] = this.get(i, j); + for (j = 0; j <= i; j++) { + g = 0; + for (k = 0; k <= i; k++) { + g += V[k][i + 1] * V[k][j]; + } + for (k = 0; k <= i; k++) { + V[k][j] -= g * d[k]; + } } } - return copy; + + for (k = 0; k <= i; k++) { + V[k][i + 1] = 0; + } } - isSquare() { - return this.rows === this.columns; + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + V[n - 1][j] = 0; } - isSymmetric() { - if (!this.isSquare()) return false; + V[n - 1][n - 1] = 1; + e[0] = 0; +} - var symmetric = true; - this.forEachNonZero((i, j, v) => { - if (this.get(j, i) !== v) { - symmetric = false; - return false; - } - return v; - }); - return symmetric; - } +function tql2(n, e, d, V) { - get cardinality() { - return this.elements.size; - } + var g, h, i, j, k, l, m, p, r, + dl1, c, c2, c3, el1, s, s2, + iter; - get size() { - return this.rows * this.columns; + for (i = 1; i < n; i++) { + e[i - 1] = e[i]; } - get(row, column) { - return this.elements.get(row * this.columns + column); - } + e[n - 1] = 0; - set(row, column, value) { - if (this.threshold && Math.abs(value) < this.threshold) value = 0; - if (value === 0) { - this.elements.remove(row * this.columns + column); - } else { - this.elements.set(row * this.columns + column, value); + var f = 0, + tst1 = 0, + eps = Math.pow(2, -52); + + for (l = 0; l < n; l++) { + tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); + m = l; + while (m < n) { + if (Math.abs(e[m]) <= eps * tst1) { + break; + } + m++; } - return this; - } - - mmul(other) { - if (this.columns !== other.rows) - 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); + + if (m > l) { + iter = 0; + do { + iter = iter + 1; + + g = d[l]; + p = (d[l + 1] - g) / (2 * e[l]); + r = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(p, 1); + if (p < 0) { + r = -r; } - return v2; - }); - return v1; - }); - return result; - } - kroneckerProduct(other) { - const m = this.rows; - const n = this.columns; - const p = other.rows; - const q = other.columns; + d[l] = e[l] / (p + r); + d[l + 1] = e[l] * (p + r); + dl1 = d[l + 1]; + h = g - d[l]; + for (i = l + 2; i < n; i++) { + d[i] -= h; + } - 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; - } + f = f + h; - forEachNonZero(callback) { - this.elements.forEachPair((key, value) => { - const i = (key / this.columns) | 0; - const j = key % this.columns; - let r = callback(i, j, value); - if (r === false) return false; // stop iteration - if (this.threshold && Math.abs(r) < this.threshold) r = 0; - if (r !== value) { - if (r === 0) { - this.elements.remove(key, true); - } else { - this.elements.set(key, r); + p = d[m]; + c = 1; + c2 = c; + c3 = c; + el1 = e[l + 1]; + s = 0; + s2 = 0; + for (i = m - 1; i >= l; i--) { + c3 = c2; + c2 = c; + s2 = s; + g = c * e[i]; + h = c * p; + r = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(p, e[i]); + e[i + 1] = s * r; + s = e[i] / r; + c = p / r; + p = c * d[i] - s * g; + d[i + 1] = h + s * (c * g + s * d[i]); + + for (k = 0; k < n; k++) { + h = V[k][i + 1]; + V[k][i + 1] = s * V[k][i] + c * h; + V[k][i] = c * V[k][i] - s * h; + } } + + p = -s * s2 * c3 * el1 * e[l] / dl1; + e[l] = s * p; + d[l] = c * p; + } - return true; - }); - this.elements.maybeShrinkCapacity(); - return this; + while (Math.abs(e[l]) > eps * tst1); + } + d[l] = d[l] + f; + e[l] = 0; } - 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}; - } + 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]; + } + } - setThreshold(newThreshold) { - if (newThreshold !== 0 && newThreshold !== this.threshold) { - this.threshold = newThreshold; - this.forEachNonZero((i, j, v) => v); + if (k !== i) { + d[k] = d[i]; + d[i] = p; + for (j = 0; j < n; j++) { + p = V[j][i]; + V[j][i] = V[j][k]; + V[j][k] = p; + } } - return this; } } -SparseMatrix.prototype.klass = 'Matrix'; +function orthes(n, H, ort, V) { + + var low = 0, + high = n - 1, + f, g, h, i, j, m, + scale; + + for (m = low + 1; m <= high - 1; m++) { + scale = 0; + for (i = m; i <= high; i++) { + scale = scale + Math.abs(H[i][m - 1]); + } -SparseMatrix.identity = SparseMatrix.eye; -SparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct; + if (scale !== 0) { + h = 0; + for (i = high; i >= m; i--) { + ort[i] = H[i][m - 1] / scale; + h += ort[i] * ort[i]; + } -module.exports = SparseMatrix; + g = Math.sqrt(h); + if (ort[m] > 0) { + g = -g; + } -/* - Add dynamically instance and static methods for mathematical operations - */ + h = h - ort[m] * g; + ort[m] = ort[m] - g; -var inplaceOperator = ` -(function %name%(value) { - if (typeof value === 'number') return this.%name%S(value); - return this.%name%M(value); -}) -`; + for (j = m; j < n; j++) { + f = 0; + for (i = high; i >= m; i--) { + f += ort[i] * H[i][j]; + } -var inplaceOperatorScalar = ` -(function %name%S(value) { - this.forEachNonZero((i, j, v) => v %op% value); - return this; -}) -`; + f = f / h; + for (i = m; i <= high; i++) { + H[i][j] -= f * ort[i]; + } + } -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; -}) -`; + for (i = 0; i <= high; i++) { + f = 0; + for (j = high; j >= m; j--) { + f += ort[j] * H[i][j]; + } -var staticOperator = ` -(function %name%(matrix, value) { - var newMatrix = new SparseMatrix(matrix); - return newMatrix.%name%(value); -}) -`; + f = f / h; + for (j = m; j <= high; j++) { + H[i][j] -= f * ort[j]; + } + } -var inplaceMethod = ` -(function %name%() { - this.forEachNonZero((i, j, v) => %method%(v)); - return this; -}) -`; + ort[m] = scale * ort[m]; + H[m][m - 1] = scale * g; + } + } -var staticMethod = ` -(function %name%(matrix) { - var newMatrix = new SparseMatrix(matrix); - return newMatrix.%name%(); -}) -`; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = (i === j ? 1 : 0); + } + } -var operators = [ - // Arithmetic operators - ['+', 'add'], - ['-', 'sub', 'subtract'], - ['*', 'mul', 'multiply'], - ['/', 'div', 'divide'], - ['%', 'mod', 'modulus'], - // Bitwise operators - ['&', 'and'], - ['|', 'or'], - ['^', 'xor'], - ['<<', 'leftShift'], - ['>>', 'signPropagatingRightShift'], - ['>>>', 'rightShift', 'zeroFillRightShift'] -]; + for (m = high - 1; m >= low + 1; m--) { + if (H[m][m - 1] !== 0) { + for (i = m + 1; i <= high; i++) { + ort[i] = H[i][m - 1]; + } -for (var operator of operators) { - for (var i = 1; i < operator.length; i++) { - SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]})); - SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]})); - SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]})); + for (j = m; j <= high; j++) { + g = 0; + for (i = m; i <= high; i++) { + g += ort[i] * V[i][j]; + } - SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]})); + g = (g / ort[m]) / H[m][m - 1]; + for (i = m; i <= high; i++) { + V[i][j] += g * ort[i]; + } + } + } } } -var methods = [ - ['~', 'not'] -]; +function hqr2(nn, e, d, V, H) { + var n = nn - 1, + low = 0, + high = nn - 1, + eps = Math.pow(2, -52), + exshift = 0, + norm = 0, + p = 0, + q = 0, + r = 0, + s = 0, + z = 0, + iter = 0, + i, j, k, l, m, t, w, x, y, + ra, sa, vr, vi, + notlast, cdivres; -[ - '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]); -}); + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + d[i] = H[i][i]; + e[i] = 0; + } -for (var method of methods) { - for (var i = 1; i < method.length; i++) { - SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, {name: method[i], method: method[0]})); - SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, {name: method[i]})); + for (j = Math.max(i - 1, 0); j < nn; j++) { + norm = norm + Math.abs(H[i][j]); + } } -} -function fillTemplateFunction(template, values) { - for (var i in values) { - template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]); - } - return template; -} + while (n >= low) { + l = n; + while (l > low) { + s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); + if (s === 0) { + s = norm; + } + if (Math.abs(H[l][l - 1]) < eps * s) { + break; + } + l--; + } + + if (l === n) { + H[n][n] = H[n][n] + exshift; + d[n] = H[n][n]; + e[n] = 0; + n--; + iter = 0; + } else if (l === n - 1) { + w = H[n][n - 1] * H[n - 1][n]; + p = (H[n - 1][n - 1] - H[n][n]) / 2; + q = p * p + w; + z = Math.sqrt(Math.abs(q)); + H[n][n] = H[n][n] + exshift; + H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; + x = H[n][n]; + if (q >= 0) { + z = (p >= 0) ? (p + z) : (p - z); + d[n - 1] = x + z; + d[n] = d[n - 1]; + if (z !== 0) { + d[n] = x - w / z; + } + e[n - 1] = 0; + e[n] = 0; + x = H[n][n - 1]; + s = Math.abs(x) + Math.abs(z); + p = x / s; + q = z / s; + r = Math.sqrt(p * p + q * q); + p = p / r; + q = q / r; -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { + for (j = n - 1; j < nn; j++) { + z = H[n - 1][j]; + H[n - 1][j] = q * z + p * H[n][j]; + H[n][j] = q * H[n][j] - p * z; + } -"use strict"; + for (i = 0; i <= n; i++) { + z = H[i][n - 1]; + H[i][n - 1] = q * z + p * H[i][n]; + H[i][n] = q * H[i][n] - p * z; + } -const Kernel = __webpack_require__(8); -const stat = __webpack_require__(2).array; + for (i = low; i <= high; i++) { + z = V[i][n - 1]; + V[i][n - 1] = q * z + p * V[i][n]; + V[i][n] = q * V[i][n] - p * z; + } + } else { + d[n - 1] = x + p; + d[n] = x + p; + e[n - 1] = z; + e[n] = -z; + } -var defaultOptions = { - C: 1, - tol: 1e-4, - maxPasses: 10, - maxIterations: 10000, - kernel: 'linear', - alphaTol: 1e-6, - random: Math.random, - whitening: true -}; + n = n - 2; + iter = 0; + } else { + x = H[n][n]; + y = 0; + w = 0; + if (l < n) { + y = H[n - 1][n - 1]; + w = H[n][n - 1] * H[n - 1][n]; + } -/** - * Simplified version of the Sequential Minimal Optimization algorithm for training - * support vector machines - * @param {{Object}} options - SVM options - * @param {Number} [options.C=1] - regularization parameter - * @param {Number} [options.tol=1e-4] - numerical tolerance - * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors - * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing - * @param {Number} [options.maxIterations=10000] - max number of iterations - * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels} - * @param {Function} [options.random=Math.random] - custom random number generator - * @constructor - */ -function SVM(options) { - this.options = Object.assign({}, defaultOptions, options); + if (iter === 10) { + exshift += x; + for (i = low; i <= n; i++) { + H[i][i] -= x; + } + s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); + x = y = 0.75 * s; + w = -0.4375 * s * s; + } - this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions); - this.b = 0; -} + if (iter === 30) { + s = (y - x) / 2; + s = s * s + w; + if (s > 0) { + s = Math.sqrt(s); + if (y < x) { + s = -s; + } + s = x - w / ((y - x) / 2 + s); + for (i = low; i <= n; i++) { + H[i][i] -= s; + } + exshift += s; + x = y = w = 0.964; + } + } -/** - * Train the SVM model - * @param {Array >} features - training data features - * @param {Array } labels - training data labels in the domain {1,-1} - */ -SVM.prototype.train = function (features, labels) { - if (features.length !== labels.length) { - throw new Error('Features and labels should have the same length'); - } - if (features.length < 2) { - throw new Error('Cannot train with less than 2 observations'); - } - this._trained = false; - this._loaded = false; - this.N = labels.length; - this.D = features[0].length; - if (this.options.whitening) { - this.X = new Array(this.N); - for (var i = 0; i < this.N; i++) { - this.X[i] = new Array(this.D); - } - this.minMax = new Array(this.D); - // Apply normalization and keep normalization parameters - for (var j = 0; j < this.D; j++) { - var d = new Array(this.N); - for (i = 0; i < this.N; i++) { - d[i] = features[i][j]; + iter = iter + 1; + + m = n - 2; + while (m >= l) { + z = H[m][m]; + r = x - z; + s = y - z; + p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; + q = H[m + 1][m + 1] - z - r - s; + r = H[m + 2][m + 1]; + s = Math.abs(p) + Math.abs(q) + Math.abs(r); + p = p / s; + q = q / s; + r = r / s; + if (m === l) { + break; + } + if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { + break; + } + m--; } - this.minMax[j] = stat.minMax(d); - for (i = 0; i < this.N; i++) { - this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); + + for (i = m + 2; i <= n; i++) { + H[i][i - 2] = 0; + if (i > m + 2) { + H[i][i - 3] = 0; + } } - } - } else { - this.X = features; - } - this.Y = labels; - this.b = 0; - this.W = undefined; - var kernel = this.kernel.compute(this.X); - var m = labels.length; - var alpha = new Array(m).fill(0); - this.alphas = alpha; - for (var a = 0; a < m; a++) - alpha[a] = 0; + for (k = m; k <= n - 1; k++) { + notlast = (k !== n - 1); + if (k !== m) { + p = H[k][k - 1]; + q = H[k + 1][k - 1]; + r = (notlast ? H[k + 2][k - 1] : 0); + x = Math.abs(p) + Math.abs(q) + Math.abs(r); + if (x !== 0) { + p = p / x; + q = q / x; + r = r / x; + } + } - var b1 = 0, - b2 = 0, - iter = 0, - passes = 0, - Ei = 0, - Ej = 0, - ai = 0, - aj = 0, - L = 0, - H = 0, - eta = 0; + if (x === 0) { + break; + } - while (passes < this.options.maxPasses && iter < this.options.maxIterations) { - var numChange = 0; - for (i = 0; i < m; i++) { - Ei = this._marginOnePrecomputed(i, kernel) - labels[i]; - if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) { - j = i; - while (j === i) j = Math.floor(this.options.random() * m); - Ej = this._marginOnePrecomputed(j, kernel) - labels[j]; - ai = alpha[i]; - aj = alpha[j]; - if (labels[i] === labels[j]) { - L = Math.max(0, ai + aj - this.options.C); - H = Math.min(this.options.C, ai + aj); - } else { - L = Math.max(0, aj - ai); - H = Math.min(this.options.C, this.options.C + aj + ai); + s = Math.sqrt(p * p + q * q + r * r); + if (p < 0) { + s = -s; } - if (Math.abs(L - H) < 1e-4) continue; - eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j]; - if (eta >= 0) continue; - var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta; - if (newaj > H) - newaj = H; - else if (newaj < L) - newaj = L; - if (Math.abs(aj - newaj) < 10e-4) continue; - alpha[j] = newaj; - alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj); - b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j]; - b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j]; - this.b = (b1 + b2) / 2; - if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1; - if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2; - numChange += 1; - } - } - iter++; - if (numChange === 0) - passes += 1; - else - passes = 0; - } - if (iter === this.options.maxIterations) { - throw new Error('max iterations reached'); - } + if (s !== 0) { + if (k !== m) { + H[k][k - 1] = -s * x; + } else if (l !== m) { + H[k][k - 1] = -H[k][k - 1]; + } - this.iterations = iter; + p = p + s; + x = p / s; + y = q / s; + z = r / s; + q = q / p; + r = r / p; - // Compute the weights (useful for fast decision on new test instances when linear SVM) - if (this.options.kernel === 'linear') { - this.W = new Array(this.D); - for (var r = 0; r < this.D; r++) { - this.W[r] = 0; - for (var w = 0; w < m; w++) - this.W[r] += labels[w] * alpha[w] * this.X[w][r]; - } - } + for (j = k; j < nn; j++) { + p = H[k][j] + q * H[k + 1][j]; + if (notlast) { + p = p + r * H[k + 2][j]; + H[k + 2][j] = H[k + 2][j] - p * z; + } - // Keep only support vectors - // It will compute decision on new test instances faster - // We also keep the index of the support vectors - // in the original data - var nX = []; - var nY = []; - var nAlphas = []; - this._supportVectorIdx = []; - for (i = 0; i < this.N; i++) { - if (this.alphas[i] > this.options.alphaTol) { - nX.push(this.X[i]); - nY.push(labels[i]); - nAlphas.push(this.alphas[i]); - this._supportVectorIdx.push(i); + H[k][j] = H[k][j] - p * x; + H[k + 1][j] = H[k + 1][j] - p * y; + } + + for (i = 0; i <= Math.min(n, k + 3); i++) { + p = x * H[i][k] + y * H[i][k + 1]; + if (notlast) { + p = p + z * H[i][k + 2]; + H[i][k + 2] = H[i][k + 2] - p * r; + } + H[i][k] = H[i][k] - p; + H[i][k + 1] = H[i][k + 1] - p * q; + } + + for (i = low; i <= high; i++) { + p = x * V[i][k] + y * V[i][k + 1]; + if (notlast) { + p = p + z * V[i][k + 2]; + V[i][k + 2] = V[i][k + 2] - p * r; + } + + V[i][k] = V[i][k] - p; + V[i][k + 1] = V[i][k + 1] - p * q; + } + } + } } } - this.X = nX; - this.Y = nY; - this.N = nX.length; - this.alphas = nAlphas; + if (norm === 0) { + return; + } - // A flag to say this SVM has been trained - this._trained = true; -}; - -/** - * Get prediction ({-1,1}) given one observation's features. - * @private - * @param p The observation's features. - * @returns {number} Classification result ({-1,1}) - */ -SVM.prototype.predictOne = function (p) { - var margin = this.marginOne(p); - return margin > 0 ? 1 : -1; -}; + for (n = nn - 1; n >= 0; n--) { + p = d[n]; + q = e[n]; -/** - * Predict the classification outcome of a trained svm given one or several observations' features. - * @param {Array} features - The observation(s)' features - * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation - * is given - */ -SVM.prototype.predict = function (features) { - if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first'); - if (Array.isArray(features) && Array.isArray(features[0])) { - return features.map(this.predictOne.bind(this)); - } else { - return this.predictOne(features); - } -}; + if (q === 0) { + l = n; + H[n][n] = 1; + for (i = n - 1; i >= 0; i--) { + w = H[i][i] - p; + r = 0; + for (j = l; j <= n; j++) { + r = r + H[i][j] * H[j][n]; + } -/** - * Get margin given one observation's features - * @private - * @param {Array} features - Features - * @returns {Number} - The computed margin - */ -SVM.prototype.marginOne = function (features, noWhitening) { - // Apply normalization - if (this.options.whitening && !noWhitening) { - features = this._applyWhitening(features); - } - var ans = this.b, i; - if (this.options.kernel === 'linear' && this.W) { - // Use weights, it's faster - for (i = 0; i < this.W.length; i++) { - ans += this.W[i] * features[i]; - } - } else { - for (i = 0; i < this.N; i++) { - ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0]; - } - } - return ans; -}; + if (e[i] < 0) { + z = w; + s = r; + } else { + l = i; + if (e[i] === 0) { + H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm)); + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; + t = (x * s - z * r) / q; + H[i][n] = t; + H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z); + } + t = Math.abs(H[i][n]); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n] = H[j][n] / t; + } + } + } + } + } else if (q < 0) { + l = n - 1; -/** - * Get a margin using the precomputed kernel. Much faster than normal margin computation - * @private - * @param {Number} index - Train data index - * @param {Array< Array >} kernel - The precomputed kernel - * @returns {number} Computed margin - * @private - */ -SVM.prototype._marginOnePrecomputed = function (index, kernel) { - var ans = this.b, i; - for (i = 0; i < this.N; i++) { - ans += this.alphas[i] * this.Y[i] * kernel[index][i]; - } - return ans; -}; + if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { + H[n - 1][n - 1] = q / H[n][n - 1]; + H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; + } else { + cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); + H[n - 1][n - 1] = cdivres[0]; + H[n - 1][n] = cdivres[1]; + } + H[n][n - 1] = 0; + H[n][n] = 1; + for (i = n - 2; i >= 0; i--) { + ra = 0; + sa = 0; + for (j = l; j <= n; j++) { + ra = ra + H[i][j] * H[j][n - 1]; + sa = sa + H[i][j] * H[j][n]; + } -/** - * Returns the margin of one or several observations given its features - * @param {Array >|Array} features - Features from on or several observations. - * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if - * only one observation's features given - */ -SVM.prototype.margin = function (features) { - if (Array.isArray(features)) { - return features.map(this.marginOne.bind(this)); - } else { - return this.marginOne(features); - } -}; + w = H[i][i] - p; -/** - * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances - * created from {@link #SVM.load load} if linear kernel - * @returns {Array} The indices in the training vector of the support vectors - */ -SVM.prototype.supportVectors = function () { - if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first'); - if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them'); - return this._supportVectorIdx; -}; + if (e[i] < 0) { + z = w; + r = ra; + s = sa; + } else { + l = i; + if (e[i] === 0) { + cdivres = cdiv(-ra, -sa, w, q); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; + vi = (d[i] - p) * 2 * q; + if (vr === 0 && vi === 0) { + vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); + } + cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { + H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; + H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; + } else { + cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); + H[i + 1][n - 1] = cdivres[0]; + H[i + 1][n] = cdivres[1]; + } + } -/** - * Create a SVM instance from a saved model - * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON} - * @returns {SVM} Instance of svm classifier - */ -SVM.load = function (model) { - this._loaded = true; - this._trained = false; - var svm = new SVM(model.options); - if (model.options.kernel === 'linear') { - svm.W = model.W.slice(); - svm.D = svm.W.length; - } else { - svm.X = model.X.slice(); - svm.Y = model.Y.slice(); - svm.alphas = model.alphas.slice(); - svm.N = svm.X.length; - svm.D = svm.X[0].length; + t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n - 1] = H[j][n - 1] / t; + H[j][n] = H[j][n] / t; + } + } + } + } + } } - svm.minMax = model.minMax; - svm.b = model.b; - svm._loaded = true; - svm._trained = false; - return svm; -}; -/** - * Export the minimal object that enables to reload the model - * @returns {Object} Model object that can be reused with {@link #SVM.load load} - */ -SVM.prototype.toJSON = function () { - if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first'); - var model = {}; - model.options = Object.assign({}, this.options); - model.b = this.b; - model.minMax = this.minMax; - if (model.options.kernel === 'linear') { - model.W = this.W.slice(); - } else { - // Exporting non-linear models is heavier - model.X = this.X.slice(); - model.Y = this.Y.slice(); - model.alphas = this.alphas.slice(); + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + for (j = i; j < nn; j++) { + V[i][j] = H[i][j]; + } + } } - return model; -}; -SVM.prototype._applyWhitening = function (features) { - if (!this.minMax) throw new Error('Could not apply whitening'); - var whitened = new Array(features.length); - for (var j = 0; j < features.length; j++) { - whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); + for (j = nn - 1; j >= low; j--) { + for (i = low; i <= high; i++) { + z = 0; + for (k = low; k <= Math.min(j, high); k++) { + z = z + V[i][k] * H[k][j]; + } + V[i][j] = z; + } + } +} + +function cdiv(xr, xi, yr, yi) { + var r, d; + if (Math.abs(yr) > Math.abs(yi)) { + r = yi / yr; + d = yr + r * yi; + return [(xr + r * xi) / d, (xi - r * xr) / d]; + } else { + r = yr / yi; + d = yi + r * yr; + return [(r * xr + xi) / d, (r * xi - xr) / d]; } - return whitened; -}; +} -module.exports = SVM; +/* harmony default export */ __webpack_exports__["a"] = (EigenvalueDecomposition); /***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { +/* 161 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony export (immutable) */ __webpack_exports__["b"] = inverse; +/* harmony export (immutable) */ __webpack_exports__["a"] = solve; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__dc_lu__ = __webpack_require__(24); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__dc_qr__ = __webpack_require__(59); -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var LOOP = 8; -var FLOAT_MUL = 1 / 16777216; +function inverse(matrix) { + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + return solve(matrix, __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].eye(matrix.rows)); +} -function multiply_uint32(n, m) { - n >>>= 0; - m >>>= 0; - var nlo = n & 0xffff; - var nhi = n - nlo; - return (nhi * m >>> 0) + nlo * m >>> 0; +function solve(leftHandSide, rightHandSide) { + leftHandSide = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(leftHandSide); + rightHandSide = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(rightHandSide); + return leftHandSide.isSquare() ? new __WEBPACK_IMPORTED_MODULE_1__dc_lu__["a" /* default */](leftHandSide).solve(rightHandSide) : new __WEBPACK_IMPORTED_MODULE_2__dc_qr__["a" /* default */](leftHandSide).solve(rightHandSide); } -var XSadd = (function () { - function XSadd() { - var seed = arguments.length <= 0 || arguments[0] === undefined ? Date.now() : arguments[0]; - _classCallCheck(this, XSadd); +/***/ }), +/* 162 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(3); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return __WEBPACK_IMPORTED_MODULE_0__matrix__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Matrix", function() { return __WEBPACK_IMPORTED_MODULE_0__matrix__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__ = __webpack_require__(23); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "abstractMatrix", function() { return __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__decompositions__ = __webpack_require__(161); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "solve", function() { return __WEBPACK_IMPORTED_MODULE_2__decompositions__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "inverse", function() { return __WEBPACK_IMPORTED_MODULE_2__decompositions__["b"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__dc_svd_js__ = __webpack_require__(60); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "SingularValueDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_3__dc_svd_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "SVD", function() { return __WEBPACK_IMPORTED_MODULE_3__dc_svd_js__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__dc_evd_js__ = __webpack_require__(160); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "EigenvalueDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_4__dc_evd_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "EVD", function() { return __WEBPACK_IMPORTED_MODULE_4__dc_evd_js__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__dc_cholesky_js__ = __webpack_require__(159); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CholeskyDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_5__dc_cholesky_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "CHO", function() { return __WEBPACK_IMPORTED_MODULE_5__dc_cholesky_js__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__dc_lu_js__ = __webpack_require__(24); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "LuDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_6__dc_lu_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "LU", function() { return __WEBPACK_IMPORTED_MODULE_6__dc_lu_js__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__dc_qr_js__ = __webpack_require__(59); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "QrDecomposition", function() { return __WEBPACK_IMPORTED_MODULE_7__dc_qr_js__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "QR", function() { return __WEBPACK_IMPORTED_MODULE_7__dc_qr_js__["a"]; }); + - this.state = new Uint32Array(4); - this.init(seed); - } - _createClass(XSadd, [{ - key: "init", - value: function init(seed) { - this.state[0] = seed; - this.state[1] = 0; - this.state[2] = 0; - this.state[3] = 0; - for (var i = 1; i < LOOP; i++) { - this.state[i & 3] ^= i + multiply_uint32(1812433253, this.state[i - 1 & 3] ^ this.state[i - 1 & 3] >>> 30 >>> 0) >>> 0; - } - period_certification(this); - for (var i = 0; i < LOOP; i++) { - next_state(this); - } - } - /** - * Returns a 32-bit integer r (0 <= r < 2^32) - */ - }, { - key: "getUint32", - value: function getUint32() { - next_state(this); - return this.state[3] + this.state[2] >>> 0; - } - /** - * Returns a floating point number r (0.0 <= r < 1.0) - */ - }, { - key: "getFloat", - value: function getFloat() { - return (this.getUint32() >>> 8) * FLOAT_MUL; - } - }, { - key: "random", - get: function get() { - if (!this._random) { - this._random = this.getFloat.bind(this); - } - return this._random; - } - }]); - return XSadd; -})(); -exports["default"] = XSadd; -function period_certification(xsadd) { - if (xsadd.state[0] === 0 && xsadd.state[1] === 0 && xsadd.state[2] === 0 && xsadd.state[3] === 0) { - xsadd.state[0] = 88; // X - xsadd.state[1] = 83; // S - xsadd.state[2] = 65; // A - xsadd.state[3] = 68; // D - } -} -var sh1 = 15; -var sh2 = 18; -var sh3 = 11; -function next_state(xsadd) { - var t = xsadd.state[0]; - t ^= t << sh1; - t ^= t >>> sh2; - t ^= xsadd.state[3] << sh3; - xsadd.state[0] = xsadd.state[1]; - xsadd.state[1] = xsadd.state[2]; - xsadd.state[2] = xsadd.state[3]; - xsadd.state[3] = t; -} -module.exports = exports["default"]; /***/ }), -/* 62 */ +/* 163 */ /***/ (function(module, exports) { -(function(undefined) { - 'use strict'; - - // Node.js usage: - // - // var Picker = require('RandomSelection').Picker; - // var greetingPicker = new Picker(['hello', 'hi', 'howdy']); - // var greeting = greetingPicker.pick(); - - // Our namespace. Exported members will be attached to this. - var ns; - - // Set our namespace based on whether we are running in Node.js or the browser. - if (typeof module !== 'undefined' && module.exports) { - // We are running in Node. - ns = module.exports; - } - else { - // We are running in the browser. - // `this` is the `window`. - // Use window.RandomSelection as our namespace. - ns = this.RandomSelection = {}; - } - - // Gets a shallow copy of the given array. - function clone(arr) { - var newArr = []; - for (var i=0; i y) { - return 1; - } - return 0; - }; +/***/ }), +/* 165 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(8); - /* - 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. - */ - insort = function(a, x, lo, hi, cmp) { - var mid; - if (lo == null) { - lo = 0; +class MatrixFlipColumnView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); } - if (cmp == null) { - cmp = defaultCmp; + + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); + return this; } - if (lo < 0) { - throw new Error('lo must be non-negative'); + + get(rowIndex, columnIndex) { + return this.matrix.get(rowIndex, this.columns - columnIndex - 1); } - if (hi == null) { - hi = a.length; +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixFlipColumnView; + + + +/***/ }), +/* 166 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(8); + + +class MatrixFlipRowView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); } - while (lo < hi) { - mid = floor((lo + hi) / 2); - if (cmp(x, a[mid]) < 0) { - hi = mid; - } else { - lo = mid + 1; - } + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); + return this; } - return ([].splice.apply(a, [lo, lo - lo].concat(x)), x); - }; + get(rowIndex, columnIndex) { + return this.matrix.get(this.rows - rowIndex - 1, columnIndex); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixFlipRowView; - /* - Push item onto heap, maintaining the heap invariant. - */ - heappush = function(array, item, cmp) { - if (cmp == null) { - cmp = defaultCmp; - } - array.push(item); - return _siftdown(array, 0, array.length - 1, cmp); - }; +/***/ }), +/* 167 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - /* - Pop the smallest item off the heap, maintaining the heap invariant. - */ +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(8); - heappop = function(array, cmp) { - var lastelt, returnitem; - if (cmp == null) { - cmp = defaultCmp; + +class MatrixRowView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, row) { + super(matrix, 1, matrix.columns); + this.row = row; } - lastelt = array.pop(); - if (array.length) { - returnitem = array[0]; - array[0] = lastelt; - _siftup(array, 0, cmp); - } else { - returnitem = lastelt; + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.row, columnIndex, value); + return this; } - return returnitem; - }; + get(rowIndex, columnIndex) { + return this.matrix.get(this.row, columnIndex); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixRowView; - /* - 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) - */ - heapreplace = function(array, item, cmp) { - var returnitem; - if (cmp == null) { - cmp = defaultCmp; - } - returnitem = array[0]; - array[0] = item; - _siftup(array, 0, cmp); - return returnitem; - }; +/***/ }), +/* 168 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - /* - Fast version of a heappush followed by a heappop. - */ +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(8); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(15); - heappushpop = function(array, item, cmp) { - var _ref; - if (cmp == null) { - cmp = defaultCmp; - } - if (array.length && cmp(array[0], item) < 0) { - _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; - _siftup(array, 0, cmp); - } - return item; - }; - /* - Transform list into a heap, in-place, in O(array.length) time. - */ +class MatrixSelectionView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, rowIndices, columnIndices) { + var indices = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["i" /* checkIndices */])(matrix, rowIndices, columnIndices); + super(matrix, indices.row.length, indices.column.length); + this.rowIndices = indices.row; + this.columnIndices = indices.column; + } - heapify = function(array, cmp) { - var i, _i, _j, _len, _ref, _ref1, _results, _results1; - if (cmp == null) { - cmp = defaultCmp; + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); + return this; } - _ref1 = (function() { - _results1 = []; - for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); } - return _results1; - }).apply(this).reverse(); - _results = []; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - i = _ref1[_i]; - _results.push(_siftup(array, i, cmp)); + + get(rowIndex, columnIndex) { + return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); } - return _results; - }; +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixSelectionView; - /* - Update the position of the given item in the heap. - This function should be called every time the item is being modified. - */ - updateItem = function(array, item, cmp) { - var pos; - if (cmp == null) { - cmp = defaultCmp; - } - pos = array.indexOf(item); - if (pos === -1) { - return; - } - _siftdown(array, 0, pos, cmp); - return _siftup(array, pos, cmp); - }; +/***/ }), +/* 169 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(8); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(15); - /* - Find the n largest elements in a dataset. - */ - nlargest = function(array, n, cmp) { - var elem, result, _i, _len, _ref; - if (cmp == null) { - cmp = defaultCmp; +class MatrixSubView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, startRow, endRow, startColumn, endColumn) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["h" /* checkRange */])(matrix, startRow, endRow, startColumn, endColumn); + super(matrix, endRow - startRow + 1, endColumn - startColumn + 1); + this.startRow = startRow; + this.startColumn = startColumn; } - result = array.slice(0, n); - if (!result.length) { - return result; + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); + return this; } - heapify(result, cmp); - _ref = array.slice(n); - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - elem = _ref[_i]; - heappushpop(result, elem, cmp); + + get(rowIndex, columnIndex) { + return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); } - return result.sort(cmp).reverse(); - }; +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixSubView; - /* - Find the n smallest elements in a dataset. - */ - nsmallest = function(array, n, cmp) { - var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; - if (cmp == null) { - cmp = defaultCmp; - } - if (n * 10 <= array.length) { - result = array.slice(0, n).sort(cmp); - if (!result.length) { - return result; - } - los = result[result.length - 1]; - _ref = array.slice(n); - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - elem = _ref[_i]; - if (cmp(elem, los) < 0) { - insort(result, elem, 0, null, cmp); - result.pop(); - los = result[result.length - 1]; - } - } - return result; - } - heapify(array, cmp); - _results = []; - for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { - _results.push(heappop(array, cmp)); - } - return _results; - }; +/***/ }), +/* 170 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - _siftdown = function(array, startpos, pos, cmp) { - var newitem, parent, parentpos; - if (cmp == null) { - cmp = defaultCmp; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(8); + + +class MatrixTransposeView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.columns, matrix.rows); } - newitem = array[pos]; - while (pos > startpos) { - parentpos = (pos - 1) >> 1; - parent = array[parentpos]; - if (cmp(newitem, parent) < 0) { - array[pos] = parent; - pos = parentpos; - continue; - } - break; + + set(rowIndex, columnIndex, value) { + this.matrix.set(columnIndex, rowIndex, value); + return this; } - return array[pos] = newitem; - }; - _siftup = function(array, pos, cmp) { - var childpos, endpos, newitem, rightpos, startpos; - if (cmp == null) { - cmp = defaultCmp; + get(rowIndex, columnIndex) { + return this.matrix.get(columnIndex, rowIndex); } - endpos = array.length; - startpos = pos; - newitem = array[pos]; - childpos = 2 * pos + 1; - while (childpos < endpos) { - rightpos = childpos + 1; - if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { - childpos = rightpos; - } - array[pos] = array[childpos]; - pos = childpos; - childpos = 2 * pos + 1; +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixTransposeView; + + + +/***/ }), +/* 171 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const defaultOptions = { + sigma: 1, + degree: 1 +}; + +class ANOVAKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + this.degree = options.degree; } - array[pos] = newitem; - return _siftdown(array, startpos, pos, cmp); - }; - Heap = (function() { - Heap.push = heappush; + compute(x, y) { + var sum = 0; + var len = Math.min(x.length, y.length); + for (var i = 1; i <= len; ++i) { + sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) - + Math.pow(y[i - 1], i), 2)), this.degree); + } + return sum; + } +} - Heap.pop = heappop; +module.exports = ANOVAKernel; - Heap.replace = heapreplace; - Heap.pushpop = heappushpop; +/***/ }), +/* 172 */ +/***/ (function(module, exports, __webpack_require__) { - Heap.heapify = heapify; +"use strict"; - Heap.updateItem = updateItem; - Heap.nlargest = nlargest; +const squaredEuclidean = __webpack_require__(1).squared; - Heap.nsmallest = nsmallest; +const defaultOptions = { + sigma: 1 +}; - function Heap(cmp) { - this.cmp = cmp != null ? cmp : defaultCmp; - this.nodes = []; +class CauchyKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; } - Heap.prototype.push = function(x) { - return heappush(this.nodes, x, this.cmp); - }; + compute(x, y) { + return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma)); + } +} - Heap.prototype.pop = function() { - return heappop(this.nodes, this.cmp); - }; +module.exports = CauchyKernel; - Heap.prototype.peek = function() { - return this.nodes[0]; - }; - Heap.prototype.contains = function(x) { - return this.nodes.indexOf(x) !== -1; - }; +/***/ }), +/* 173 */ +/***/ (function(module, exports, __webpack_require__) { - Heap.prototype.replace = function(x) { - return heapreplace(this.nodes, x, this.cmp); - }; +"use strict"; - Heap.prototype.pushpop = function(x) { - return heappushpop(this.nodes, x, this.cmp); - }; - Heap.prototype.heapify = function() { - return heapify(this.nodes, this.cmp); - }; +const euclidean = __webpack_require__(1); - Heap.prototype.updateItem = function(x) { - return updateItem(this.nodes, x, this.cmp); - }; +const defaultOptions = { + sigma: 1 +}; - Heap.prototype.clear = function() { - return this.nodes = []; - }; +class ExponentialKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + this.divisor = 2 * options.sigma * options.sigma; + } - Heap.prototype.empty = function() { - return this.nodes.length === 0; - }; + compute(x, y) { + const distance = euclidean(x, y); + return Math.exp(-distance / this.divisor); + } +} - Heap.prototype.size = function() { - return this.nodes.length; - }; +module.exports = ExponentialKernel; - 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); - }; +/***/ }), +/* 174 */ +/***/ (function(module, exports, __webpack_require__) { - Heap.prototype.insert = Heap.prototype.push; +"use strict"; - Heap.prototype.top = Heap.prototype.peek; - Heap.prototype.front = Heap.prototype.peek; +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]); + } - Heap.prototype.has = Heap.prototype.contains; + return sum; + } +} - Heap.prototype.copy = Heap.prototype.clone; +module.exports = HistogramIntersectionKernel; - return Heap; - })(); +/***/ }), +/* 175 */ +/***/ (function(module, exports, __webpack_require__) { - (function(root, factory) { - if (true) { - return !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (typeof exports === 'object') { - return module.exports = factory(); - } else { - return root.Heap = factory(); +"use strict"; + + +const euclidean = __webpack_require__(1); + +const defaultOptions = { + sigma: 1 +}; + +class LaplacianKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; } - })(this, function() { - return Heap; - }); -}).call(this); + compute(x, y) { + const distance = euclidean(x, y); + return Math.exp(-distance / this.sigma); + } +} + +module.exports = LaplacianKernel; /***/ }), -/* 65 */ +/* 176 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const Stat = __webpack_require__(2).array; -/** - * Function that returns an array of points given 1D array as follows: - * - * [x1, y1, .. , x2, y2, ..] - * - * And receive the number of dimensions of each point. - * @param array - * @param dimensions - * @returns {Array} - Array of points. - */ -function coordArrayToPoints(array, dimensions) { - if(array.length % dimensions !== 0) { - throw new RangeError('Dimensions number must be accordance with the size of the array.'); - } - - var length = array.length / dimensions; - var pointsArr = new Array(length); +const squaredEuclidean = __webpack_require__(1).squared; - var k = 0; - for(var i = 0; i < array.length; i += dimensions) { - var point = new Array(dimensions); - for(var j = 0; j < dimensions; ++j) { - point[j] = array[i + j]; - } +const defaultOptions = { + constant: 1 +}; - pointsArr[k] = point; - k++; +class MultiquadraticKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.constant = options.constant; } - return pointsArr; + compute(x, y) { + return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant); + } } +module.exports = MultiquadraticKernel; -/** - * Function that given an array as follows: - * [x1, y1, .. , x2, y2, ..] - * - * Returns an array as follows: - * [[x1, x2, ..], [y1, y2, ..], [ .. ]] - * - * And receives the number of dimensions of each coordinate. - * @param array - * @param dimensions - * @returns {Array} - Matrix of coordinates - */ -function coordArrayToCoordMatrix(array, dimensions) { - if(array.length % dimensions !== 0) { - throw new RangeError('Dimensions number must be accordance with the size of the array.'); - } - var coordinatesArray = new Array(dimensions); - var points = array.length / dimensions; - for (var i = 0; i < coordinatesArray.length; i++) { - coordinatesArray[i] = new Array(points); - } +/***/ }), +/* 177 */ +/***/ (function(module, exports, __webpack_require__) { - for(i = 0; i < array.length; i += dimensions) { - for(var j = 0; j < dimensions; ++j) { - var currentPoint = Math.floor(i / dimensions); - coordinatesArray[j][currentPoint] = array[i + j]; - } - } +"use strict"; - return coordinatesArray; -} -/** - * Function that receives a coordinate matrix as follows: - * [[x1, x2, ..], [y1, y2, ..], [ .. ]] - * - * Returns an array of coordinates as follows: - * [x1, y1, .. , x2, y2, ..] - * - * @param coordMatrix - * @returns {Array} - */ -function coordMatrixToCoordArray(coordMatrix) { - var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length); - var k = 0; - for(var i = 0; i < coordMatrix[0].length; ++i) { - for(var j = 0; j < coordMatrix.length; ++j) { - coodinatesArray[k] = coordMatrix[j][i]; - ++k; - } - } +const squaredEuclidean = __webpack_require__(1).squared; - return coodinatesArray; -} +const defaultOptions = { + constant: 1 +}; -/** - * Tranpose a matrix, this method is for coordMatrixToPoints and - * pointsToCoordMatrix, that because only transposing the matrix - * you can change your representation. - * - * @param matrix - * @returns {Array} - */ -function transpose(matrix) { - var resultMatrix = new Array(matrix[0].length); - for(var i = 0; i < resultMatrix.length; ++i) { - resultMatrix[i] = new Array(matrix.length); +class RationalQuadraticKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.constant = options.constant; } - for (i = 0; i < matrix.length; ++i) { - for(var j = 0; j < matrix[0].length; ++j) { - resultMatrix[j][i] = matrix[i][j]; - } + compute(x, y) { + const distance = squaredEuclidean(x, y); + return 1 - (distance / (distance + this.constant)); } - - return resultMatrix; } +module.exports = RationalQuadraticKernel; + + +/***/ }), +/* 178 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const utils = __webpack_require__(61); +const distanceSymbol = Symbol('distance'); + /** - * Function that transform an array of points into a coordinates array - * as follows: - * [x1, y1, .. , x2, y2, ..] - * - * @param points - * @returns {Array} + * 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 */ -function pointsToCoordArray(points) { - var coodinatesArray = new Array(points.length * points[0].length); - var k = 0; - for(var i = 0; i < points.length; ++i) { - for(var j = 0; j < points[0].length; ++j) { - coodinatesArray[k] = points[i][j]; - ++k; - } - } - - return coodinatesArray; +function KMeansResult(clusters, centroids, converged, iterations, distance) { + this.clusters = clusters; + this.centroids = centroids; + this.converged = converged; + this.iterations = iterations; + this[distanceSymbol] = distance; } /** - * Apply the dot product between the smaller vector and a subsets of the - * largest one. - * - * @param firstVector - * @param secondVector - * @returns {Array} each dot product of size of the difference between the - * larger and the smallest one. + * 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 */ -function applyDotProduct(firstVector, secondVector) { - var largestVector, smallestVector; - if(firstVector.length <= secondVector.length) { - smallestVector = firstVector; - largestVector = secondVector; - } else { - smallestVector = secondVector; - largestVector = firstVector; - } - - var difference = largestVector.length - smallestVector.length + 1; - var dotProductApplied = new Array(difference); - - for (var i = 0; i < difference; ++i) { - var sum = 0; - for (var j = 0; j < smallestVector.length; ++j) { - sum += smallestVector[j] * largestVector[i + j]; - } - dotProductApplied[i] = sum; - } +KMeansResult.prototype.nearest = function (data) { + var clusterID = new Array(data.length); + var centroids = this.centroids.map(function (centroid) { + return centroid.centroid; + }); + return utils.updateClusterID(data, centroids, clusterID, this[distanceSymbol]); +}; - return dotProductApplied; -} /** - * To scale the input array between the specified min and max values. The operation is performed inplace - * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling - * will multiply the input array by min/min(input) or max/max(input) - * @param input - * @param options - * @returns {*} + * Returns a KMeansResult with the error and size of the cluster + * @ignore + * @param {Array>} data - the [x,y,z,...] points to cluster + * @return {KMeansResult} */ -function scale(input, options){ - var y; - if(options.inPlace){ - y = input; - } - else{ - y = new Array(input.length); - } - const max = options.max; - const min = options.min; - if(typeof max === "number"){ - if(typeof min === "number"){ - var minMax = Stat.minMax(input); - var factor = (max - min)/(minMax.max-minMax.min); - for(var i=0;i< y.length;i++){ - y[i]=(input[i]-minMax.min)*factor+min; - } - } - else{ - var currentMin = Stat.max(input); - var factor = max/currentMin; - for(var i=0;i< y.length;i++){ - y[i] = input[i]*factor; - } - } +KMeansResult.prototype.computeInformation = function (data) { + var enrichedCentroids = this.centroids.map(function (centroid) { + return { + centroid: centroid, + error: 0, + size: 0 + }; + }); + + 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++; } - else{ - if(typeof min === "number"){ - var currentMin = Stat.min(input); - var factor = min/currentMin; - for(var i=0;i< y.length;i++){ - y[i] = input[i]*factor; - } - } + + for (var j = 0; j < this.centroids.length; j++) { + enrichedCentroids[j].error /= enrichedCentroids[j].size; } - return y; -} -module.exports = { - coordArrayToPoints: coordArrayToPoints, - coordArrayToCoordMatrix: coordArrayToCoordMatrix, - coordMatrixToCoordArray: coordMatrixToCoordArray, - coordMatrixToPoints: transpose, - pointsToCoordArray: pointsToCoordArray, - pointsToCoordMatrix: transpose, - applyDotProduct: applyDotProduct, - scale:scale + return new KMeansResult(this.clusters, enrichedCentroids, this.converged, this.iterations, this[distanceSymbol]); }; +module.exports = KMeansResult; /***/ }), -/* 66 */ +/* 179 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const Picker = __webpack_require__(96).Picker; + /** - * - * Function that returns a Number array of equally spaced numberOfPoints - * containing a representation of intensities of the spectra arguments x - * and y. - * - * The options parameter contains an object in the following form: - * from: starting point - * to: last point - * numberOfPoints: number of points between from and to - * variant: "slot" or "smooth" - smooth is the default option - * - * The slot variant consist that each point in the new array is calculated - * averaging the existing points between the slot that belongs to the current - * value. The smooth variant is the same but takes the integral of the range - * of the slot and divide by the step size between two points in the new array. - * - * @param x - sorted increasing x values - * @param y - * @param options - * @returns {Array} new array with the equally spaced data. - * + * 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 + * @return {Array>} - Initial random points */ -function getEquallySpacedData(x, y, options) { - if (x.length>1 && x[0]>x[1]) { - x=x.slice().reverse(); - y=y.slice().reverse(); +function random(data, K) { + const rand = new Picker(data); + var ans = new Array(K); + + for (var i = 0; i < K; ++i) { + ans[i] = rand.pick(); } + return ans; +} - var xLength = x.length; - if(xLength !== y.length) - throw new RangeError("the x and y vector doesn't have the same size."); +/** + * 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 + * @return {Array>} - Initial random points + */ +function mostDistant(data, K, distanceMatrix) { + var ans = new Array(K); - if (options === undefined) options = {}; + // chooses a random point as initial cluster + ans[0] = Math.floor(Math.random() * data.length); - var from = options.from === undefined ? x[0] : options.from - if (isNaN(from) || !isFinite(from)) { - throw new RangeError("'From' value must be a number"); - } - var to = options.to === undefined ? x[x.length - 1] : options.to; - if (isNaN(to) || !isFinite(to)) { - throw new RangeError("'To' value must be a number"); - } + if (K > 1) { + // chooses the more distant point + var maxDist = {dist: -1, index: -1}; + for (var l = 0; l < data.length; ++l) { + if (distanceMatrix[ans[0]][l] > maxDist.dist) { + maxDist.dist = distanceMatrix[ans[0]][l]; + maxDist.index = l; + } + } + ans[1] = maxDist.index; - var reverse = from > to; - if(reverse) { - var temp = from; - from = to; - to = temp; - } + 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) { - var numberOfPoints = options.numberOfPoints === undefined ? 100 : options.numberOfPoints; - if (isNaN(numberOfPoints) || !isFinite(numberOfPoints)) { - throw new RangeError("'Number of points' value must be a number"); - } - if(numberOfPoints < 1) - throw new RangeError("the number of point must be higher than 1"); + // minimum distance to centers + var minDistCent = {dist: Number.MAX_VALUE, index: -1}; + for (var n = 0; n < k; ++n) { + if (distanceMatrix[n][m] < minDistCent.dist && ans.indexOf(m) === -1) { + minDistCent = { + dist: distanceMatrix[n][m], + index: m + }; + } + } - var algorithm = options.variant === "slot" ? "slot" : "smooth"; // default value: smooth + if (minDistCent.dist !== Number.MAX_VALUE && minDistCent.dist > center.dist) { + center = Object.assign({}, minDistCent); + } + } - var output = algorithm === "slot" ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints); + ans[k] = center.index; + } + } + } - return reverse ? output.reverse() : output; + return ans.map((index) => data[index]); } -/** - * function that retrieves the getEquallySpacedData with the variant "smooth" - * - * @param x - * @param y - * @param from - Initial point - * @param to - Final point - * @param numberOfPoints - * @returns {Array} - Array of y's equally spaced with the variant "smooth" - */ -function getEquallySpacedSmooth(x, y, from, to, numberOfPoints) { - var xLength = x.length; - - var step = (to - from) / (numberOfPoints - 1); - var halfStep = step / 2; +exports.random = random; +exports.mostDistant = mostDistant; - var start = from - halfStep; - var output = new Array(numberOfPoints); - var initialOriginalStep = x[1] - x[0]; - var lastOriginalStep = x[x.length - 1] - x[x.length - 2]; +/***/ }), +/* 180 */ +/***/ (function(module, exports, __webpack_require__) { - // Init main variables - var min = start; - var max = start + step; +"use strict"; - 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; +/** +* 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 +*/ - var i = 0; // index of input - var j = 0; // index of output - function getSlope(x0, y0, x1, y1) { - return (y1 - y0) / (x1 - x0); - } +function Node(obj, dimension, parent) { + this.obj = obj; + this.left = null; + this.right = null; + this.parent = parent; + this.dimension = dimension; +} - main: while(true) { - while (nextX - max >= 0) { - // no overlap with original point, just consume current value - var add = integral(0, max - previousX, slope, previousY); - sumAtMax = currentValue + add; +function kdTree(points, metric, dimensions) { - output[j] = (sumAtMax - sumAtMin) / step; - j++; + var self = this; - if (j === numberOfPoints) - break main; + function buildTree(points, depth, parent) { + var dim = depth % dimensions.length, + median, + node; - min = max; - max += step; - sumAtMin = sumAtMax; + if (points.length === 0) { + return null; } - - if(previousX <= min && min <= nextX) { - add = integral(0, min - previousX, slope, previousY); - sumAtMin = currentValue + add; + if (points.length === 1) { + return new Node(points[0], dim, parent); } - currentValue += integral(previousX, nextX, slope, intercept); + points.sort(function (a, b) { + return a[dimensions[dim]] - b[dimensions[dim]]; + }); - previousX = nextX; - previousY = nextY; + median = Math.floor(points.length / 2); + node = new Node(points[median], dim, parent); + node.left = buildTree(points.slice(0, median), depth + 1, node); + node.right = buildTree(points.slice(median + 1), depth + 1, node); - if (i < xLength) { - nextX = x[i]; - nextY = y[i]; - i++; - } else if (i === xLength) { - nextX += lastOriginalStep; - nextY = 0; + return node; + } + + // Reloads a serialied tree + function loadTree (data) { + // Just need to restore the `parent` parameter + self.root = data; + + function restoreParent (root) { + if (root.left) { + root.left.parent = root; + restoreParent(root.left); + } + + if (root.right) { + root.right.parent = root; + restoreParent(root.right); + } } - // updating parameters - slope = getSlope(previousX, previousY, nextX, nextY); - intercept = -slope*previousX + previousY; + + restoreParent(self.root); } - return output; -} + // If points is not an array, assume we're loading a pre-built tree + if (!Array.isArray(points)) loadTree(points, metric, dimensions); + else this.root = buildTree(points, 0, null); -/** - * function that retrieves the getEquallySpacedData with the variant "slot" - * - * @param x - * @param y - * @param from - Initial point - * @param to - Final point - * @param numberOfPoints - * @returns {Array} - Array of y's equally spaced with the variant "slot" - */ -function getEquallySpacedSlot(x, y, from, to, numberOfPoints) { - var xLength = x.length; + // Convert to a JSON serializable structure; this just requires removing + // the `parent` property + this.toJSON = function (src) { + if (!src) src = this.root; + var dest = new Node(src.obj, src.dimension, null); + if (src.left) dest.left = self.toJSON(src.left); + if (src.right) dest.right = self.toJSON(src.right); + return dest; + }; - var step = (to - from) / (numberOfPoints - 1); - var halfStep = step / 2; - var lastStep = x[x.length - 1] - x[x.length - 2]; + this.insert = function (point) { + function innerSearch(node, parent) { - var start = from - halfStep; - var output = new Array(numberOfPoints); + if (node === null) { + return parent; + } - // Init main variables - var min = start; - var max = start + step; + var dimension = dimensions[node.dimension]; + if (point[dimension] < node.obj[dimension]) { + return innerSearch(node.left, node); + } else { + return innerSearch(node.right, node); + } + } - var previousX = -Number.MAX_VALUE; - var previousY = 0; - var nextX = x[0]; - var nextY = y[0]; - var frontOutsideSpectra = 0; - var backOutsideSpectra = true; + var insertPosition = innerSearch(this.root, null), + newNode, + dimension; - var currentValue = 0; + if (insertPosition === null) { + this.root = new Node(point, 0, null); + return; + } - // for slot algorithm - var currentPoints = 0; + newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition); + dimension = dimensions[insertPosition.dimension]; - var i = 1; // index of input - var j = 0; // index of output + if (point[dimension] < insertPosition.obj[dimension]) { + insertPosition.left = newNode; + } else { + insertPosition.right = newNode; + } + }; - main: while(true) { - if (previousX>=nextX) throw (new Error('x must be an increasing serie')); - while (previousX - max > 0) { - // no overlap with original point, just consume current value - if(backOutsideSpectra) { - currentPoints++; - backOutsideSpectra = false; - } + this.remove = function (point) { + var node; - output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints; - j++; + function nodeSearch(node) { + if (node === null) { + return null; + } - if (j === numberOfPoints) - break main; + if (node.obj === point) { + return node; + } - min = max; - max += step; - currentValue = 0; - currentPoints = 0; - } + var dimension = dimensions[node.dimension]; - if(previousX > min) { - currentValue += previousY; - currentPoints++; + if (point[dimension] < node.obj[dimension]) { + return nodeSearch(node.left, node); + } else { + return nodeSearch(node.right, node); + } } - if(previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) - currentPoints--; + function removeNode(node) { + var nextNode, + nextObj, + pDimension; - previousX = nextX; - previousY = nextY; + function findMin(node, dim) { + var dimension, + own, + left, + right, + min; - if (i < xLength) { - nextX = x[i]; - nextY = y[i]; - i++; - } else { - nextX += lastStep; - nextY = 0; - frontOutsideSpectra++; - } - } + if (node === null) { + return null; + } - return output; -} -/** - * Function that calculates the integral of the line between two - * x-coordinates, given the slope and intercept of the line. - * - * @param x0 - * @param x1 - * @param slope - * @param intercept - * @returns {number} integral value. - */ -function integral(x0, x1, slope, intercept) { - return (0.5 * slope * x1 * x1 + intercept * x1) - (0.5 * slope * x0 * x0 + intercept * x0); -} + dimension = dimensions[dim]; -exports.getEquallySpacedData = getEquallySpacedData; -exports.integral = integral; + if (node.dimension === dim) { + if (node.left !== null) { + return findMin(node.left, dim); + } + return node; + } -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { + own = node.obj[dimension]; + left = findMin(node.left, dim); + right = findMin(node.right, dim); + min = node; -"use strict"; + if (left !== null && left.obj[dimension] < own) { + min = left; + } + if (right !== null && right.obj[dimension] < min.obj[dimension]) { + min = right; + } + return min; + } + if (node.left === null && node.right === null) { + if (node.parent === null) { + self.root = null; + return; + } -exports.SNV = SNV; -var Stat = __webpack_require__(2).array; + pDimension = dimensions[node.parent.dimension]; -/** - * Function that applies the standard normal variate (SNV) to an array of values. - * - * @param data - Array of values. - * @returns {Array} - applied the SNV. - */ -function SNV(data) { - var mean = Stat.mean(data); - var std = Stat.standardDeviation(data); - var result = data.slice(); - for (var i = 0; i < data.length; i++) { - result[i] = (result[i] - mean) / std; - } - return result; -} + if (node.obj[pDimension] < node.parent.obj[pDimension]) { + node.parent.left = null; + } else { + node.parent.right = null; + } + return; + } + // If the right subtree is not empty, swap with the minimum element on the + // node's dimension. If it is empty, we swap the left and right subtrees and + // do the same. + if (node.right !== null) { + nextNode = findMin(node.right, node.dimension); + nextObj = nextNode.obj; + removeNode(nextNode); + node.obj = nextObj; + } else { + nextNode = findMin(node.left, node.dimension); + nextObj = nextNode.obj; + removeNode(nextNode); + node.right = node.left; + node.left = null; + node.obj = nextObj; + } -/***/ }), -/* 68 */ -/***/ (function(module, exports) { + } -// auxiliary file to create the 256 look at table elements + node = nodeSearch(self.root); -var ans = new Array(256); -for (var i = 0; i < 256; i++) { - var num = i; - var c = 0; - while (num) { - num = num & (num - 1); - c++; - } - ans[i] = c; -} + if (node === null) { return; } -module.exports = ans; + removeNode(node); + }; -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { + this.nearest = function (point, maxNodes, maxDistance) { + var i, + result, + bestNodes; -"use strict"; + bestNodes = new BinaryHeap( + function (e) { return -e[1]; } + ); -const defaultOptions = { - mode: 'index' -}; + function nearestSearch(node) { + var bestChild, + dimension = dimensions[node.dimension], + ownDistance = metric(point, node.obj), + linearPoint = {}, + linearDistance, + otherChild, + i; -module.exports = function *(M, N, options) { - options = Object.assign({}, defaultOptions, 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; + function saveNode(node, distance) { + bestNodes.push([node, distance]); + if (bestNodes.size() > maxNodes) { + bestNodes.pop(); + } + } - // init a and b - for (var i = 0; i < N; i++) { - a[i] = i; - if (i < N - M) b[i] = 0; - else b[i] = 1; - } + 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]]; + } + } - // init c - for (i = 0; i < M; i++) { - c[i] = N - M + i; - } + linearDistance = metric(linearPoint, node.obj); - // 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 (node.right === null && node.left === null) { + if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { + saveNode(node, ownDistance); + } + return; + } - 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; + if (node.right === null) { + bestChild = node.left; + } else if (node.left === null) { + bestChild = node.right; } else { - if (i === p[0]) { - return 0; + if (point[dimension] < node.obj[dimension]) { + bestChild = node.left; + } else { + bestChild = node.right; + } + } + + nearestSearch(bestChild); + + if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { + saveNode(node, ownDistance); + } + + if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) { + if (bestChild === node.left) { + otherChild = node.right; } else { - p[j] = p[i]; - z = p[i] - 1; - p[i] = 0; - x = j - 1; - y = i - 1; + otherChild = node.left; + } + if (otherChild !== null) { + nearestSearch(otherChild); } } } - return 1; - } - if (options.mode === 'index') { - yield c.slice(); - while (twiddle()) { - c[z] = a[x]; - yield c.slice(); - } - } else if (options.mode === 'mask') { - yield b.slice(); - while (twiddle()) { - b[x] = 1; - b[y] = 0; - yield b.slice(); + if (maxDistance) { + for (i = 0; i < maxNodes; i += 1) { + bestNodes.push([null, maxDistance]); + } } - } else { - throw new Error('Invalid mode'); - } -}; + if(self.root) + nearestSearch(self.root); -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + 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; + }; -/** - * ConfusionMatrix class - */ -class ConfusionMatrix { - /** - * Constructor - * @param {Array} matrix - The confusion matrix, a 2D Array - * @param {Array} labels - Labels of the confusion matrix, a 1D Array - */ - constructor(matrix, labels) { - if (matrix.length !== matrix[0].length) { - throw new Error('Confusion matrix must be square'); + this.balanceFactor = function () { + function height(node) { + if (node === null) { + return 0; + } + return Math.max(height(node.left), height(node.right)) + 1; } - if (labels.length !== matrix.length) { - throw new Error('Confusion matrix and labels should have the same length'); + + function count(node) { + if (node === null) { + return 0; + } + return count(node.left) + count(node.right) + 1; } - this.labels = labels; - this.matrix = matrix; - } + return height(self.root) / (Math.log(count(self.root)) / Math.log(2)); + }; +} - /** - * Compute the general prediction accuracy - * @returns {number} - The prediction accuracy ([0-1] - */ - get accuracy() { - var correct = 0, incorrect = 0; - for (var i = 0; i < this.matrix.length; i++) { - for (var j = 0; j < this.matrix.length; j++) { - if (i === j) correct += this.matrix[i][j]; - else incorrect += this.matrix[i][j]; - } +// Binary heap implementation from: +// http://eloquentjavascript.net/appendix2.html + +function BinaryHeap(scoreFunction){ + this.content = []; + this.scoreFunction = scoreFunction; +} + +BinaryHeap.prototype = { + push: function(element) { + // Add the new element to the end of the array. + this.content.push(element); + // Allow it to bubble up. + this.bubbleUp(this.content.length - 1); + }, + + pop: function() { + // Store the first element so we can return it later. + var result = this.content[0]; + // Get the element at the end of the array. + var end = this.content.pop(); + // If there are any elements left, put the end element at the + // start, and let it sink down. + if (this.content.length > 0) { + this.content[0] = end; + this.sinkDown(0); } + return result; + }, - return correct / (correct + incorrect); - } + peek: function() { + return this.content[0]; + }, - /** - * Compute the number of predicted observations - * @returns {number} - The number of predicted observations - */ - get nbPredicted() { - var predicted = 0; - for (var i = 0; i < this.matrix.length; i++) { - for (var j = 0; j < this.matrix.length; j++) { - predicted += this.matrix[i][j]; + remove: function(node) { + var len = this.content.length; + // To remove a value, we must search through the array to find + // it. + for (var i = 0; i < len; i++) { + if (this.content[i] == node) { + // When it is found, the process seen in 'pop' is repeated + // to fill up the hole. + var end = this.content.pop(); + if (i != len - 1) { + this.content[i] = end; + if (this.scoreFunction(end) < this.scoreFunction(node)) + this.bubbleUp(i); + else + this.sinkDown(i); + } + return; } } - return predicted; - } -} + throw new Error("Node not found."); + }, -module.exports = ConfusionMatrix; + size: function() { + return this.content.length; + }, + bubbleUp: function(n) { + // Fetch the element that has to be moved. + var element = this.content[n]; + // When at 0, an element can not go up any further. + while (n > 0) { + // Compute the parent element's index, and fetch it. + var parentN = Math.floor((n + 1) / 2) - 1, + parent = this.content[parentN]; + // Swap the elements if the parent is greater. + if (this.scoreFunction(element) < this.scoreFunction(parent)) { + this.content[parentN] = element; + this.content[n] = parent; + // Update 'n' to continue at the new position. + n = parentN; + } + // Found a parent that is less, no need to move it further. + else { + break; + } + } + }, -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { + sinkDown: function(n) { + // Look up the target element and its score. + var length = this.content.length, + element = this.content[n], + elemScore = this.scoreFunction(element); -/** - * Created by acastillo on 8/5/15. - */ -var Matrix = __webpack_require__(0); -var math = __webpack_require__(22); + while(true) { + // Compute the indices of the child elements. + var child2N = (n + 1) * 2, 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], + 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], + child2Score = this.scoreFunction(child2); + if (child2Score < (swap == null ? elemScore : child1Score)){ + swap = child2N; + } + } -var DEBUG = false; -/** Levenberg Marquardt curve-fitting: minimize sum of weighted squared residuals - ---------- INPUT VARIABLES ----------- - func = function of n independent variables, 't', and m parameters, 'p', - returning the simulated model: y_hat = func(t,p,c) - p = n-vector of initial guess of parameter values - t = m-vectors or matrix of independent variables (used as arg to func) - y_dat = m-vectors or matrix of data to be fit by func(t,p) - weight = weighting vector for least squares fit ( weight >= 0 ) ... - inverse of the standard measurement errors - Default: sqrt(d.o.f. / ( y_dat' * y_dat )) - dp = fractional increment of 'p' for numerical derivatives - dp(j)>0 central differences calculated - dp(j)<0 one sided 'backwards' differences calculated - dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed - Default: 0.001; - p_min = n-vector of lower bounds for parameter values - p_max = n-vector of upper bounds for parameter values - c = an optional matrix of values passed to func(t,p,c) - opts = vector of algorithmic parameters - parameter defaults meaning - opts(1) = prnt 3 >1 intermediate results; >2 plots - opts(2) = MaxIter 10*Npar maximum number of iterations - opts(3) = epsilon_1 1e-3 convergence tolerance for gradient - opts(4) = epsilon_2 1e-3 convergence tolerance for parameters - opts(5) = epsilon_3 1e-3 convergence tolerance for Chi-square - opts(6) = epsilon_4 1e-2 determines acceptance of a L-M step - opts(7) = lambda_0 1e-2 initial value of L-M paramter - opts(8) = lambda_UP_fac 11 factor for increasing lambda - opts(9) = lambda_DN_fac 9 factor for decreasing lambda - opts(10) = Update_Type 1 1: Levenberg-Marquardt lambda update - 2: Quadratic update - 3: Nielsen's lambda update equations + // If the element needs to be moved, swap it, and continue. + if (swap != null) { + this.content[n] = this.content[swap]; + this.content[swap] = element; + n = swap; + } + // Otherwise, we are done. + else { + break; + } + } + } +}; - ---------- OUTPUT VARIABLES ----------- - p = least-squares optimal estimate of the parameter values - X2 = Chi squared criteria - sigma_p = asymptotic standard error of the parameters - sigma_y = asymptotic standard error of the curve-fit - corr = correlation matrix of the parameters - R_sq = R-squared cofficient of multiple determination - cvg_hst = convergence history +this.kdTree = kdTree; - Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. 22 Sep 2013 - modified from: http://octave.sourceforge.net/optim/function/leasqr.html - using references by - Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15. - Sam Roweis http://www.cs.toronto.edu/~roweis/notes/lm.pdf - Manolis Lourakis http://www.ics.forth.gr/~lourakis/levmar/levmar.pdf - Hans Nielson http://www2.imm.dtu.dk/~hbn/publ/TR9905.ps - Mathworks optimization toolbox reference manual - K. Madsen, H.B., Nielsen, and O. Tingleff - http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf - */ -var LM = { +exports.kdTree = kdTree; +exports.BinaryHeap = BinaryHeap; - optimize: function(func,p,t,y_dat,weight,dp,p_min,p_max,c,opts){ - var tensor_parameter = 0; // set to 1 of parameter is a tensor +/***/ }), +/* 181 */ +/***/ (function(module, exports, __webpack_require__) { - var iteration = 0; // iteration counter - //func_calls = 0; // running count of function evaluations +"use strict"; - if((typeof p[0])!="object"){ - for(var i=0;i< p.length;i++){ - p[i]=[p[i]]; - } - } - //p = p(:); y_dat = y_dat(:); // make column vectors - var i,k; - var eps = 2^-52; - var Npar = p.length;//length(p); // number of parameters - var Npnt = y_dat.length;//length(y_dat); // number of data points - var p_old = Matrix.zeros(Npar,1); // previous set of parameters - var y_old = Matrix.zeros(Npnt,1); // previous model, y_old = y_hat(t;p_old) - var X2 = 1e-2/eps; // a really big initial Chi-sq value - var X2_old = 1e-2/eps; // a really big initial Chi-sq value - var J = Matrix.zeros(Npnt,Npar); +module.exports = KNN; +var KDTree = __webpack_require__(180).kdTree; +var Distances = __webpack_require__(41); - if (t.length != y_dat.length) { - console.log('lm.m error: the length of t must equal the length of y_dat'); +/** + * K-Nearest neighboor constructor. + * + * @param reload - loading purposes. + * @param model - loading purposes + * @constructor + */ +function KNN(reload, model) { + if(reload) { + this.kdtree = model.kdtree; + this.k = model.k; + this.classes = model.classes; + } +} - length_t = t.length; - length_y_dat = y_dat.length; - var X2 = 0, corr = 0, sigma_p = 0, sigma_y = 0, R_sq = 0, cvg_hist = 0; - if (!tensor_parameter) { - return; - } +/** + * Function that trains the KNN with the given trainingSet and trainingLabels. + * The third argument is an object with the following options. + * * distance: that represent the distance function applied (default: euclidean) + * * k: the number of neighboors to take in count for classify (default: number of features + 1) + * + * @param trainingSet + * @param trainingLabels + * @param options + */ +KNN.prototype.train = function (trainingSet, trainingLabels, options) { + if(options === undefined) options = {}; + if(options.distance === undefined) options.distance = Distances.distance.euclidean; + if(options.k === undefined) options.k = trainingSet[0].length + 1; + + var classes = 0; + var exist = new Array(1000); + var j = 0; + for(var i = 0; i < trainingLabels.length; ++i) { + if(exist.indexOf(trainingLabels[i]) === -1) { + classes++; + exist[j] = trainingLabels[i]; + j++; } + } - weight = weight||Math.sqrt((Npnt-Npar+1)/(math.multiply(math.transpose(y_dat),y_dat))); - dp = dp || 0.001; - p_min = p_min || math.multiply(Math.abs(p),-100); - p_max = p_max || math.multiply(Math.abs(p),100); - c = c || 1; - // Algorithmic Paramters - //prnt MaxIter eps1 eps2 epx3 eps4 lam0 lamUP lamDN UpdateType - opts = opts ||[ 3,10*Npar, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 1 ]; + // copy dataset + var points = new Array(trainingSet.length); + for(i = 0; i < points.length; ++i) { + points[i] = trainingSet[i].slice(); + } - var prnt = opts[0]; // >1 intermediate results; >2 plots - var MaxIter = opts[1]; // maximum number of iterations - var epsilon_1 = opts[2]; // convergence tolerance for gradient - var epsilon_2 = opts[3]; // convergence tolerance for parameter - var epsilon_3 = opts[4]; // convergence tolerance for Chi-square - var epsilon_4 = opts[5]; // determines acceptance of a L-M step - var lambda_0 = opts[6]; // initial value of damping paramter, lambda - var lambda_UP_fac = opts[7]; // factor for increasing lambda - var lambda_DN_fac = opts[8]; // factor for decreasing lambda - var Update_Type = opts[9]; // 1: Levenberg-Marquardt lambda update - // 2: Quadratic update - // 3: Nielsen's lambda update equations + this.features = trainingSet[0].length; + for(i = 0; i < trainingLabels.length; ++i) { + points[i].push(trainingLabels[i]); + } - if ( tensor_parameter && prnt == 3 ) prnt = 2; + var dimensions = new Array(trainingSet[0].length); + for(i = 0; i < dimensions.length; ++i) { + dimensions[i] = i; + } + this.kdtree = new KDTree(points, options.distance, dimensions); + this.k = options.k; + this.classes = classes; +}; - if(!dp.length || dp.length == 1){ - var dp_array = new Array(Npar); - for(var i=0;i maxPoints) { + predictedClass = currentClass; + maxPoints = currentPoints; + } + } - // initialize Jacobian with finite difference calculation - //console.log("J "+weight_sq); - var result = this.lm_matx(func,t,p_old,y_old,1,J,p,y_dat,weight_sq,dp,c); - var JtWJ = result.JtWJ,JtWdy=result.JtWdy,X2=result.Chi_sq,y_hat=result.y_hat,J=result.J; - //[JtWJ,JtWdy,X2,y_hat,J] = this.lm_matx(func,t,p_old,y_old,1,J,p,y_dat,weight_sq,dp,c); - //console.log(JtWJ); + return predictedClass; +}; - if ( Math.max(Math.abs(JtWdy)) < epsilon_1 ){ - console.log(' *** Your Initial Guess is Extremely Close to Optimal ***') - console.log(' *** epsilon_1 = ', epsilon_1); - stop = true; - } +/** + * function that returns a KNN classifier with the given model. + * + * @param model + */ +KNN.load = function (model) { + if(model.modelName !== "KNN") + throw new RangeError("The given model is invalid!"); + return new KNN(true, model); +}; - switch(Update_Type){ - case 1: // Marquardt: init'l lambda - lambda = lambda_0; - break; - default: // Quadratic and Nielsen - lambda = lambda_0 * Math.max(math.diag(JtWJ)); - nu=2; - } - //console.log(X2); - X2_old = X2; // previous value of X2 - //console.log(MaxIter+" "+Npar); - //var cvg_hst = Matrix.ones(MaxIter,Npar+3); // initialize convergence history - var h = null; - while ( !stop && iteration <= MaxIter ) { // --- Main Loop - iteration = iteration + 1; - // incremental change in parameters - switch(Update_Type){ - case 1: // Marquardt - //h = ( JtWJ + lambda * math.diag(math.diag(JtWJ)) ) \ JtWdy; - //h = math.multiply(math.inv(JtWdy),math.add(JtWJ,math.multiply(lambda,math.diag(math.diag(Npar))))); - h = math.solve(math.add(JtWJ,math.multiply(math.diag(math.diag(JtWJ)),lambda)),JtWdy); - break; - default: // Quadratic and Nielsen - //h = ( JtWJ + lambda * math.eye(Npar) ) \ JtWdy; +/** + * function that exports the current KNN classifier. + */ +KNN.prototype.export = function () { + return { + modelName: "KNN", + kdtree: this.kdtree, + k: this.k, + classes: this.classes + }; +}; - h = math.solve(math.add(JtWJ,math.multiply( Matrix.eye(Npar),lambda)),JtWdy); - } +/***/ }), +/* 182 */ +/***/ (function(module, exports, __webpack_require__) { - /*for(var k=0;k< h.length;k++){ - h[k]=[h[k]]; - }*/ - //console.log("h "+h); - //h=math.matrix(h); - // big = max(abs(h./p)) > 2; - //this is a big step - // --- Are parameters [p+h] much better than [p] ? - var hidx = new Array(idx.length); - for(k=0;k, 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 X2_try = math.multiply(math.transpose(delta_y),math.dotMultiply(delta_y,weight_sq)); + for (var i = 0; i < data.x.length; i++) { + error += Math.abs(data.y[i] - func(data.x[i])); + } - if ( Update_Type == 2 ){ // Quadratic - // One step of quadratic line update in the h direction for minimum X2 - //var alpha = JtWdy'*h / ( (X2_try - X2)/2 + 2*JtWdy'*h ) ; - var JtWdy_th = math.multiply(math.transpose(JtWdy),h); - var alpha = math.multiply(JtWdy_th,math.inv(math.add(math.multiply(math.subtract(X2_try - X2),1/2)),math.multiply(JtWdy_th,2)));//JtWdy'*h / ( (X2_try - X2)/2 + 2*JtWdy'*h ) ; + return error; +} - h = math.multiply(alpha, h); - for(var k=0;k epsilon_4 ) { // it IS significantly better - //console.log("Here"); - dX2 = X2 - X2_old; - X2_old = X2; - p_old = p; - y_old = y_hat; - p = p_try; // accept p_try +"use strict"; - result = this.lm_matx(func, t, p_old, y_old, dX2, J, p, y_dat, weight_sq, dp, c); - JtWJ = result.JtWJ,JtWdy=result.JtWdy,X2=result.Chi_sq,y_hat=result.y_hat,J=result.J; - // decrease lambda ==> Gauss-Newton method - switch (Update_Type) { - case 1: // Levenberg - lambda = Math.max(lambda / lambda_DN_fac, 1.e-7); - break; - case 2: // Quadratic - lambda = Math.max(lambda / (1 + alpha), 1.e-7); - break; - case 3: // Nielsen - lambda = math.multiply(Math.max(1 / 3, 1 - (2 * rho - 1) ^ 3),lambda); - nu = 2; - break; - } - } - else { // it IS NOT better - X2 = X2_old; // do not accept p_try - if (iteration%(2 * Npar)==0) { // rank-1 update of Jacobian - result = this.lm_matx(func, t, p_old, y_old, -1, J, p, y_dat, weight_sq, dp, c); - JtWJ = result.JtWJ,JtWdy=result.JtWdy,dX2=result.Chi_sq,y_hat=result.y_hat,J=result.J; - } +const Matrix = __webpack_require__(0); - // increase lambda ==> gradient descent method - switch (Update_Type) { - case 1: // Levenberg - lambda = Math.min(lambda * lambda_UP_fac, 1.e7); - break; - case 2: // Quadratic - lambda = lambda + Math.abs((X2_try - X2) / 2 / alpha); - break; - case 3: // Nielsen - lambda = lambda * nu; - nu = 2 * nu; - break; - } - } - }// --- End of Main Loop +/** + * 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} params - Array of previous parameter values + * @param {number} gradientDifference - Adjustment for decrease the damping parameter + * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter + * @return {Matrix} + */ +function gradientFunction(data, params, gradientDifference, paramFunction) { + const n = paramFunction.length; + const m = data.x.length; - // --- convergence achieved, find covariance and confidence intervals + var ans = new Array(n); + const func = paramFunction(...params); - // equal weights for paramter error analysis - weight_sq = math.multiply(math.multiply(math.transpose(delta_y),delta_y), Matrix.ones(Npnt,1)); + for (var param = 0; param < n; param++) { + ans[param] = new Array(m); - weight_sq.apply(function(i,j){ - weight_sq[i][j] = (Npnt-Nfit+1)/weight_sq[i][j]; - }); - //console.log(weight_sq); - result = this.lm_matx(func,t,p_old,y_old,-1,J,p,y_dat,weight_sq,dp,c); - JtWJ = result.JtWJ,JtWdy=result.JtWdy,X2=result.Chi_sq,y_hat=result.y_hat,J=result.J; + var auxParams = params.concat(); + auxParams[param] += gradientDifference; + var funcParam = paramFunction(...auxParams); - /*if nargout > 2 // standard error of parameters - covar = inv(JtWJ); - sigma_p = sqrt(diag(covar)); - end + for (var point = 0; point < m; point++) { + ans[param][point] = func(data.x[point]) - funcParam(data.x[point]); + } + } - if nargout > 3 // standard error of the fit - // sigma_y = sqrt(diag(J * covar * J')); // slower version of below - sigma_y = zeros(Npnt,1); - for i=1:Npnt - sigma_y(i) = J(i,:) * covar * J(i,:)'; - end - sigma_y = sqrt(sigma_y); - end + return new Matrix(ans); +} - if nargout > 4 // parameter correlation matrix - corr = covar ./ [sigma_p*sigma_p']; - end +/** + * 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} params - Array of previous parameter values + * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter + * @return {Matrix} + */ +function matrixFunction(data, params, paramFunction) { + const m = data.x.length; - if nargout > 5 // coefficient of multiple determination - R_sq = corrcoef([y_dat y_hat]); - R_sq = R_sq(1,2).^2; - end + var ans = new Array(m); + const func = paramFunction(...params); - if nargout > 6 // convergence history - cvg_hst = cvg_hst(1:iteration,:); - end*/ + for (var point = 0; point < m; point++) { + ans[point] = data.y[point] - func(data.x[point]); + } - // endfunction # ---------------------------------------------------------- LM + return new Matrix([ans]); +} - return { p:p, X2:X2}; - }, +/** + * 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(data, params, damping, gradientDifference, parameterizedFunction) { + var identity = Matrix.eye(parameterizedFunction.length) + .mul(damping * gradientDifference * gradientDifference); + var gradientFunc = gradientFunction(data, params, gradientDifference, parameterizedFunction); + var matrixFunc = matrixFunction(data, params, parameterizedFunction).transpose(); + params = new Matrix([params]); - lm_FD_J:function(func,t,p,y,dp,c) { - // J = lm_FD_J(func,t,p,y,{dp},{c}) - // - // partial derivatives (Jacobian) dy/dp for use with lm.m - // computed via Finite Differences - // Requires n or 2n function evaluations, n = number of nonzero values of dp - // -------- INPUT VARIABLES --------- - // func = function of independent variables, 't', and parameters, 'p', - // returning the simulated model: y_hat = func(t,p,c) - // t = m-vector of independent variables (used as arg to func) - // p = n-vector of current parameter values - // y = func(t,p,c) n-vector initialised by user before each call to lm_FD_J - // dp = fractional increment of p for numerical derivatives - // dp(j)>0 central differences calculated - // dp(j)<0 one sided differences calculated - // dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed - // Default: 0.001; - // c = optional vector of constants passed to y_hat = func(t,p,c) - //---------- OUTPUT VARIABLES ------- - // J = Jacobian Matrix J(i,j)=dy(i)/dp(j) i=1:n; j=1:m + var inverse = Matrix.inv(identity.add(gradientFunc.mmul(gradientFunc.transposeView()))); + params = params.sub( + ((inverse.mmul(gradientFunc)).mmul(matrixFunc).mul(gradientDifference)).transposeView() + ); + return params.to1DArray(); +} - // Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. November 2005 - // modified from: ftp://fly.cnuce.cnr.it/pub/software/octave/leasqr/ - // Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15. +module.exports = step; - var m = y.length; // number of data points - var n = p.length; // number of parameters - dp = dp || math.multiply( Matrix.ones(n, 1), 0.001); +/***/ }), +/* 184 */ +/***/ (function(module, exports, __webpack_require__) { - var ps = p.clone();//JSON.parse(JSON.stringify(p)); - //var ps = $.extend(true, [], p); - var J = new Matrix(m,n), del =new Array(n); // initialize Jacobian to Zero +"use strict"; - for (var j = 0;j < n; j++) { - //console.log(j+" "+dp[j]+" "+p[j]+" "+ps[j]+" "+del[j]); - del[j] = dp[j]*(1+Math.abs(p[j][0])); // parameter perturbation - p[j] = [ps[j][0]+del[j]]; // perturb parameter p(j) - //console.log(j+" "+dp[j]+" "+p[j]+" "+ps[j]+" "+del[j]); - if (del[j] != 0){ - y1 = func(t, p, c); - //func_calls = func_calls + 1; - if (dp[j][0] < 0) { // backwards difference - //J(:,j) = math.dotDivide(math.subtract(y1, y),del[j]);//. / del[j]; - //console.log(del[j]); - //console.log(y); - var column = math.dotDivide(math.subtract(y1, y),del[j]); - for(var k=0;k< m;k++){ - J[k][j]=column[k][0]; - } - //console.log(column); - } - else{ - p[j][0] = ps[j][0] - del[j]; - //J(:,j) = (y1 - feval(func, t, p, c)). / (2. * del[j]); - var column = math.dotDivide(math.subtract(y1,func(t,p,c)),2*del[j]); - for(var k=0;k< m;k++){ - J[k][j]=column[k][0]; - } +var Matrix = __webpack_require__(4).Matrix; + +// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs +function CholeskyDecomposition(value) { + if (!(this instanceof CholeskyDecomposition)) { + return new CholeskyDecomposition(value); + } + value = Matrix.checkMatrix(value); + if (!value.isSymmetric()) { + throw new Error('Matrix is not symmetric'); + } + + var a = value, + dimension = a.rows, + l = new Matrix(dimension, dimension), + positiveDefinite = true, + i, j, k; + + for (j = 0; j < dimension; j++) { + var Lrowj = l[j]; + var d = 0; + for (k = 0; k < j; k++) { + var Lrowk = l[k]; + var s = 0; + for (i = 0; i < k; i++) { + s += Lrowk[i] * Lrowj[i]; + } + Lrowj[k] = s = (a[j][k] - s) / l[k][k]; + d = d + s * s; + } + + d = a[j][j] - d; + + positiveDefinite &= (d > 0); + l[j][j] = Math.sqrt(Math.max(d, 0)); + for (k = j + 1; k < dimension; k++) { + l[j][k] = 0; + } + } + + if (!positiveDefinite) { + throw new Error('Matrix is not positive definite'); + } + + this.L = l; +} - } // central difference, additional func call - } +CholeskyDecomposition.prototype = { + get lowerTriangularMatrix() { + return this.L; + }, + solve: function (value) { + value = Matrix.checkMatrix(value); - p[j] = ps[j]; // restore p(j) + var l = this.L, + dimension = l.rows; + if (value.rows !== dimension) { + throw new Error('Matrix dimensions do not match'); } - //console.log("lm_FD_J: "+ JSON.stringify(J)); - return J; - }, + var count = value.columns, + B = value.clone(), + i, j, k; - // endfunction # -------------------------------------------------- LM_FD_J - lm_Broyden_J: function(p_old,y_old,J,p,y){ - // J = lm_Broyden_J(p_old,y_old,J,p,y) - // carry out a rank-1 update to the Jacobian matrix using Broyden's equation - //---------- INPUT VARIABLES ------- - // p_old = previous set of parameters - // y_old = model evaluation at previous set of parameters, y_hat(t;p_old) - // J = current version of the Jacobian matrix - // p = current set of parameters - // y = model evaluation at current set of parameters, y_hat(t;p) - //---------- OUTPUT VARIABLES ------- - // J = rank-1 update to Jacobian Matrix J(i,j)=dy(i)/dp(j) i=1:n; j=1:m - //console.log(p+" X "+ p_old) - var h = math.subtract(p, p_old); + for (k = 0; k < dimension; k++) { + for (j = 0; j < count; j++) { + for (i = 0; i < k; i++) { + B[k][j] -= B[i][j] * l[k][i]; + } + B[k][j] /= l[k][k]; + } + } - //console.log("hhh "+h); - var h_t = math.transpose(h); - h_t.div(math.multiply(h_t,h)); + for (k = dimension - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + for (i = k + 1; i < dimension; i++) { + B[k][j] -= B[i][j] * l[i][k]; + } + B[k][j] /= l[k][k]; + } + } - //console.log(h_t); - //J = J + ( y - y_old - J*h )*h' / (h'*h); // Broyden rank-1 update eq'n - J = math.add(J, math.multiply(math.subtract(y, math.add(y_old,math.multiply(J,h))),h_t)); - return J; - // endfunction # ---------------------------------------------- LM_Broyden_J - }, + return B; + } +}; - lm_matx : function (func,t,p_old,y_old,dX2,J,p,y_dat,weight_sq,dp,c,iteration){ - // [JtWJ,JtWdy,Chi_sq,y_hat,J] = this.lm_matx(func,t,p_old,y_old,dX2,J,p,y_dat,weight_sq,{da},{c}) - // - // Evaluate the linearized fitting matrix, JtWJ, and vector JtWdy, - // and calculate the Chi-squared error function, Chi_sq - // Used by Levenberg-Marquard algorithm, lm.m - // -------- INPUT VARIABLES --------- - // func = function ofpn independent variables, p, and m parameters, p, - // returning the simulated model: y_hat = func(t,p,c) - // t = m-vectors or matrix of independent variables (used as arg to func) - // p_old = n-vector of previous parameter values - // y_old = m-vector of previous model ... y_old = y_hat(t;p_old); - // dX2 = previous change in Chi-squared criteria - // J = m-by-n Jacobian of model, y_hat, with respect to parameters, p - // p = n-vector of current parameter values - // y_dat = n-vector of data to be fit by func(t,p,c) - // weight_sq = square of the weighting vector for least squares fit ... - // inverse of the standard measurement errors - // dp = fractional increment of 'p' for numerical derivatives - // dp(j)>0 central differences calculated - // dp(j)<0 one sided differences calculated - // dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed - // Default: 0.001; - // c = optional vector of constants passed to y_hat = func(t,p,c) - //---------- OUTPUT VARIABLES ------- - // JtWJ = linearized Hessian matrix (inverse of covariance matrix) - // JtWdy = linearized fitting vector - // Chi_sq = Chi-squared criteria: weighted sum of the squared residuals WSSR - // y_hat = model evaluated with parameters 'p' - // J = m-by-n Jacobian of model, y_hat, with respect to parameters, p +module.exports = CholeskyDecomposition; - // Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. November 2005 - // modified from: ftp://fly.cnuce.cnr.it/pub/software/octave/leasqr/ - // Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15. +/***/ }), +/* 185 */ +/***/ (function(module, exports, __webpack_require__) { - var Npnt = y_dat.length; // number of data points - var Npar = p.length; // number of parameters +"use strict"; - dp = dp || 0.001; +const Matrix = __webpack_require__(4).Matrix; +const util = __webpack_require__(26); +const hypotenuse = util.hypotenuse; +const getFilled2DArray = util.getFilled2DArray; - //var JtWJ = new Matrix.zeros(Npar); - //var JtWdy = new Matrix.zeros(Npar,1); +const defaultOptions = { + assumeSymmetric: false +}; - var y_hat = func(t,p,c); // evaluate model using parameters 'p' - //func_calls = func_calls + 1; - //console.log(J); - if ( (iteration%(2*Npar))==0 || dX2 > 0 ) { - //console.log("Par"); - J = this.lm_FD_J(func, t, p, y_hat, dp, c); // finite difference - } - else{ - //console.log("ImPar"); - J = this.lm_Broyden_J(p_old, y_old, J, p, y_hat); // rank-1 update - } - //console.log(y_dat); - //console.log(y_hat); - var delta_y = math.subtract(y_dat, y_hat); // residual error between model and data - //console.log(delta_y[0][0]); - //console.log(delta_y.rows+" "+delta_y.columns+" "+JSON.stringify(weight_sq)); - //var Chi_sq = delta_y' * ( delta_y .* weight_sq ); // Chi-squared error criteria - var Chi_sq = math.multiply(math.transpose(delta_y),math.dotMultiply(delta_y,weight_sq)); - //JtWJ = J' * ( J .* ( weight_sq * ones(1,Npar) ) ); - var Jt = math.transpose(J); +// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs +function EigenvalueDecomposition(matrix, options) { + options = Object.assign({}, defaultOptions, options); + if (!(this instanceof EigenvalueDecomposition)) { + return new EigenvalueDecomposition(matrix, options); + } + matrix = Matrix.checkMatrix(matrix); + if (!matrix.isSquare()) { + throw new Error('Matrix is not a square matrix'); + } - //console.log(weight_sq); + var n = matrix.columns, + V = getFilled2DArray(n, n, 0), + d = new Array(n), + e = new Array(n), + value = matrix, + i, j; - var JtWJ = math.multiply(Jt, math.dotMultiply(J,math.multiply(weight_sq, Matrix.ones(1,Npar)))); + var isSymmetric = false; + if (options.assumeSymmetric) { + isSymmetric = true; + } else { + isSymmetric = matrix.isSymmetric(); + } - //JtWdy = J' * ( weight_sq .* delta_y ); - var JtWdy = math.multiply(Jt, math.dotMultiply(weight_sq,delta_y)); + if (isSymmetric) { + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = value.get(i, j); + } + } + tred2(n, e, d, V); + tql2(n, e, d, V); + } else { + var H = getFilled2DArray(n, n, 0), + ort = new Array(n); + for (j = 0; j < n; j++) { + for (i = 0; i < n; i++) { + H[i][j] = value.get(i, j); + } + } + orthes(n, H, ort, V); + hqr2(n, e, d, V, H); + } + this.n = n; + this.e = e; + this.d = d; + this.V = V; +} - return {JtWJ:JtWJ,JtWdy:JtWdy,Chi_sq:Chi_sq,y_hat:y_hat,J:J}; - // endfunction # ------------------------------------------------------ LM_MATX +EigenvalueDecomposition.prototype = { + get realEigenvalues() { + return this.d; + }, + get imaginaryEigenvalues() { + return this.e; + }, + get eigenvectorMatrix() { + if (!Matrix.isMatrix(this.V)) { + this.V = new Matrix(this.V); + } + return this.V; + }, + get diagonalMatrix() { + var n = this.n, + e = this.e, + d = this.d, + X = new Matrix(n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + X[i][j] = 0; + } + X[i][i] = d[i]; + if (e[i] > 0) { + X[i][i + 1] = e[i]; + } else if (e[i] < 0) { + X[i][i - 1] = e[i]; + } + } + return X; } +}; +function tred2(n, e, d, V) { + var f, g, h, i, j, k, + hh, scale; -}; + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + } -module.exports = LM; + for (i = n - 1; i > 0; i--) { + scale = 0; + h = 0; + for (k = 0; k < i; k++) { + scale = scale + Math.abs(d[k]); + } -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { + if (scale === 0) { + e[i] = d[i - 1]; + for (j = 0; j < i; j++) { + d[j] = V[i - 1][j]; + V[i][j] = 0; + V[j][i] = 0; + } + } else { + for (k = 0; k < i; k++) { + d[k] /= scale; + h += d[k] * d[k]; + } -"use strict"; + f = d[i - 1]; + g = Math.sqrt(h); + if (f > 0) { + g = -g; + } + e[i] = scale * g; + h = h - f * g; + d[i - 1] = f - g; + for (j = 0; j < i; j++) { + e[j] = 0; + } -exports.additiveSymmetric = __webpack_require__(73); -exports.avg = __webpack_require__(74); -exports.bhattacharyya = __webpack_require__(75); -exports.canberra = __webpack_require__(76); -exports.chebyshev = __webpack_require__(77); -exports.clark = __webpack_require__(78); -exports.czekanowski = __webpack_require__(79); -exports.dice = __webpack_require__(23); -exports.divergence = __webpack_require__(80); -exports.euclidean = __webpack_require__(1); -exports.fidelity = __webpack_require__(81); -exports.gower = __webpack_require__(82); -exports.harmonicMean = __webpack_require__(83); -exports.hellinger = __webpack_require__(84); -exports.innerProduct = __webpack_require__(85); -exports.intersection = __webpack_require__(24); -exports.jaccard = __webpack_require__(25); -exports.jeffreys = __webpack_require__(86); -exports.jensenDifference = __webpack_require__(87); -exports.jensenShannon = __webpack_require__(88); -exports.kdivergence = __webpack_require__(89); -exports.kulczynski = __webpack_require__(26); -exports.kullbackLeibler = __webpack_require__(90); -exports.kumarHassebrook = __webpack_require__(91); -exports.kumarJohnson = __webpack_require__(92); -exports.lorentzian = __webpack_require__(93); -exports.manhattan = __webpack_require__(94); -exports.matusita = __webpack_require__(95); -exports.minkowski = __webpack_require__(96); -exports.motyka = __webpack_require__(27); -exports.neyman = __webpack_require__(97); -exports.pearson = __webpack_require__(98); -exports.probabilisticSymmetric = __webpack_require__(99); -exports.ruzicka = __webpack_require__(100); -exports.soergel = __webpack_require__(101); -exports.sorensen = __webpack_require__(102); -exports.squared = __webpack_require__(103); -exports.squaredChord = __webpack_require__(28); -exports.squaredEuclidean = __webpack_require__(1).squared; -exports.taneja = __webpack_require__(104); -exports.tanimoto = __webpack_require__(105); -exports.topsoe = __webpack_require__(106); -exports.tree = __webpack_require__(161); -exports.waveHedges = __webpack_require__(107); + for (j = 0; j < i; j++) { + f = d[j]; + V[j][i] = f; + g = e[j] + V[j][j] * f; + for (k = j + 1; k <= i - 1; k++) { + g += V[k][j] * d[k]; + e[k] += V[k][j] * f; + } + e[j] = g; + } + f = 0; + for (j = 0; j < i; j++) { + e[j] /= h; + f += e[j] * d[j]; + } -/***/ }), -/* 73 */ -/***/ (function(module, exports) { + hh = f / (h + h); + for (j = 0; j < i; j++) { + e[j] -= hh * d[j]; + } -module.exports = function additiveSymmetric(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]); + for (j = 0; j < i; j++) { + f = d[j]; + g = e[j]; + for (k = j; k <= i - 1; k++) { + V[k][j] -= (f * e[k] + g * d[k]); + } + d[j] = V[i - 1][j]; + V[i][j] = 0; + } + } + d[i] = h; } - return 2 * d; -}; + for (i = 0; i < n - 1; i++) { + V[n - 1][i] = V[i][i]; + V[i][i] = 1; + h = d[i + 1]; + if (h !== 0) { + for (k = 0; k <= i; k++) { + d[k] = V[k][i + 1] / h; + } -/***/ }), -/* 74 */ -/***/ (function(module, exports) { + for (j = 0; j <= i; j++) { + g = 0; + for (k = 0; k <= i; k++) { + g += V[k][i + 1] * V[k][j]; + } + for (k = 0; k <= i; k++) { + V[k][j] -= g * d[k]; + } + } + } -module.exports = function avg(a, b) { - var ii = a.length, - max = 0, - ans = 0, - aux = 0; - for (var i = 0; i < ii ; i++) { - aux = Math.abs(a[i] - b[i]); - ans += aux; - if (max < aux) { - max = aux; + for (k = 0; k <= i; k++) { + V[k][i + 1] = 0; } } - return (max + ans) / 2; -}; - - -/***/ }), -/* 75 */ -/***/ (function(module, exports) { -module.exports = function bhattacharyya(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += Math.sqrt(a[i] * b[i]); + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + V[n - 1][j] = 0; } - return - Math.log(ans); -}; + V[n - 1][n - 1] = 1; + e[0] = 0; +} -/***/ }), -/* 76 */ -/***/ (function(module, exports) { +function tql2(n, e, d, V) { -module.exports = function canberra(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]); + var g, h, i, j, k, l, m, p, r, + dl1, c, c2, c3, el1, s, s2, + iter; + + for (i = 1; i < n; i++) { + e[i - 1] = e[i]; } - return ans; -}; + e[n - 1] = 0; -/***/ }), -/* 77 */ -/***/ (function(module, exports) { + var f = 0, + tst1 = 0, + eps = Math.pow(2, -52); -module.exports = function chebyshev(a, b) { - var ii = a.length, - max = 0, - aux = 0; - for (var i = 0; i < ii ; i++) { - aux = Math.abs(a[i] - b[i]); - if (max < aux) { - max = aux; + for (l = 0; l < n; l++) { + tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); + m = l; + while (m < n) { + if (Math.abs(e[m]) <= eps * tst1) { + break; + } + m++; } - } - return max; -}; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports) { -module.exports = function clark(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += Math.sqrt(((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]))); - } - return 2 * d; -}; + if (m > l) { + iter = 0; + do { + iter = iter + 1; + g = d[l]; + p = (d[l + 1] - g) / (2 * e[l]); + r = hypotenuse(p, 1); + if (p < 0) { + r = -r; + } -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { + d[l] = e[l] / (p + r); + d[l + 1] = e[l] * (p + r); + dl1 = d[l + 1]; + h = g - d[l]; + for (i = l + 2; i < n; i++) { + d[i] -= h; + } -"use strict"; + f = f + h; + p = d[m]; + c = 1; + c2 = c; + c3 = c; + el1 = e[l + 1]; + s = 0; + s2 = 0; + for (i = m - 1; i >= l; i--) { + c3 = c2; + c2 = c; + s2 = s; + g = c * e[i]; + h = c * p; + r = hypotenuse(p, e[i]); + e[i + 1] = s * r; + s = e[i] / r; + c = p / r; + p = c * d[i] - s * g; + d[i + 1] = h + s * (c * g + s * d[i]); -const czekanowskiSimilarity = __webpack_require__(30); + for (k = 0; k < n; k++) { + h = V[k][i + 1]; + V[k][i + 1] = s * V[k][i] + c * h; + V[k][i] = c * V[k][i] - s * h; + } + } -module.exports = function czekanowskiDistance(a, b) { - return 1 - czekanowskiSimilarity(a, b); -}; + p = -s * s2 * c3 * el1 * e[l] / dl1; + e[l] = s * p; + d[l] = c * p; + } + while (Math.abs(e[l]) > eps * tst1); + } + d[l] = d[l] + f; + e[l] = 0; + } -/***/ }), -/* 80 */ -/***/ (function(module, exports) { + 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]; + } + } -module.exports = function divergence(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])); + if (k !== i) { + d[k] = d[i]; + d[i] = p; + for (j = 0; j < n; j++) { + p = V[j][i]; + V[j][i] = V[j][k]; + V[j][k] = p; + } + } } - return 2 * d; -}; - +} -/***/ }), -/* 81 */ -/***/ (function(module, exports) { +function orthes(n, H, ort, V) { -module.exports = function fidelity(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += Math.sqrt(a[i] * b[i]); - } - return ans; -}; + var low = 0, + high = n - 1, + f, g, h, i, j, m, + scale; + for (m = low + 1; m <= high - 1; m++) { + scale = 0; + for (i = m; i <= high; i++) { + scale = scale + Math.abs(H[i][m - 1]); + } -/***/ }), -/* 82 */ -/***/ (function(module, exports) { + if (scale !== 0) { + h = 0; + for (i = high; i >= m; i--) { + ort[i] = H[i][m - 1] / scale; + h += ort[i] * ort[i]; + } -module.exports = function gower(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += Math.abs(a[i] - b[i]); - } - return ans / ii; -}; + g = Math.sqrt(h); + if (ort[m] > 0) { + g = -g; + } + h = h - ort[m] * g; + ort[m] = ort[m] - g; -/***/ }), -/* 83 */ -/***/ (function(module, exports) { + for (j = m; j < n; j++) { + f = 0; + for (i = high; i >= m; i--) { + f += ort[i] * H[i][j]; + } -module.exports = function harmonicMean(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += (a[i] * b[i]) / (a[i] + b[i]); - } - return 2 * ans; -}; + f = f / h; + for (i = m; i <= high; i++) { + H[i][j] -= f * ort[i]; + } + } + for (i = 0; i <= high; i++) { + f = 0; + for (j = high; j >= m; j--) { + f += ort[j] * H[i][j]; + } -/***/ }), -/* 84 */ -/***/ (function(module, exports) { + f = f / h; + for (j = m; j <= high; j++) { + H[i][j] -= f * ort[j]; + } + } -module.exports = function hellinger(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += Math.sqrt(a[i] * b[i]); + ort[m] = scale * ort[m]; + H[m][m - 1] = scale * g; + } } - return 2 * Math.sqrt(1 - ans); -}; - - -/***/ }), -/* 85 */ -/***/ (function(module, exports) { -module.exports = function innerProduct(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += a[i] * b[i]; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = (i === j ? 1 : 0); + } } - return ans; -}; + for (m = high - 1; m >= low + 1; m--) { + if (H[m][m - 1] !== 0) { + for (i = m + 1; i <= high; i++) { + ort[i] = H[i][m - 1]; + } -/***/ }), -/* 86 */ -/***/ (function(module, exports) { + for (j = m; j <= high; j++) { + g = 0; + for (i = m; i <= high; i++) { + g += ort[i] * V[i][j]; + } -module.exports = function jeffreys(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += (a[i] - b[i]) * Math.log(a[i] / b[i]); + g = (g / ort[m]) / H[m][m - 1]; + for (i = m; i <= high; i++) { + V[i][j] += g * ort[i]; + } + } + } } - return ans; -}; +} +function hqr2(nn, e, d, V, H) { + var n = nn - 1, + low = 0, + high = nn - 1, + eps = Math.pow(2, -52), + exshift = 0, + norm = 0, + p = 0, + q = 0, + r = 0, + s = 0, + z = 0, + iter = 0, + i, j, k, l, m, t, w, x, y, + ra, sa, vr, vi, + notlast, cdivres; -/***/ }), -/* 87 */ -/***/ (function(module, exports) { + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + d[i] = H[i][i]; + e[i] = 0; + } -module.exports = function jensenDifference(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += ((a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2) - ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2); + for (j = Math.max(i - 1, 0); j < nn; j++) { + norm = norm + Math.abs(H[i][j]); + } } - return ans; -}; + while (n >= low) { + l = n; + while (l > low) { + s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); + if (s === 0) { + s = norm; + } + if (Math.abs(H[l][l - 1]) < eps * s) { + break; + } + l--; + } -/***/ }), -/* 88 */ -/***/ (function(module, exports) { + if (l === n) { + H[n][n] = H[n][n] + exshift; + d[n] = H[n][n]; + e[n] = 0; + n--; + iter = 0; + } else if (l === n - 1) { + w = H[n][n - 1] * H[n - 1][n]; + p = (H[n - 1][n - 1] - H[n][n]) / 2; + q = p * p + w; + z = Math.sqrt(Math.abs(q)); + H[n][n] = H[n][n] + exshift; + H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; + x = H[n][n]; -module.exports = function jensenShannon(a, b) { - var ii = a.length, - p = 0, - q = 0; - for (var i = 0; i < ii ; i++) { - p += a[i] * Math.log(2 * a[i] / (a[i] + b[i])); - q += b[i] * Math.log(2 * b[i] / (a[i] + b[i])); - } - return (p + q) / 2; -}; + if (q >= 0) { + z = (p >= 0) ? (p + z) : (p - z); + d[n - 1] = x + z; + d[n] = d[n - 1]; + if (z !== 0) { + d[n] = x - w / z; + } + e[n - 1] = 0; + e[n] = 0; + x = H[n][n - 1]; + s = Math.abs(x) + Math.abs(z); + p = x / s; + q = z / s; + r = Math.sqrt(p * p + q * q); + p = p / r; + q = q / r; + for (j = n - 1; j < nn; j++) { + z = H[n - 1][j]; + H[n - 1][j] = q * z + p * H[n][j]; + H[n][j] = q * H[n][j] - p * z; + } -/***/ }), -/* 89 */ -/***/ (function(module, exports) { + for (i = 0; i <= n; i++) { + z = H[i][n - 1]; + H[i][n - 1] = q * z + p * H[i][n]; + H[i][n] = q * H[i][n] - p * z; + } -module.exports = function kdivergence(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])); - } - return ans; -}; + for (i = low; i <= high; i++) { + z = V[i][n - 1]; + V[i][n - 1] = q * z + p * V[i][n]; + V[i][n] = q * V[i][n] - p * z; + } + } else { + d[n - 1] = x + p; + d[n] = x + p; + e[n - 1] = z; + e[n] = -z; + } + + n = n - 2; + iter = 0; + } else { + x = H[n][n]; + y = 0; + w = 0; + if (l < n) { + y = H[n - 1][n - 1]; + w = H[n][n - 1] * H[n - 1][n]; + } + + if (iter === 10) { + exshift += x; + for (i = low; i <= n; i++) { + H[i][i] -= x; + } + s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); + x = y = 0.75 * s; + w = -0.4375 * s * s; + } + if (iter === 30) { + s = (y - x) / 2; + s = s * s + w; + if (s > 0) { + s = Math.sqrt(s); + if (y < x) { + s = -s; + } + s = x - w / ((y - x) / 2 + s); + for (i = low; i <= n; i++) { + H[i][i] -= s; + } + exshift += s; + x = y = w = 0.964; + } + } -/***/ }), -/* 90 */ -/***/ (function(module, exports) { + iter = iter + 1; -module.exports = function kullbackLeibler(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += a[i] * Math.log(a[i] / b[i]); - } - return ans; -}; + m = n - 2; + while (m >= l) { + z = H[m][m]; + r = x - z; + s = y - z; + p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; + q = H[m + 1][m + 1] - z - r - s; + r = H[m + 2][m + 1]; + s = Math.abs(p) + Math.abs(q) + Math.abs(r); + p = p / s; + q = q / s; + r = r / s; + if (m === l) { + break; + } + if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { + break; + } + m--; + } + for (i = m + 2; i <= n; i++) { + H[i][i - 2] = 0; + if (i > m + 2) { + H[i][i - 3] = 0; + } + } -/***/ }), -/* 91 */ -/***/ (function(module, exports) { + for (k = m; k <= n - 1; k++) { + notlast = (k !== n - 1); + if (k !== m) { + p = H[k][k - 1]; + q = H[k + 1][k - 1]; + r = (notlast ? H[k + 2][k - 1] : 0); + x = Math.abs(p) + Math.abs(q) + Math.abs(r); + if (x !== 0) { + p = p / x; + q = q / x; + r = r / x; + } + } -module.exports = function kumarHassebrook(a, b) { - var ii = a.length, - p = 0, - p2 = 0, - q2 = 0; - for (var i = 0; i < ii ; i++) { - p += a[i] * b[i]; - p2 += a[i] * a[i]; - q2 += b[i] * b[i]; - } - return p / (p2 + q2 - p); -}; + if (x === 0) { + break; + } + s = Math.sqrt(p * p + q * q + r * r); + if (p < 0) { + s = -s; + } -/***/ }), -/* 92 */ -/***/ (function(module, exports) { + if (s !== 0) { + if (k !== m) { + H[k][k - 1] = -s * x; + } else if (l !== m) { + H[k][k - 1] = -H[k][k - 1]; + } -module.exports = function kumarJohnson(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += Math.pow(a[i] * a[i] - b[i] * b[i],2) / (2 * Math.pow(a[i] * b[i],1.5)); - } - return ans; -}; + p = p + s; + x = p / s; + y = q / s; + z = r / s; + q = q / p; + r = r / p; + for (j = k; j < nn; j++) { + p = H[k][j] + q * H[k + 1][j]; + if (notlast) { + p = p + r * H[k + 2][j]; + H[k + 2][j] = H[k + 2][j] - p * z; + } -/***/ }), -/* 93 */ -/***/ (function(module, exports) { + H[k][j] = H[k][j] - p * x; + H[k + 1][j] = H[k + 1][j] - p * y; + } -module.exports = function lorentzian(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += Math.log(Math.abs(a[i] - b[i]) + 1); - } - return ans; -}; + for (i = 0; i <= Math.min(n, k + 3); i++) { + p = x * H[i][k] + y * H[i][k + 1]; + if (notlast) { + p = p + z * H[i][k + 2]; + H[i][k + 2] = H[i][k + 2] - p * r; + } + H[i][k] = H[i][k] - p; + H[i][k + 1] = H[i][k + 1] - p * q; + } -/***/ }), -/* 94 */ -/***/ (function(module, exports) { + for (i = low; i <= high; i++) { + p = x * V[i][k] + y * V[i][k + 1]; + if (notlast) { + p = p + z * V[i][k + 2]; + V[i][k + 2] = V[i][k + 2] - p * r; + } -module.exports = function manhattan(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += Math.abs(a[i] - b[i]); + V[i][k] = V[i][k] - p; + V[i][k + 1] = V[i][k + 1] - p * q; + } + } + } + } } - return d; -}; - - -/***/ }), -/* 95 */ -/***/ (function(module, exports) { -module.exports = function matusita(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += Math.sqrt(a[i] * b[i]); + if (norm === 0) { + return; } - return Math.sqrt(2 - 2 * ans); -}; + for (n = nn - 1; n >= 0; n--) { + p = d[n]; + q = e[n]; -/***/ }), -/* 96 */ -/***/ (function(module, exports) { + if (q === 0) { + l = n; + H[n][n] = 1; + for (i = n - 1; i >= 0; i--) { + w = H[i][i] - p; + r = 0; + for (j = l; j <= n; j++) { + r = r + H[i][j] * H[j][n]; + } -module.exports = function minkowski(a, b, p) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += Math.pow(Math.abs(a[i] - b[i]),p); - } - return Math.pow(d,(1/p)); -}; + if (e[i] < 0) { + z = w; + s = r; + } else { + l = i; + if (e[i] === 0) { + H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm)); + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; + t = (x * s - z * r) / q; + H[i][n] = t; + H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z); + } + t = Math.abs(H[i][n]); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n] = H[j][n] / t; + } + } + } + } + } else if (q < 0) { + l = n - 1; -/***/ }), -/* 97 */ -/***/ (function(module, exports) { + if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { + H[n - 1][n - 1] = q / H[n][n - 1]; + H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; + } else { + cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); + H[n - 1][n - 1] = cdivres[0]; + H[n - 1][n] = cdivres[1]; + } -module.exports = function neyman(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += ((a[i] - b[i]) * (a[i] - b[i])) / a[i]; - } - return d; -}; + H[n][n - 1] = 0; + H[n][n] = 1; + for (i = n - 2; i >= 0; i--) { + ra = 0; + sa = 0; + for (j = l; j <= n; j++) { + ra = ra + H[i][j] * H[j][n - 1]; + sa = sa + H[i][j] * H[j][n]; + } + w = H[i][i] - p; -/***/ }), -/* 98 */ -/***/ (function(module, exports) { + if (e[i] < 0) { + z = w; + r = ra; + s = sa; + } else { + l = i; + if (e[i] === 0) { + cdivres = cdiv(-ra, -sa, w, q); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; + vi = (d[i] - p) * 2 * q; + if (vr === 0 && vi === 0) { + vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); + } + cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { + H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; + H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; + } else { + cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); + H[i + 1][n - 1] = cdivres[0]; + H[i + 1][n] = cdivres[1]; + } + } -module.exports = function pearson(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += ((a[i] - b[i]) * (a[i] - b[i])) / b[i]; + t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n - 1] = H[j][n - 1] / t; + H[j][n] = H[j][n] / t; + } + } + } + } + } } - return d; -}; - - -/***/ }), -/* 99 */ -/***/ (function(module, exports) { -module.exports = function probabilisticSymmetric(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]); + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + for (j = i; j < nn; j++) { + V[i][j] = H[i][j]; + } + } } - return 2 * d; -}; - -/***/ }), -/* 100 */ -/***/ (function(module, exports) { + for (j = nn - 1; j >= low; j--) { + for (i = low; i <= high; i++) { + z = 0; + for (k = low; k <= Math.min(j, high); k++) { + z = z + V[i][k] * H[k][j]; + } + V[i][j] = z; + } + } +} -module.exports = function ruzicka(a, b) { - var ii = a.length, - up = 0, - down = 0; - for (var i = 0; i < ii ; i++) { - up += Math.min(a[i],b[i]); - down += Math.max(a[i],b[i]); +function cdiv(xr, xi, yr, yi) { + var r, d; + if (Math.abs(yr) > Math.abs(yi)) { + r = yi / yr; + d = yr + r * yi; + return [(xr + r * xi) / d, (xi - r * xr) / d]; + } else { + r = yr / yi; + d = yi + r * yr; + return [(r * xr + xi) / d, (r * xi - xr) / d]; } - return up / down; -}; +} + +module.exports = EigenvalueDecomposition; /***/ }), -/* 101 */ -/***/ (function(module, exports) { +/* 186 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = function soergel(a, b) { - var ii = a.length, - up = 0, - down = 0; - for (var i = 0; i < ii ; i++) { - up += Math.abs(a[i] - b[i]); - down += Math.max(a[i],b[i]); - } - return up / down; -}; +"use strict"; -/***/ }), -/* 102 */ -/***/ (function(module, exports) { +var Matrix = __webpack_require__(4).Matrix; +var hypotenuse = __webpack_require__(26).hypotenuse; -module.exports = function sorensen(a, b) { - var ii = a.length, - up = 0, - down = 0; - for (var i = 0; i < ii ; i++) { - up += Math.abs(a[i] - b[i]); - down += a[i] + b[i]; +//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs +function QrDecomposition(value) { + if (!(this instanceof QrDecomposition)) { + return new QrDecomposition(value); } - return up / down; -}; - + value = Matrix.checkMatrix(value); -/***/ }), -/* 103 */ -/***/ (function(module, exports) { + var qr = value.clone(), + m = value.rows, + n = value.columns, + rdiag = new Array(n), + i, j, k, s; -module.exports = function squared(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]); + for (k = 0; k < n; k++) { + var nrm = 0; + for (i = k; i < m; i++) { + nrm = hypotenuse(nrm, qr[i][k]); + } + if (nrm !== 0) { + if (qr[k][k] < 0) { + nrm = -nrm; + } + for (i = k; i < m; i++) { + qr[i][k] /= nrm; + } + qr[k][k] += 1; + for (j = k + 1; j < n; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * qr[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + qr[i][j] += s * qr[i][k]; + } + } + } + rdiag[k] = -nrm; } - return d; -}; + this.QR = qr; + this.Rdiag = rdiag; +} -/***/ }), -/* 104 */ -/***/ (function(module, exports) { +QrDecomposition.prototype = { + solve: function (value) { + value = Matrix.checkMatrix(value); -module.exports = function taneja(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i]))); - } - return ans; -}; + var qr = this.QR, + m = qr.rows; + if (value.rows !== m) { + throw new Error('Matrix row dimensions must agree'); + } + if (!this.isFullRank()) { + throw new Error('Matrix is rank deficient'); + } -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { + var count = value.columns; + var X = value.clone(); + var n = qr.columns; + var i, j, k, s; -var tanimotoS = __webpack_require__(31); + for (k = 0; k < n; k++) { + for (j = 0; j < count; j++) { + s = 0; + for (i = k; i < m; i++) { + s += qr[i][k] * X[i][j]; + } + s = -s / qr[k][k]; + for (i = k; i < m; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + for (k = n - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + X[k][j] /= this.Rdiag[k]; + } + for (i = 0; i < k; i++) { + for (j = 0; j < count; j++) { + X[i][j] -= X[k][j] * qr[i][k]; + } + } + } -module.exports = function tanimoto(a, b, bitvector) { - if (bitvector) - return 1 - tanimotoS(a, b, bitvector); - else { - var ii = a.length, - p = 0, - q = 0, - m = 0; - for (var i = 0; i < ii ; i++) { - p += a[i]; - q += b[i]; - m += Math.min(a[i],b[i]); + return X.subMatrix(0, n - 1, 0, count - 1); + }, + isFullRank: function () { + var columns = this.QR.columns; + for (var i = 0; i < columns; i++) { + if (this.Rdiag[i] === 0) { + return false; + } } - return (p + q - 2 * m) / (p + q - m); - } -}; + return true; + }, + get upperTriangularMatrix() { + var qr = this.QR, + n = qr.columns, + X = new Matrix(n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + if (i < j) { + X[i][j] = qr[i][j]; + } else if (i === j) { + X[i][j] = this.Rdiag[i]; + } else { + X[i][j] = 0; + } + } + } + return X; + }, + get orthogonalMatrix() { + var qr = this.QR, + rows = qr.rows, + columns = qr.columns, + X = new Matrix(rows, columns), + i, j, k, s; + for (k = columns - 1; k >= 0; k--) { + for (i = 0; i < rows; i++) { + X[i][k] = 0; + } + X[k][k] = 1; + for (j = k; j < columns; j++) { + if (qr[k][k] !== 0) { + s = 0; + for (i = k; i < rows; i++) { + s += qr[i][k] * X[i][j]; + } -/***/ }), -/* 106 */ -/***/ (function(module, exports) { + s = -s / qr[k][k]; -module.exports = function topsoe(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i])); + for (i = k; i < rows; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + } + return X; } - return ans; }; - -/***/ }), -/* 107 */ -/***/ (function(module, exports) { - -module.exports = function waveHedges(a, b) { - var ii = a.length, - ans = 0; - for (var i = 0; i < ii ; i++) { - ans += 1 - (Math.min(a[i], b[i]) / Math.max(a[i], b[i])); - } - return ans; -}; +module.exports = QrDecomposition; /***/ }), -/* 108 */ +/* 187 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -exports.cosine = __webpack_require__(29); -exports.czekanowski = __webpack_require__(30); -exports.dice = __webpack_require__(109); -exports.intersection = __webpack_require__(110); -exports.jaccard = __webpack_require__(111); -exports.kulczynski = __webpack_require__(112); -exports.motyka = __webpack_require__(113); -exports.pearson = __webpack_require__(114); -exports.squaredChord = __webpack_require__(115); -exports.tanimoto = __webpack_require__(31); +var Matrix = __webpack_require__(4).Matrix; +var SingularValueDecomposition = __webpack_require__(64); +var EigenvalueDecomposition = __webpack_require__(185); +var LuDecomposition = __webpack_require__(63); +var QrDecomposition = __webpack_require__(186); +var CholeskyDecomposition = __webpack_require__(184); -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { +function inverse(matrix) { + matrix = Matrix.checkMatrix(matrix); + return solve(matrix, Matrix.eye(matrix.rows)); +} -var diceD = __webpack_require__(23); +/** + * Returns the inverse + * @memberOf Matrix + * @static + * @param {Matrix} matrix + * @return {Matrix} matrix + * @alias inv + */ +Matrix.inverse = Matrix.inv = inverse; -module.exports = function dice(a, b) { - return 1 - diceD(a,b); +/** + * Returns the inverse + * @memberOf Matrix + * @static + * @param {Matrix} matrix + * @return {Matrix} matrix + * @alias inv + */ +Matrix.prototype.inverse = Matrix.prototype.inv = function () { + return inverse(this); }; +function solve(leftHandSide, rightHandSide) { + leftHandSide = Matrix.checkMatrix(leftHandSide); + rightHandSide = Matrix.checkMatrix(rightHandSide); + return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide); +} -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - -var intersectionD = __webpack_require__(24); - -module.exports = function intersection(a, b) { - return 1 - intersectionD(a,b); +Matrix.solve = solve; +Matrix.prototype.solve = function (other) { + return solve(this, other); }; - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - -var jaccardD = __webpack_require__(25); - -module.exports = function jaccard(a, b) { - return 1 - jaccardD(a, b); +module.exports = { + SingularValueDecomposition: SingularValueDecomposition, + SVD: SingularValueDecomposition, + EigenvalueDecomposition: EigenvalueDecomposition, + EVD: EigenvalueDecomposition, + LuDecomposition: LuDecomposition, + LU: LuDecomposition, + QrDecomposition: QrDecomposition, + QR: QrDecomposition, + CholeskyDecomposition: CholeskyDecomposition, + CHO: CholeskyDecomposition, + inverse: inverse, + solve: solve }; /***/ }), -/* 112 */ +/* 188 */ /***/ (function(module, exports, __webpack_require__) { -var kulczynskiD = __webpack_require__(26); - -module.exports = function kulczynski(a, b) { - return 1 / kulczynskiD(a, b); -}; - - -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { +"use strict"; -var motykaD = __webpack_require__(27); -module.exports = function motyka(a, b) { - return 1 - motykaD(a,b); -}; +if (!Symbol.species) { + Symbol.species = Symbol.for('@@species'); +} /***/ }), -/* 114 */ +/* 189 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var stat=__webpack_require__(2).array; -var cosine=__webpack_require__(29); - -module.exports = function pearson(a, b) { - var avgA=stat.mean(a); - var avgB=stat.mean(b); +var BaseView = __webpack_require__(9); - var newA=new Array(a.length); - var newB=new Array(b.length); - for (var i=0; i>} distance - Array of points to be clustered - * @param {json} options - * @option isDistanceMatrix: Is the input a distance matrix? - * @constructor - */ -function agnes(data, options) { - options = Object.assign({}, defaultOptions, options); - var len = data.length; +/***/ }), +/* 194 */ +/***/ (function(module, exports, __webpack_require__) { - var distance = data;//If source - if(!options.isDistanceMatrix) { - distance = new Array(len); - for(var i = 0;i < len; i++) { - distance[i] = new Array(len); - for (var j = 0; j < len; j++) { - distance[i][j] = options.disFunc(data[i],data[j]); - } - } - } +"use strict"; - // allows to use a string or a given function - if (typeof options.kind === "string") { - switch (options.kind) { - case 'single': - options.kind = simpleLink; - break; - case 'complete': - options.kind = completeLink; - break; - case 'average': - options.kind = averageLink; - break; - case 'centroid': - options.kind = centroidLink; - break; - case 'ward': - options.kind = wardLink; - break; - default: - throw new RangeError('Unknown kind of similarity'); - } - } - else if (typeof options.kind !== "function") - throw new TypeError('Undefined kind of similarity'); +var BaseView = __webpack_require__(9); +var util = __webpack_require__(16); - var list = new Array(len); - for (var i = 0; i < distance.length; i++) - list[i] = new ClusterLeaf(i); - var min = 10e5, - d = {}, - dis = 0; +class MatrixSubView extends BaseView { + constructor(matrix, startRow, endRow, startColumn, endColumn) { + util.checkRange(matrix, startRow, endRow, startColumn, endColumn); + super(matrix, endRow - startRow + 1, endColumn - startColumn + 1); + this.startRow = startRow; + this.startColumn = startColumn; + } - while (list.length > 1) { - // calculates the minimum distance - d = {}; - min = 10e5; - for (var j = 0; j < list.length; j++){ - for (var k = j + 1; k < list.length; k++) { - var fdistance, sdistance; - if (list[j] instanceof ClusterLeaf) - fdistance = [list[j].index]; - else { - fdistance = new Array(list[j].index.length); - for (var e = 0; e < fdistance.length; e++) - fdistance[e] = list[j].index[e].index; - } - if (list[k] instanceof ClusterLeaf) - sdistance = [list[k].index]; - else { - sdistance = new Array(list[k].index.length); - for (var f = 0; f < sdistance.length; f++) - sdistance[f] = list[k].index[f].index; - } - dis = options.kind(fdistance, sdistance, distance).toFixed(4); - if (dis in d) { - d[dis].push([list[j], list[k]]); - } - else { - d[dis] = [[list[j], list[k]]]; - } - min = Math.min(dis, min); - } - } - // cluster dots - var dmin = d[min.toFixed(4)]; - var clustered = new Array(dmin.length); - var aux, - count = 0; - while (dmin.length > 0) { - aux = dmin.shift(); - for (var q = 0; q < dmin.length; q++) { - var int = dmin[q].filter(function(n) { - //noinspection JSReferencingMutableVariableFromClosure - return aux.indexOf(n) !== -1 - }); - if (int.length > 0) { - var diff = dmin[q].filter(function(n) { - //noinspection JSReferencingMutableVariableFromClosure - return aux.indexOf(n) === -1 - }); - aux = aux.concat(diff); - dmin.splice(q-- ,1); - } - } - clustered[count++] = aux; - } - clustered.length = count; + set(rowIndex, columnIndex, value) { + this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); + return this; + } - for (var ii = 0; ii < clustered.length; ii++) { - var obj = new Cluster(); - obj.children = clustered[ii].concat(); - obj.distance = min; - obj.index = new Array(len); - var indCount = 0; - for (var jj = 0; jj < clustered[ii].length; jj++) { - if (clustered[ii][jj] instanceof ClusterLeaf) - obj.index[indCount++] = clustered[ii][jj]; - else { - indCount += clustered[ii][jj].index.length; - obj.index = clustered[ii][jj].index.concat(obj.index); - } - list.splice((list.indexOf(clustered[ii][jj])), 1); - } - obj.index.length = indCount; - list.push(obj); - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); } - return list[0]; } -module.exports = agnes; +module.exports = MatrixSubView; /***/ }), -/* 119 */ +/* 195 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var euclidean = __webpack_require__(1); -var ClusterLeaf = __webpack_require__(35); -var Cluster = __webpack_require__(10); +var BaseView = __webpack_require__(9); -/** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ -function simpleLink(cluster1, cluster2, disFun) { - var m = 10e100; - for (var i = 0; i < cluster1.length; i++) - for (var j = i; j < cluster2.length; j++) { - var d = disFun(cluster1[i], cluster2[j]); - m = Math.min(d,m); - } - return m; +class MatrixTransposeView extends BaseView { + constructor(matrix) { + super(matrix, matrix.columns, matrix.rows); + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(columnIndex, rowIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(columnIndex, rowIndex); + } } +module.exports = MatrixTransposeView; + + +/***/ }), +/* 196 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const squaredDistance = __webpack_require__(1).squared; + +const defaultOptions = { + distanceFunction: squaredDistance, + similarityFunction: false, + returnVector: false +}; + /** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} + * Find the nearest vector in a list to a sample vector + * @param {Array>} listVectors - List of vectors with same dimensions + * @param {Array} vector - Reference vector to "classify" + * @param {object} [options] - Options object + * @param {function} [options.distanceFunction = squaredDistance] - Function that receives two vectors and return their distance value as number + * @param {function} [options.similarityFunction = undefined] - Function that receives two vectors and return their similarity value as number + * @param {boolean} [options.returnVector = false] - Return the nearest vector instead of its index + * @return {number|Array} - The index or the content of the nearest vector */ -function completeLink(cluster1, cluster2, disFun) { - var m = -1; - for (var i = 0; i < cluster1.length; i++) - for (var j = i; j < cluster2.length; j++) { - var d = disFun(cluster1[i], cluster2[j]); - m = Math.max(d,m); +function nearestVector(listVectors, vector, options) { + options = options || defaultOptions; + const distanceFunction = options.distanceFunction || defaultOptions.distanceFunction; + const similarityFunction = options.similarityFunction || defaultOptions.similarityFunction; + const returnVector = options.returnVector || defaultOptions.returnVector; + + var vectorIndex = -1; + if (typeof similarityFunction === 'function') { + + // maximum similarity + var maxSim = Number.MIN_VALUE; + for (var j = 0; j < listVectors.length; j++) { + var sim = similarityFunction(vector, listVectors[j]); + if (sim > maxSim) { + maxSim = sim; + vectorIndex = j; + } } - return m; -} + } else if (typeof distanceFunction === 'function') { -/** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ -function averageLink(cluster1, cluster2, disFun) { - var m = 0; - for (var i = 0; i < cluster1.length; i++) - for (var j = 0; j < cluster2.length; j++) - m += disFun(cluster1[i], cluster2[j]); - return m / (cluster1.length * cluster2.length); + // minimum distance + var minDist = Number.MAX_VALUE; + for (var i = 0; i < listVectors.length; i++) { + var dist = distanceFunction(vector, listVectors[i]); + if (dist < minDist) { + minDist = dist; + vectorIndex = i; + } + } + } else { + throw new Error('A similarity or distance function it\'s required'); + } + + if (returnVector) { + return listVectors[vectorIndex]; + } else { + return vectorIndex; + } } -/** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ -function centroidLink(cluster1, cluster2, disFun) { - var x1 = 0, - y1 = 0, - x2 = 0, - y2 = 0; - for (var i = 0; i < cluster1.length; i++) { - x1 += cluster1[i][0]; - y1 += cluster1[i][1]; +module.exports = nearestVector; + + +/***/ }), +/* 197 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// Accuracy +exports.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); } - for (var j = 0; j < cluster2.length; j++) { - x2 += cluster2[j][0]; - y2 += cluster2[j][1]; + return result; +}; + +// Error rate +exports.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)); } - x1 /= cluster1.length; - y1 /= cluster1.length; - x2 /= cluster2.length; - y2 /= cluster2.length; - return disFun([x1,y1], [x2,y2]); -} + return result; +}; -/** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ -function wardLink(cluster1, cluster2, disFun) { - var x1 = 0, - y1 = 0, - x2 = 0, - y2 = 0; - for (var i = 0; i < cluster1.length; i++) { - x1 += cluster1[i][0]; - y1 += cluster1[i][1]; +// False positive rate +exports.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; } - for (var j = 0; j < cluster2.length; j++) { - x2 += cluster2[j][0]; - y2 += cluster2[j][1]; + return result; +}; + +// True positive rate +exports.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; } - x1 /= cluster1.length; - y1 /= cluster1.length; - x2 /= cluster2.length; - y2 /= cluster2.length; - return disFun([x1,y1], [x2,y2])*cluster1.length*cluster2.length / (cluster1.length+cluster2.length); -} + return result; +}; -/** - * @private - * Returns the most distant point and his distance - * @param {Array >} splitting - Clusters to split - * @param {Array >} data - Original data - * @param {function} disFun - Distance function - * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant - */ -function diff(splitting, data, disFun) { - var ans = { - d:0, - p:0 - }; +// False negative rate +exports.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 result; +}; - var Ci = new Array(splitting[0].length); - for (var e = 0; e < splitting[0].length; e++) - Ci[e] = data[splitting[0][e]]; - var Cj = new Array(splitting[1].length); - for (var f = 0; f < splitting[1].length; f++) - Cj[f] = data[splitting[1][f]]; +// True negative rate +exports.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 result; +}; - var dist, ndist; - for (var i = 0; i < Ci.length; i++) { - dist = 0; - for (var j = 0; j < Ci.length; j++) - if (i !== j) - dist += disFun(Ci[i], Ci[j]); - dist /= (Ci.length - 1); - ndist = 0; - for (var k = 0; k < Cj.length; k++) - ndist += disFun(Ci[i], Cj[k]); - ndist /= Cj.length; - if ((dist - ndist) > ans.d) { - ans.d = (dist - ndist); - ans.p = i; - } +// Positive predictive value +exports.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; +}; -var defaultOptions = { - dist: euclidean, - kind: 'single' +// Negative predictive value +exports.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 result; }; -/** - * @private - * Intra-cluster distance - * @param {Array} index - * @param {Array} data - * @param {function} disFun - * @returns {number} - */ -function intrDist(index, data, disFun) { - var dist = 0, - count = 0; - for (var i = 0; i < index.length; i++) - for (var j = i; j < index.length; j++) { - dist += disFun(data[index[i].index], data[index[j].index]); - count++ - } - return dist / count; -} +// Prediction conditioned fallout +exports.pcfall = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + for (var i = 0; i < l; i++) { + result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1; + } + return result; +}; -/** - * Splits the higher level clusters - * @param {Array >} data - Array of points to be clustered - * @param {json} options - * @constructor - */ -function diana(data, options) { - options = options || {}; - for (var o in defaultOptions) - if (!(options.hasOwnProperty(o))) - options[o] = defaultOptions[o]; - if (typeof options.kind === "string") { - switch (options.kind) { - case 'single': - options.kind = simpleLink; - break; - case 'complete': - options.kind = completeLink; - break; - case 'average': - options.kind = averageLink; - break; - case 'centroid': - options.kind = centroidLink; - break; - case 'ward': - options.kind = wardLink; - break; - default: - throw new RangeError('Unknown kind of similarity'); - } +// Prediction conditioned miss +exports.pcmiss = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + for (var i = 0; i < l; i++) { + result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1; } - else if (typeof options.kind !== "function") - throw new TypeError('Undefined kind of similarity'); - var tree = new Cluster(); - tree.children = new Array(data.length); - tree.index = new Array(data.length); - for (var ind = 0; ind < data.length; ind++) { - tree.children[ind] = new ClusterLeaf(ind); - tree.index[ind] = new ClusterLeaf(ind); + return result; +}; + +// Lift value +exports.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 result; +}; - tree.distance = intrDist(tree.index, data, options.dist); - var m, M, clId, - dist, rebel; - var list = [tree]; - while (list.length > 0) { - M = 0; - clId = 0; - for (var i = 0; i < list.length; i++) { - m = 0; - for (var j = 0; j < list[i].length; j++) { - for (var l = (j + 1); l < list[i].length; l++) { - m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m); - } - } - if (m > M) { - M = m; - clId = i; - } - } - M = 0; - if (list[clId].index.length === 2) { - list[clId].children = [list[clId].index[0], list[clId].index[1]]; - list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]); - } - else if (list[clId].index.length === 3) { - list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]]; - var d = [ - options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]), - options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index]) - ]; - list[clId].distance = (d[0] + d[1]) / 2; - } - else { - var C = new Cluster(); - var sG = new Cluster(); - var splitting = [new Array(list[clId].index.length), []]; - for (var spl = 0; spl < splitting[0].length; spl++) - splitting[0][spl] = spl; - for (var ii = 0; ii < splitting[0].length; ii++) { - dist = 0; - for (var jj = 0; jj < splitting[0].length; jj++) - if (ii !== jj) - dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]); - dist /= (splitting[0].length - 1); - if (dist > M) { - M = dist; - rebel = ii; - } - } - splitting[1] = [rebel]; - splitting[0].splice(rebel, 1); - dist = diff(splitting, data, options.dist); - while (dist.d > 0) { - splitting[1].push(splitting[0][dist.p]); - splitting[0].splice(dist.p, 1); - dist = diff(splitting, data, options.dist); - } - var fData = new Array(splitting[0].length); - C.index = new Array(splitting[0].length); - for (var e = 0; e < fData.length; e++) { - fData[e] = data[list[clId].index[splitting[0][e]].index]; - C.index[e] = list[clId].index[splitting[0][e]]; - C.children[e] = list[clId].index[splitting[0][e]]; - } - var sData = new Array(splitting[1].length); - sG.index = new Array(splitting[1].length); - for (var f = 0; f < sData.length; f++) { - sData[f] = data[list[clId].index[splitting[1][f]].index]; - sG.index[f] = list[clId].index[splitting[1][f]]; - sG.children[f] = list[clId].index[splitting[1][f]]; - } - C.distance = intrDist(C.index, data, options.dist); - sG.distance = intrDist(sG.index, data, options.dist); - list.push(C); - list.push(sG); - list[clId].children = [C, sG]; - } - list.splice(clId, 1); +// Rate of positive predictions +exports.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 tree; -} + return result; +}; -module.exports = diana; +// Rate of negative predictions +exports.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 result; +}; + +// Threshold +exports.threshold = pred => { + const clone = pred.cutoffs.slice(); + clone[0] = clone[1]; // Remove the infinite value + return clone; +}; /***/ }), -/* 120 */ +/* 198 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +"use strict"; + + +var Matrix = __webpack_require__(0); +var Utils = __webpack_require__(27); + +module.exports = OPLS; + +function OPLS(dataset, predictions, numberOSC) { + var X = new Matrix(dataset); + var y = new Matrix(predictions); + + X = Utils.featureNormalize(X).result; + y = Utils.featureNormalize(y).result; + + var rows = X.rows; + var columns = X.columns; + + var sumOfSquaresX = X.clone().mul(X).sum(); + var w = X.transpose().mmul(y); + w.div(Utils.norm(w)); + + var orthoW = new Array(numberOSC); + var orthoT = new Array(numberOSC); + var orthoP = new Array(numberOSC); + for (var i = 0; i < numberOSC; i++) { + var t = X.mmul(w); + + var numerator = X.transpose().mmul(t); + var denominator = t.transpose().mmul(t)[0][0]; + var p = numerator.div(denominator); + + numerator = w.transpose().mmul(p)[0][0]; + denominator = w.transpose().mmul(w)[0][0]; + var wOsc = p.sub(w.clone().mul(numerator / denominator)); + wOsc.div(Utils.norm(wOsc)); + + var tOsc = X.mmul(wOsc); + + numerator = X.transpose().mmul(tOsc); + denominator = tOsc.transpose().mmul(tOsc)[0][0]; + var pOsc = numerator.div(denominator); + + X.sub(tOsc.mmul(pOsc.transpose())); + orthoW[i] = wOsc.getColumn(0); + orthoT[i] = tOsc.getColumn(0); + orthoP[i] = pOsc.getColumn(0); + } + this.Xosc = X; -const squaredEuclidean = __webpack_require__(1).squared; + var sumOfSquaresXosx = this.Xosc.clone().mul(this.Xosc).sum(); + this.R2X = 1 - sumOfSquaresXosx/sumOfSquaresX; -const defaultOptions = { - sigma: 1 -}; + this.W = orthoW; + this.T = orthoT; + this.P = orthoP; + this.numberOSC = numberOSC; +} -class GaussianKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - this.divisor = 2 * options.sigma * options.sigma; - } +OPLS.prototype.correctDataset = function (dataset) { + var X = new Matrix(dataset); - compute(x, y) { - const distance = squaredEuclidean(x, y); - return Math.exp(-distance / this.divisor); + var sumOfSquaresX = X.clone().mul(X).sum(); + for (var i = 0; i < this.numberOSC; i++) { + var currentW = this.W.getColumnVector(i); + var currentP = this.P.getColumnVector(i); + + var t = X.mmul(currentW); + X.sub(t.mmul(currentP)); } -} + var sumOfSquaresXosx = X.clone().mul(X).sum(); -module.exports = GaussianKernel; + var R2X = 1 - sumOfSquaresXosx / sumOfSquaresX; + return { + datasetOsc: X, + R2Dataset: R2X + }; +}; /***/ }), -/* 121 */ +/* 199 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const defaultOptions = { - degree: 1, - constant: 1, - scale: 1 -}; +var Matrix = __webpack_require__(0); +var Utils = __webpack_require__(27); -class PolynomialKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); +class PLS { + constructor(X, Y) { + if (X === true) { + const model = Y; + 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; + } else { + if (X.length !== Y.length) + throw new RangeError('The number of X rows must be equal to the number of Y rows'); - this.degree = options.degree; - this.constant = options.constant; - this.scale = options.scale; - } + const resultX = Utils.featureNormalize(X); + this.X = resultX.result; + this.meanX = resultX.means; + this.stdDevX = resultX.std; - compute(x, y) { - var sum = 0; - for (var i = 0; i < x.length; i++) { - sum += x[i] * y[i]; + const resultY = Utils.featureNormalize(Y); + this.Y = resultY.result; + this.meanY = resultY.means; + this.stdDevY = resultY.std; } - return Math.pow(this.scale * sum + this.constant, this.degree); } -} -module.exports = PolynomialKernel; + /** + * 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 {Object} options - recieves the latentVectors and the tolerance of each step of the PLS + */ + train(options) { + if(options === undefined) options = {}; + var latentVectors = options.latentVectors; + if (latentVectors === undefined) { + latentVectors = Math.min(this.X.length - 1, this.X[0].length); + } -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { + var tolerance = options.tolerance; + if (tolerance === undefined) { + tolerance = 1e-5; + } + + var X = this.X; + var Y = this.Y; -"use strict"; + var rx = X.rows; + var cx = X.columns; + var ry = Y.rows; + var cy = Y.columns; + var ssqXcal = X.clone().mul(X).sum(); // for the r² + var sumOfSquaresY = Y.clone().mul(Y).sum(); -const defaultOptions = { - alpha: 0.01, - constant: -Math.E -}; + var n = latentVectors; //Math.max(cx, cy); // components of the pls + 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; -class SigmoidKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.alpha = options.alpha; - this.constant = options.constant; - } + while(Utils.norm(Y) > tolerance && k < n) { + var transposeX = X.transpose(); + var transposeY = Y.transpose(); - compute(x, y) { - var sum = 0; - for (var i = 0; i < x.length; i++) { - sum += x[i] * y[i]; - } - return Math.tanh(this.alpha * sum + this.constant); - } -} + var tIndex = maxSumColIndex(X.clone().mulM(X)); + var uIndex = maxSumColIndex(Y.clone().mulM(Y)); -module.exports = SigmoidKernel; + var t1 = X.getColumnVector(tIndex); + var u = Y.getColumnVector(uIndex); + var t = Matrix.zeros(rx, 1); + while(Utils.norm(t1.clone().sub(t)) > tolerance) { + var w = transposeX.mmul(u); + w.div(Utils.norm(w)); + t = t1; + t1 = X.mmul(w); + var q = transposeY.mmul(t1); + q.div(Utils.norm(q)); + u = Y.mmul(q); + } -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { + t = t1; + var num = transposeX.mmul(t); + var den = (t.transpose().mmul(t))[0][0]; + var p = num.div(den); + var pnorm = Utils.norm(p); + p.div(pnorm); + t.mul(pnorm); + w.mul(pnorm); -"use strict"; + num = u.transpose().mmul(t); + den = (t.transpose().mmul(t))[0][0]; + var b = (num.div(den))[0][0]; + X.sub(t.mmul(p.transpose())); + Y.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); -const defaultOptions = { - sigma: 1, - degree: 1 -}; + B[k][k] = b; + k++; + } -class ANOVAKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - this.degree = options.degree; + 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 = X; + this.F = Y; + this.T = T; + this.P = P; + this.U = U; + this.Q = Q; + this.W = W; + this.B = B; + this.PBQ = P.mmul(B).mmul(Q.transpose()); + this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0]; + } + + /** + * Predicts the behavior of the given dataset. + * @param dataset - data to be predicted. + * @returns {Matrix} - predictions of each element of the dataset. + */ + predict(dataset) { + var X = Matrix.checkMatrix(dataset); + X = X.subRowVector(this.meanX).divRowVector(this.stdDevX); + var Y = X.mmul(this.PBQ); + Y = Y.mulRowVector(this.stdDevY).addRowVector(this.meanY); + return Y; + } + + /** + * Returns the explained variance on training of the PLS model + * @return {number} + */ + getExplainedVariance() { + return this.R2X; + } + + toJSON() { + return { + name: 'PLS', + R2X: this.R2X, + meanX: this.meanX, + stdDevX: this.stdDevX, + meanY: this.meanY, + stdDevY: this.stdDevY, + PBQ: this.PBQ, + }; } - compute(x, y) { - var sum = 0; - var len = Math.min(x.length, y.length); - for (var i = 1; i <= len; ++i) { - sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) - - Math.pow(y[i - 1], i), 2)), this.degree); - } - return sum; + /** + * Load a PLS model from a JSON Object + * @param model + * @return {PLS} - PLS object from the given model + */ + static load(model) { + if (model.name !== 'PLS') + throw new RangeError('Invalid model: ' + model.name); + return new PLS(true, model); } } -module.exports = ANOVAKernel; - - -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const squaredEuclidean = __webpack_require__(1).squared; - -const defaultOptions = { - sigma: 1 -}; +module.exports = PLS; -class CauchyKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; +/** + * Retrieves the sum at the column of the given matrix. + * @param matrix + * @param column + * @returns {number} + */ +function getColSum(matrix, column) { + var sum = 0; + for (var i = 0; i < matrix.rows; i++) { + sum += matrix[i][column]; } + return sum; +} - compute(x, y) { - return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma)); +/** + * Function that returns the index where the sum of each + * column vector is maximum. + * @param {Matrix} data + * @returns {number} index of the maximum + */ +function maxSumColIndex(data) { + var maxIndex = 0; + var maxSum = -Infinity; + for(var i = 0; i < data.columns; ++i) { + var currentSum = getColSum(data, i); + if(currentSum > maxSum) { + maxSum = currentSum; + maxIndex = i; + } } + return maxIndex; } -module.exports = CauchyKernel; - /***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { +/* 200 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; - - -const euclidean = __webpack_require__(1); - -const defaultOptions = { - sigma: 1 -}; - -class ExponentialKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - this.divisor = 2 * options.sigma * options.sigma; +/* harmony export (immutable) */ __webpack_exports__["a"] = checkArraySize; +function checkArraySize(x, y) { + if (!Array.isArray(x) || !Array.isArray(y)) { + throw new TypeError('x and y must be arrays'); } - - compute(x, y) { - const distance = euclidean(x, y); - return Math.exp(-distance / this.divisor); + if (x.length !== y.length) { + throw new RangeError('x and y arrays must have the same length'); } } -module.exports = ExponentialKernel; - /***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { +/* 201 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; - - -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; +/* harmony export (immutable) */ __webpack_exports__["a"] = maybeToPrecision; +function maybeToPrecision(value, digits) { + if (value < 0) { + value = 0 - value; + if (typeof digits === 'number') { + return '- ' + value.toPrecision(digits); + } else { + return '- ' + value.toString(); + } + } else { + if (typeof digits === 'number') { + return value.toPrecision(digits); + } else { + return value.toString(); + } } } -module.exports = HistogramIntersectionKernel; - /***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { +/* 202 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ml_regression_simple_linear__ = __webpack_require__(34); -const euclidean = __webpack_require__(1); - -const defaultOptions = { - sigma: 1 -}; -class LaplacianKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; +class ExponentialRegression extends __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["a" /* default */] { + constructor(x, y) { + super(); + if (x === true) { + this.A = y.A; + this.B = y.B; + } else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["b" /* checkArrayLength */])(x, y); + regress(this, x, y); + } } - compute(x, y) { - const distance = euclidean(x, y); - return Math.exp(-distance / this.sigma); + _predict(input) { + return this.B * Math.exp(input * this.A); } -} - -module.exports = LaplacianKernel; - - -/***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const squaredEuclidean = __webpack_require__(1).squared; - -const defaultOptions = { - constant: 1 -}; - -class MultiquadraticKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.constant = options.constant; + toJSON() { + return { + name: 'exponentialRegression', + A: this.A, + B: this.B + }; } - compute(x, y) { - return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant); + toString(precision) { + return 'f(x) = ' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.B, precision) + ' * e^(' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.A, precision) + ' * x)'; } -} - -module.exports = MultiquadraticKernel; - - -/***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const squaredEuclidean = __webpack_require__(1).squared; - -const defaultOptions = { - constant: 1 -}; + toLaTeX(precision) { + if (this.A >= 0) { + return 'f(x) = ' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.B, precision) + 'e^{' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.A, precision) + 'x}'; + } else { + return 'f(x) = \\frac{' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.B, precision) + '}{e^{' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(-this.A, precision) + 'x}}'; + } -class RationalQuadraticKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.constant = options.constant; } - compute(x, y) { - const distance = squaredEuclidean(x, y); - return 1 - (distance / (distance + this.constant)); + static load(json) { + if (json.name !== 'exponentialRegression') { + throw new TypeError('not a exponential regression model'); + } + return new ExponentialRegression(true, json); } } +/* harmony export (immutable) */ __webpack_exports__["default"] = ExponentialRegression; -module.exports = RationalQuadraticKernel; - - -/***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const utils = __webpack_require__(36); -const distanceSymbol = Symbol('distance'); - -/** - * 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 - */ -function KMeansResult(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 - */ -KMeansResult.prototype.nearest = function (data) { - var clusterID = new Array(data.length); - var centroids = this.centroids.map(function (centroid) { - return centroid.centroid; - }); - return utils.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} - */ -KMeansResult.prototype.computeInformation = function (data) { - var enrichedCentroids = this.centroids.map(function (centroid) { - return { - centroid: centroid, - error: 0, - size: 0 - }; - }); - - 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 j = 0; j < this.centroids.length; j++) { - enrichedCentroids[j].error /= enrichedCentroids[j].size; +function regress(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]); } - return new KMeansResult(this.clusters, enrichedCentroids, this.converged, this.iterations, this[distanceSymbol]); -}; - -module.exports = KMeansResult; + const linear = new __WEBPACK_IMPORTED_MODULE_1_ml_regression_simple_linear__["default"](x, yl); + er.A = linear.slope; + er.B = Math.exp(linear.intercept); +} /***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { +/* 203 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(5); -const Picker = __webpack_require__(62).Picker; +// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs +function CholeskyDecomposition(value) { + if (!(this instanceof CholeskyDecomposition)) { + return new CholeskyDecomposition(value); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + if (!value.isSymmetric()) { + throw new Error('Matrix is not symmetric'); + } -/** - * 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 - * @return {Array>} - Initial random points - */ -function random(data, K) { - const rand = new Picker(data); - var ans = new Array(K); + var a = value, + dimension = a.rows, + l = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](dimension, dimension), + positiveDefinite = true, + i, j, k; - for (var i = 0; i < K; ++i) { - ans[i] = rand.pick(); + for (j = 0; j < dimension; j++) { + var Lrowj = l[j]; + var d = 0; + for (k = 0; k < j; k++) { + var Lrowk = l[k]; + var s = 0; + for (i = 0; i < k; i++) { + s += Lrowk[i] * Lrowj[i]; + } + Lrowj[k] = s = (a[j][k] - s) / l[k][k]; + d = d + s * s; + } + + d = a[j][j] - d; + + positiveDefinite &= (d > 0); + l[j][j] = Math.sqrt(Math.max(d, 0)); + for (k = j + 1; k < dimension; k++) { + l[j][k] = 0; + } } - return ans; + + if (!positiveDefinite) { + throw new Error('Matrix is not positive definite'); + } + + this.L = l; } -/** - * 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 - * @return {Array>} - Initial random points - */ -function mostDistant(data, K, distanceMatrix) { - var ans = new Array(K); +CholeskyDecomposition.prototype = { + get lowerTriangularMatrix() { + return this.L; + }, + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); - // chooses a random point as initial cluster - ans[0] = Math.floor(Math.random() * data.length); + var l = this.L, + dimension = l.rows; - if (K > 1) { - // chooses the more distant point - var maxDist = {dist: -1, index: -1}; - for (var l = 0; l < data.length; ++l) { - if (distanceMatrix[ans[0]][l] > maxDist.dist) { - maxDist.dist = distanceMatrix[ans[0]][l]; - maxDist.index = l; - } + if (value.rows !== dimension) { + throw new Error('Matrix dimensions do not match'); } - ans[1] = maxDist.index; - - if (K > 2) { - // chooses the set of points that maximises the min distance - for (var k = 2; k < K; ++k) { - var center = {dist: -1, index: -1}; - for (var m = 0; m < data.length; ++m) { - // minimum distance to centers - var minDistCent = {dist: Number.MAX_VALUE, index: -1}; - for (var n = 0; n < k; ++n) { - if (distanceMatrix[n][m] < minDistCent.dist && ans.indexOf(m) === -1) { - minDistCent = { - dist: distanceMatrix[n][m], - index: m - }; - } - } + var count = value.columns, + B = value.clone(), + i, j, k; - if (minDistCent.dist !== Number.MAX_VALUE && minDistCent.dist > center.dist) { - center = Object.assign({}, minDistCent); - } + for (k = 0; k < dimension; k++) { + for (j = 0; j < count; j++) { + for (i = 0; i < k; i++) { + B[k][j] -= B[i][j] * l[k][i]; } + B[k][j] /= l[k][k]; + } + } - ans[k] = center.index; + for (k = dimension - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + for (i = k + 1; i < dimension; i++) { + B[k][j] -= B[i][j] * l[i][k]; + } + B[k][j] /= l[k][k]; } } - } - return ans.map((index) => data[index]); -} + return B; + } +}; -exports.random = random; -exports.mostDistant = mostDistant; +/* unused harmony default export */ var _unused_webpack_default_export = (CholeskyDecomposition); /***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { +/* 204 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(30); -/** -* 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 -*/ +const defaultOptions = { + assumeSymmetric: false +}; -function Node(obj, dimension, parent) { - this.obj = obj; - this.left = null; - this.right = null; - this.parent = parent; - this.dimension = dimension; -} +// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs +function EigenvalueDecomposition(matrix, options) { + options = Object.assign({}, defaultOptions, options); + if (!(this instanceof EigenvalueDecomposition)) { + return new EigenvalueDecomposition(matrix, options); + } + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + if (!matrix.isSquare()) { + throw new Error('Matrix is not a square matrix'); + } -function kdTree(points, metric, dimensions) { + var n = matrix.columns, + V = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + d = new Array(n), + e = new Array(n), + value = matrix, + i, j; - var self = this; + var isSymmetric = false; + if (options.assumeSymmetric) { + isSymmetric = true; + } else { + isSymmetric = matrix.isSymmetric(); + } - function buildTree(points, depth, parent) { - var dim = depth % dimensions.length, - median, - node; + if (isSymmetric) { + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = value.get(i, j); + } + } + tred2(n, e, d, V); + tql2(n, e, d, V); + } else { + var H = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + ort = new Array(n); + for (j = 0; j < n; j++) { + for (i = 0; i < n; i++) { + H[i][j] = value.get(i, j); + } + } + orthes(n, H, ort, V); + hqr2(n, e, d, V, H); + } - if (points.length === 0) { - return null; + this.n = n; + this.e = e; + this.d = d; + this.V = V; +} + +EigenvalueDecomposition.prototype = { + get realEigenvalues() { + return this.d; + }, + get imaginaryEigenvalues() { + return this.e; + }, + get eigenvectorMatrix() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.V)) { + this.V = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.V); } - if (points.length === 1) { - return new Node(points[0], dim, parent); + return this.V; + }, + get diagonalMatrix() { + var n = this.n, + e = this.e, + d = this.d, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + X[i][j] = 0; + } + X[i][i] = d[i]; + if (e[i] > 0) { + X[i][i + 1] = e[i]; + } else if (e[i] < 0) { + X[i][i - 1] = e[i]; + } + } + return X; + } +}; + +function tred2(n, e, d, V) { + + var f, g, h, i, j, k, + hh, scale; + + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + } + + for (i = n - 1; i > 0; i--) { + scale = 0; + h = 0; + for (k = 0; k < i; k++) { + scale = scale + Math.abs(d[k]); } - points.sort(function (a, b) { - return a[dimensions[dim]] - b[dimensions[dim]]; - }); + if (scale === 0) { + e[i] = d[i - 1]; + for (j = 0; j < i; j++) { + d[j] = V[i - 1][j]; + V[i][j] = 0; + V[j][i] = 0; + } + } else { + for (k = 0; k < i; k++) { + d[k] /= scale; + h += d[k] * d[k]; + } + + f = d[i - 1]; + g = Math.sqrt(h); + if (f > 0) { + g = -g; + } - median = Math.floor(points.length / 2); - node = new Node(points[median], dim, parent); - node.left = buildTree(points.slice(0, median), depth + 1, node); - node.right = buildTree(points.slice(median + 1), depth + 1, node); + e[i] = scale * g; + h = h - f * g; + d[i - 1] = f - g; + for (j = 0; j < i; j++) { + e[j] = 0; + } - return node; - } + for (j = 0; j < i; j++) { + f = d[j]; + V[j][i] = f; + g = e[j] + V[j][j] * f; + for (k = j + 1; k <= i - 1; k++) { + g += V[k][j] * d[k]; + e[k] += V[k][j] * f; + } + e[j] = g; + } - // Reloads a serialied tree - function loadTree (data) { - // Just need to restore the `parent` parameter - self.root = data; + f = 0; + for (j = 0; j < i; j++) { + e[j] /= h; + f += e[j] * d[j]; + } - function restoreParent (root) { - if (root.left) { - root.left.parent = root; - restoreParent(root.left); + hh = f / (h + h); + for (j = 0; j < i; j++) { + e[j] -= hh * d[j]; } - if (root.right) { - root.right.parent = root; - restoreParent(root.right); + for (j = 0; j < i; j++) { + f = d[j]; + g = e[j]; + for (k = j; k <= i - 1; k++) { + V[k][j] -= (f * e[k] + g * d[k]); + } + d[j] = V[i - 1][j]; + V[i][j] = 0; } } - - restoreParent(self.root); + d[i] = h; } - // If points is not an array, assume we're loading a pre-built tree - if (!Array.isArray(points)) loadTree(points, metric, dimensions); - else this.root = buildTree(points, 0, null); - - // Convert to a JSON serializable structure; this just requires removing - // the `parent` property - this.toJSON = function (src) { - if (!src) src = this.root; - var dest = new Node(src.obj, src.dimension, null); - if (src.left) dest.left = self.toJSON(src.left); - if (src.right) dest.right = self.toJSON(src.right); - return dest; - }; - - this.insert = function (point) { - function innerSearch(node, parent) { - - if (node === null) { - return parent; + for (i = 0; i < n - 1; i++) { + V[n - 1][i] = V[i][i]; + V[i][i] = 1; + h = d[i + 1]; + if (h !== 0) { + for (k = 0; k <= i; k++) { + d[k] = V[k][i + 1] / h; } - var dimension = dimensions[node.dimension]; - if (point[dimension] < node.obj[dimension]) { - return innerSearch(node.left, node); - } else { - return innerSearch(node.right, node); + for (j = 0; j <= i; j++) { + g = 0; + for (k = 0; k <= i; k++) { + g += V[k][i + 1] * V[k][j]; + } + for (k = 0; k <= i; k++) { + V[k][j] -= g * d[k]; + } } } - var insertPosition = innerSearch(this.root, null), - newNode, - dimension; - - if (insertPosition === null) { - this.root = new Node(point, 0, null); - return; + for (k = 0; k <= i; k++) { + V[k][i + 1] = 0; } + } - newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition); - dimension = dimensions[insertPosition.dimension]; + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + V[n - 1][j] = 0; + } - if (point[dimension] < insertPosition.obj[dimension]) { - insertPosition.left = newNode; - } else { - insertPosition.right = newNode; - } - }; + V[n - 1][n - 1] = 1; + e[0] = 0; +} - this.remove = function (point) { - var node; +function tql2(n, e, d, V) { - function nodeSearch(node) { - if (node === null) { - return null; - } + var g, h, i, j, k, l, m, p, r, + dl1, c, c2, c3, el1, s, s2, + iter; - if (node.obj === point) { - return node; - } + for (i = 1; i < n; i++) { + e[i - 1] = e[i]; + } - var dimension = dimensions[node.dimension]; + e[n - 1] = 0; - if (point[dimension] < node.obj[dimension]) { - return nodeSearch(node.left, node); - } else { - return nodeSearch(node.right, node); + var f = 0, + tst1 = 0, + eps = Math.pow(2, -52); + + for (l = 0; l < n; l++) { + tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); + m = l; + while (m < n) { + if (Math.abs(e[m]) <= eps * tst1) { + break; } + m++; } - function removeNode(node) { - var nextNode, - nextObj, - pDimension; + if (m > l) { + iter = 0; + do { + iter = iter + 1; - function findMin(node, dim) { - var dimension, - own, - left, - right, - min; + g = d[l]; + p = (d[l + 1] - g) / (2 * e[l]); + r = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(p, 1); + if (p < 0) { + r = -r; + } - if (node === null) { - return null; + d[l] = e[l] / (p + r); + d[l + 1] = e[l] * (p + r); + dl1 = d[l + 1]; + h = g - d[l]; + for (i = l + 2; i < n; i++) { + d[i] -= h; } - dimension = dimensions[dim]; + f = f + h; - if (node.dimension === dim) { - if (node.left !== null) { - return findMin(node.left, dim); + p = d[m]; + c = 1; + c2 = c; + c3 = c; + el1 = e[l + 1]; + s = 0; + s2 = 0; + for (i = m - 1; i >= l; i--) { + c3 = c2; + c2 = c; + s2 = s; + g = c * e[i]; + h = c * p; + r = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(p, e[i]); + e[i + 1] = s * r; + s = e[i] / r; + c = p / r; + p = c * d[i] - s * g; + d[i + 1] = h + s * (c * g + s * d[i]); + + for (k = 0; k < n; k++) { + h = V[k][i + 1]; + V[k][i + 1] = s * V[k][i] + c * h; + V[k][i] = c * V[k][i] - s * h; } - return node; } - own = node.obj[dimension]; - left = findMin(node.left, dim); - right = findMin(node.right, dim); - min = node; + p = -s * s2 * c3 * el1 * e[l] / dl1; + e[l] = s * p; + d[l] = c * p; - if (left !== null && left.obj[dimension] < own) { - min = left; - } - if (right !== null && right.obj[dimension] < min.obj[dimension]) { - min = right; - } - return min; } + while (Math.abs(e[l]) > eps * tst1); + } + d[l] = d[l] + f; + e[l] = 0; + } - if (node.left === null && node.right === null) { - if (node.parent === null) { - self.root = null; - return; - } - - pDimension = dimensions[node.parent.dimension]; - - if (node.obj[pDimension] < node.parent.obj[pDimension]) { - node.parent.left = null; - } else { - node.parent.right = null; - } - return; + for (i = 0; i < n - 1; i++) { + k = i; + p = d[i]; + for (j = i + 1; j < n; j++) { + if (d[j] < p) { + k = j; + p = d[j]; } + } - // If the right subtree is not empty, swap with the minimum element on the - // node's dimension. If it is empty, we swap the left and right subtrees and - // do the same. - if (node.right !== null) { - nextNode = findMin(node.right, node.dimension); - nextObj = nextNode.obj; - removeNode(nextNode); - node.obj = nextObj; - } else { - nextNode = findMin(node.left, node.dimension); - nextObj = nextNode.obj; - removeNode(nextNode); - node.right = node.left; - node.left = null; - node.obj = nextObj; + if (k !== i) { + d[k] = d[i]; + d[i] = p; + for (j = 0; j < n; j++) { + p = V[j][i]; + V[j][i] = V[j][k]; + V[j][k] = p; } - } + } +} - node = nodeSearch(self.root); +function orthes(n, H, ort, V) { - if (node === null) { return; } + var low = 0, + high = n - 1, + f, g, h, i, j, m, + scale; - removeNode(node); - }; + for (m = low + 1; m <= high - 1; m++) { + scale = 0; + for (i = m; i <= high; i++) { + scale = scale + Math.abs(H[i][m - 1]); + } - this.nearest = function (point, maxNodes, maxDistance) { - var i, - result, - bestNodes; + if (scale !== 0) { + h = 0; + for (i = high; i >= m; i--) { + ort[i] = H[i][m - 1] / scale; + h += ort[i] * ort[i]; + } - bestNodes = new BinaryHeap( - function (e) { return -e[1]; } - ); + g = Math.sqrt(h); + if (ort[m] > 0) { + g = -g; + } - function nearestSearch(node) { - var bestChild, - dimension = dimensions[node.dimension], - ownDistance = metric(point, node.obj), - linearPoint = {}, - linearDistance, - otherChild, - i; + h = h - ort[m] * g; + ort[m] = ort[m] - g; - function saveNode(node, distance) { - bestNodes.push([node, distance]); - if (bestNodes.size() > maxNodes) { - bestNodes.pop(); + for (j = m; j < n; j++) { + f = 0; + for (i = high; i >= m; i--) { + f += ort[i] * H[i][j]; } - } - 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]]; + f = f / h; + for (i = m; i <= high; i++) { + H[i][j] -= f * ort[i]; } } - linearDistance = metric(linearPoint, node.obj); - - if (node.right === null && node.left === null) { - if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { - saveNode(node, ownDistance); + for (i = 0; i <= high; i++) { + f = 0; + for (j = high; j >= m; j--) { + f += ort[j] * H[i][j]; } - return; - } - 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; + f = f / h; + for (j = m; j <= high; j++) { + H[i][j] -= f * ort[j]; } } - nearestSearch(bestChild); + ort[m] = scale * ort[m]; + H[m][m - 1] = scale * g; + } + } - if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { - saveNode(node, ownDistance); + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = (i === j ? 1 : 0); + } + } + + for (m = high - 1; m >= low + 1; m--) { + if (H[m][m - 1] !== 0) { + for (i = m + 1; i <= high; i++) { + ort[i] = H[i][m - 1]; } - 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); + for (j = m; j <= high; j++) { + g = 0; + for (i = m; i <= high; i++) { + g += ort[i] * V[i][j]; } - } - } - if (maxDistance) { - for (i = 0; i < maxNodes; i += 1) { - bestNodes.push([null, maxDistance]); + g = (g / ort[m]) / H[m][m - 1]; + for (i = m; i <= high; i++) { + V[i][j] += g * ort[i]; + } } } + } +} - if(self.root) - nearestSearch(self.root); - - result = []; +function hqr2(nn, e, d, V, H) { + var n = nn - 1, + low = 0, + high = nn - 1, + eps = Math.pow(2, -52), + exshift = 0, + norm = 0, + p = 0, + q = 0, + r = 0, + s = 0, + z = 0, + iter = 0, + i, j, k, l, m, t, w, x, y, + ra, sa, vr, vi, + notlast, cdivres; - 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]]); - } + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + d[i] = H[i][i]; + e[i] = 0; } - return result; - }; - this.balanceFactor = function () { - function height(node) { - if (node === null) { - return 0; - } - return Math.max(height(node.left), height(node.right)) + 1; + for (j = Math.max(i - 1, 0); j < nn; j++) { + norm = norm + Math.abs(H[i][j]); } + } - function count(node) { - if (node === null) { - return 0; + while (n >= low) { + l = n; + while (l > low) { + s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); + if (s === 0) { + s = norm; } - return count(node.left) + count(node.right) + 1; + if (Math.abs(H[l][l - 1]) < eps * s) { + break; + } + l--; } - return height(self.root) / (Math.log(count(self.root)) / Math.log(2)); - }; -} - -// Binary heap implementation from: -// http://eloquentjavascript.net/appendix2.html - -function BinaryHeap(scoreFunction){ - this.content = []; - this.scoreFunction = scoreFunction; -} - -BinaryHeap.prototype = { - push: function(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); - }, + if (l === n) { + H[n][n] = H[n][n] + exshift; + d[n] = H[n][n]; + e[n] = 0; + n--; + iter = 0; + } else if (l === n - 1) { + w = H[n][n - 1] * H[n - 1][n]; + p = (H[n - 1][n - 1] - H[n][n]) / 2; + q = p * p + w; + z = Math.sqrt(Math.abs(q)); + H[n][n] = H[n][n] + exshift; + H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; + x = H[n][n]; - pop: function() { - // Store the first element so we can return it later. - var result = this.content[0]; - // Get the element at the end of the array. - var end = this.content.pop(); - // If there are any elements left, put the end element at the - // start, and let it sink down. - if (this.content.length > 0) { - this.content[0] = end; - this.sinkDown(0); - } - return result; - }, + if (q >= 0) { + z = (p >= 0) ? (p + z) : (p - z); + d[n - 1] = x + z; + d[n] = d[n - 1]; + if (z !== 0) { + d[n] = x - w / z; + } + e[n - 1] = 0; + e[n] = 0; + x = H[n][n - 1]; + s = Math.abs(x) + Math.abs(z); + p = x / s; + q = z / s; + r = Math.sqrt(p * p + q * q); + p = p / r; + q = q / r; - peek: function() { - return this.content[0]; - }, + for (j = n - 1; j < nn; j++) { + z = H[n - 1][j]; + H[n - 1][j] = q * z + p * H[n][j]; + H[n][j] = q * H[n][j] - p * z; + } - remove: function(node) { - var len = this.content.length; - // To remove a value, we must search through the array to find - // it. - for (var i = 0; i < len; i++) { - if (this.content[i] == node) { - // When it is found, the process seen in 'pop' is repeated - // to fill up the hole. - var end = this.content.pop(); - if (i != len - 1) { - this.content[i] = end; - if (this.scoreFunction(end) < this.scoreFunction(node)) - this.bubbleUp(i); - else - this.sinkDown(i); + for (i = 0; i <= n; i++) { + z = H[i][n - 1]; + H[i][n - 1] = q * z + p * H[i][n]; + H[i][n] = q * H[i][n] - p * z; } - return; + + for (i = low; i <= high; i++) { + z = V[i][n - 1]; + V[i][n - 1] = q * z + p * V[i][n]; + V[i][n] = q * V[i][n] - p * z; + } + } else { + d[n - 1] = x + p; + d[n] = x + p; + e[n - 1] = z; + e[n] = -z; } - } - throw new Error("Node not found."); - }, - size: function() { - return this.content.length; - }, + n = n - 2; + iter = 0; + } else { + x = H[n][n]; + y = 0; + w = 0; + if (l < n) { + y = H[n - 1][n - 1]; + w = H[n][n - 1] * H[n - 1][n]; + } - bubbleUp: function(n) { - // Fetch the element that has to be moved. - var element = this.content[n]; - // When at 0, an element can not go up any further. - while (n > 0) { - // Compute the parent element's index, and fetch it. - var parentN = Math.floor((n + 1) / 2) - 1, - parent = this.content[parentN]; - // Swap the elements if the parent is greater. - if (this.scoreFunction(element) < this.scoreFunction(parent)) { - this.content[parentN] = element; - this.content[n] = parent; - // Update 'n' to continue at the new position. - n = parentN; + if (iter === 10) { + exshift += x; + for (i = low; i <= n; i++) { + H[i][i] -= x; + } + s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); + x = y = 0.75 * s; + w = -0.4375 * s * s; } - // Found a parent that is less, no need to move it further. - else { - break; + + if (iter === 30) { + s = (y - x) / 2; + s = s * s + w; + if (s > 0) { + s = Math.sqrt(s); + if (y < x) { + s = -s; + } + s = x - w / ((y - x) / 2 + s); + for (i = low; i <= n; i++) { + H[i][i] -= s; + } + exshift += s; + x = y = w = 0.964; + } } - } - }, - sinkDown: function(n) { - // Look up the target element and its score. - var length = this.content.length, - element = this.content[n], - elemScore = this.scoreFunction(element); + iter = iter + 1; - while(true) { - // Compute the indices of the child elements. - var child2N = (n + 1) * 2, 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], - 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], - child2Score = this.scoreFunction(child2); - if (child2Score < (swap == null ? elemScore : child1Score)){ - swap = child2N; + m = n - 2; + while (m >= l) { + z = H[m][m]; + r = x - z; + s = y - z; + p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; + q = H[m + 1][m + 1] - z - r - s; + r = H[m + 2][m + 1]; + s = Math.abs(p) + Math.abs(q) + Math.abs(r); + p = p / s; + q = q / s; + r = r / s; + if (m === l) { + break; } + if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { + break; + } + m--; } - // If the element needs to be moved, swap it, and continue. - if (swap != null) { - this.content[n] = this.content[swap]; - this.content[swap] = element; - n = swap; - } - // Otherwise, we are done. - else { - break; + for (i = m + 2; i <= n; i++) { + H[i][i - 2] = 0; + if (i > m + 2) { + H[i][i - 3] = 0; + } } - } - } -}; -this.kdTree = kdTree; + for (k = m; k <= n - 1; k++) { + notlast = (k !== n - 1); + if (k !== m) { + p = H[k][k - 1]; + q = H[k + 1][k - 1]; + r = (notlast ? H[k + 2][k - 1] : 0); + x = Math.abs(p) + Math.abs(q) + Math.abs(r); + if (x !== 0) { + p = p / x; + q = q / x; + r = r / x; + } + } -exports.kdTree = kdTree; -exports.BinaryHeap = BinaryHeap; + if (x === 0) { + break; + } + s = Math.sqrt(p * p + q * q + r * r); + if (p < 0) { + s = -s; + } -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { + if (s !== 0) { + if (k !== m) { + H[k][k - 1] = -s * x; + } else if (l !== m) { + H[k][k - 1] = -H[k][k - 1]; + } -"use strict"; + p = p + s; + x = p / s; + y = q / s; + z = r / s; + q = q / p; + r = r / p; + for (j = k; j < nn; j++) { + p = H[k][j] + q * H[k + 1][j]; + if (notlast) { + p = p + r * H[k + 2][j]; + H[k + 2][j] = H[k + 2][j] - p * z; + } -module.exports = KNN; + H[k][j] = H[k][j] - p * x; + H[k + 1][j] = H[k + 1][j] - p * y; + } -var KDTree = __webpack_require__(132).kdTree; -var Distances = __webpack_require__(18); + for (i = 0; i <= Math.min(n, k + 3); i++) { + p = x * H[i][k] + y * H[i][k + 1]; + if (notlast) { + p = p + z * H[i][k + 2]; + H[i][k + 2] = H[i][k + 2] - p * r; + } -/** - * K-Nearest neighboor constructor. - * - * @param reload - loading purposes. - * @param model - loading purposes - * @constructor - */ -function KNN(reload, model) { - if(reload) { - this.kdtree = model.kdtree; - this.k = model.k; - this.classes = model.classes; - } -} + H[i][k] = H[i][k] - p; + H[i][k + 1] = H[i][k + 1] - p * q; + } -/** - * Function that trains the KNN with the given trainingSet and trainingLabels. - * The third argument is an object with the following options. - * * distance: that represent the distance function applied (default: euclidean) - * * k: the number of neighboors to take in count for classify (default: number of features + 1) - * - * @param trainingSet - * @param trainingLabels - * @param options - */ -KNN.prototype.train = function (trainingSet, trainingLabels, options) { - if(options === undefined) options = {}; - if(options.distance === undefined) options.distance = Distances.distance.euclidean; - if(options.k === undefined) options.k = trainingSet[0].length + 1; + for (i = low; i <= high; i++) { + p = x * V[i][k] + y * V[i][k + 1]; + if (notlast) { + p = p + z * V[i][k + 2]; + V[i][k + 2] = V[i][k + 2] - p * r; + } - var classes = 0; - var exist = new Array(1000); - var j = 0; - for(var i = 0; i < trainingLabels.length; ++i) { - if(exist.indexOf(trainingLabels[i]) === -1) { - classes++; - exist[j] = trainingLabels[i]; - j++; + V[i][k] = V[i][k] - p; + V[i][k + 1] = V[i][k + 1] - p * q; + } + } + } } } - // copy dataset - var points = new Array(trainingSet.length); - for(i = 0; i < points.length; ++i) { - points[i] = trainingSet[i].slice(); + if (norm === 0) { + return; } - this.features = trainingSet[0].length; - for(i = 0; i < trainingLabels.length; ++i) { - points[i].push(trainingLabels[i]); - } + for (n = nn - 1; n >= 0; n--) { + p = d[n]; + q = e[n]; - var dimensions = new Array(trainingSet[0].length); - for(i = 0; i < dimensions.length; ++i) { - dimensions[i] = i; - } + if (q === 0) { + l = n; + H[n][n] = 1; + for (i = n - 1; i >= 0; i--) { + w = H[i][i] - p; + r = 0; + for (j = l; j <= n; j++) { + r = r + H[i][j] * H[j][n]; + } - this.kdtree = new KDTree(points, options.distance, dimensions); - this.k = options.k; - this.classes = classes; -}; + if (e[i] < 0) { + z = w; + s = r; + } else { + l = i; + if (e[i] === 0) { + H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm)); + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; + t = (x * s - z * r) / q; + H[i][n] = t; + H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z); + } -/** - * Function that returns the predictions given the dataset. - * - * @param dataset - * @returns {Array} - */ -KNN.prototype.predict = function (dataset) { - var predictions = new Array(dataset.length); - for(var i = 0; i < dataset.length; ++i) { - predictions[i] = this.getSinglePrediction(dataset[i]); - } + t = Math.abs(H[i][n]); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n] = H[j][n] / t; + } + } + } + } + } else if (q < 0) { + l = n - 1; - return predictions; -}; + if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { + H[n - 1][n - 1] = q / H[n][n - 1]; + H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; + } else { + cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); + H[n - 1][n - 1] = cdivres[0]; + H[n - 1][n] = cdivres[1]; + } -/** - * function that returns a prediction for a single case. - * @param currentCase - * @returns {number} - */ -KNN.prototype.getSinglePrediction = function (currentCase) { - var nearestPoints = this.kdtree.nearest(currentCase, this.k); - var pointsPerClass = new Array(this.classes); - var predictedClass = -1; - var maxPoints = -1; - var lastElement = nearestPoints[0][0].length - 1; + H[n][n - 1] = 0; + H[n][n] = 1; + for (i = n - 2; i >= 0; i--) { + ra = 0; + sa = 0; + for (j = l; j <= n; j++) { + ra = ra + H[i][j] * H[j][n - 1]; + sa = sa + H[i][j] * H[j][n]; + } - for(var i = 0; i < pointsPerClass.length; ++i) { - pointsPerClass[i] = 0; + w = H[i][i] - p; + + if (e[i] < 0) { + z = w; + r = ra; + s = sa; + } else { + l = i; + if (e[i] === 0) { + cdivres = cdiv(-ra, -sa, w, q); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; + vi = (d[i] - p) * 2 * q; + if (vr === 0 && vi === 0) { + vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); + } + cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { + H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; + H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; + } else { + cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); + H[i + 1][n - 1] = cdivres[0]; + H[i + 1][n] = cdivres[1]; + } + } + + t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n - 1] = H[j][n - 1] / t; + H[j][n] = H[j][n] / t; + } + } + } + } + } } - for(i = 0; i < nearestPoints.length; ++i) { - var currentClass = nearestPoints[i][0][lastElement]; - var currentPoints = ++pointsPerClass[currentClass]; - if(currentPoints > maxPoints) { - predictedClass = currentClass; - maxPoints = currentPoints; + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + for (j = i; j < nn; j++) { + V[i][j] = H[i][j]; + } } } - return predictedClass; -}; + for (j = nn - 1; j >= low; j--) { + for (i = low; i <= high; i++) { + z = 0; + for (k = low; k <= Math.min(j, high); k++) { + z = z + V[i][k] * H[k][j]; + } + V[i][j] = z; + } + } +} -/** - * function that returns a KNN classifier with the given model. - * - * @param model - */ -KNN.load = function (model) { - if(model.modelName !== "KNN") - throw new RangeError("The given model is invalid!"); +function cdiv(xr, xi, yr, yi) { + var r, d; + if (Math.abs(yr) > Math.abs(yi)) { + r = yi / yr; + d = yr + r * yi; + return [(xr + r * xi) / d, (xi - r * xr) / d]; + } else { + r = yr / yi; + d = yi + r * yr; + return [(r * xr + xi) / d, (r * xi - xr) / d]; + } +} - return new KNN(true, model); -}; +/* unused harmony default export */ var _unused_webpack_default_export = (EigenvalueDecomposition); -/** - * function that exports the current KNN classifier. - */ -KNN.prototype.export = function () { - return { - modelName: "KNN", - kdtree: this.kdtree, - k: this.k, - classes: this.classes - }; -}; /***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { +/* 205 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* unused harmony export inverse */ +/* harmony export (immutable) */ __webpack_exports__["a"] = solve; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__dc_lu__ = __webpack_require__(29); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__dc_qr__ = __webpack_require__(66); -var Matrix = __webpack_require__(3).Matrix; -// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs -function CholeskyDecomposition(value) { - if (!(this instanceof CholeskyDecomposition)) { - return new CholeskyDecomposition(value); - } - value = Matrix.checkMatrix(value); - if (!value.isSymmetric()) { - throw new Error('Matrix is not symmetric'); - } - var a = value, - dimension = a.rows, - l = new Matrix(dimension, dimension), - positiveDefinite = true, - i, j, k; - for (j = 0; j < dimension; j++) { - var Lrowj = l[j]; - var d = 0; - for (k = 0; k < j; k++) { - var Lrowk = l[k]; - var s = 0; - for (i = 0; i < k; i++) { - s += Lrowk[i] * Lrowj[i]; - } - Lrowj[k] = s = (a[j][k] - s) / l[k][k]; - d = d + s * s; - } +function inverse(matrix) { + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + return solve(matrix, __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].eye(matrix.rows)); +} - d = a[j][j] - d; +function solve(leftHandSide, rightHandSide) { + leftHandSide = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(leftHandSide); + rightHandSide = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(rightHandSide); + return leftHandSide.isSquare() ? new __WEBPACK_IMPORTED_MODULE_1__dc_lu__["a" /* default */](leftHandSide).solve(rightHandSide) : new __WEBPACK_IMPORTED_MODULE_2__dc_qr__["a" /* default */](leftHandSide).solve(rightHandSide); +} - positiveDefinite &= (d > 0); - l[j][j] = Math.sqrt(Math.max(d, 0)); - for (k = j + 1; k < dimension; k++) { - l[j][k] = 0; - } - } - if (!positiveDefinite) { - throw new Error('Matrix is not positive definite'); - } +/***/ }), +/* 206 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(5); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_0__matrix__["a"]; }); +/* unused harmony reexport Matrix */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__ = __webpack_require__(28); +/* unused harmony reexport abstractMatrix */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__decompositions__ = __webpack_require__(205); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __WEBPACK_IMPORTED_MODULE_2__decompositions__["a"]; }); +/* unused harmony reexport inverse */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__dc_svd_js__ = __webpack_require__(67); +/* unused harmony reexport SingularValueDecomposition */ +/* unused harmony reexport SVD */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__dc_evd_js__ = __webpack_require__(204); +/* unused harmony reexport EigenvalueDecomposition */ +/* unused harmony reexport EVD */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__dc_cholesky_js__ = __webpack_require__(203); +/* unused harmony reexport CholeskyDecomposition */ +/* unused harmony reexport CHO */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__dc_lu_js__ = __webpack_require__(29); +/* unused harmony reexport LuDecomposition */ +/* unused harmony reexport LU */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__dc_qr_js__ = __webpack_require__(66); +/* unused harmony reexport QrDecomposition */ +/* unused harmony reexport QR */ - this.L = l; -} -CholeskyDecomposition.prototype = { - get lowerTriangularMatrix() { - return this.L; - }, - solve: function (value) { - value = Matrix.checkMatrix(value); - var l = this.L, - dimension = l.rows; - if (value.rows !== dimension) { - throw new Error('Matrix dimensions do not match'); - } - var count = value.columns, - B = value.clone(), - i, j, k; - for (k = 0; k < dimension; k++) { - for (j = 0; j < count; j++) { - for (i = 0; i < k; i++) { - B[k][j] -= B[i][j] * l[k][i]; - } - B[k][j] /= l[k][k]; - } - } - for (k = dimension - 1; k >= 0; k--) { - for (j = 0; j < count; j++) { - for (i = k + 1; i < dimension; i++) { - B[k][j] -= B[i][j] * l[i][k]; - } - B[k][j] /= l[k][k]; - } - } - return B; - } -}; -module.exports = CholeskyDecomposition; /***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +/* 207 */ +/***/ (function(module, exports) { +if (!Symbol.species) { + Symbol.species = Symbol.for('@@species'); +} -const Matrix = __webpack_require__(3).Matrix; -const util = __webpack_require__(11); -const hypotenuse = util.hypotenuse; -const getFilled2DArray = util.getFilled2DArray; -const defaultOptions = { - assumeSymmetric: false -}; +/***/ }), +/* 208 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { -// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs -function EigenvalueDecomposition(matrix, options) { - options = Object.assign({}, defaultOptions, options); - if (!(this instanceof EigenvalueDecomposition)) { - return new EigenvalueDecomposition(matrix, options); - } - matrix = Matrix.checkMatrix(matrix); - if (!matrix.isSquare()) { - throw new Error('Matrix is not a square matrix'); - } +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(10); - var n = matrix.columns, - V = getFilled2DArray(n, n, 0), - d = new Array(n), - e = new Array(n), - value = matrix, - i, j; - var isSymmetric = false; - if (options.assumeSymmetric) { - isSymmetric = true; - } else { - isSymmetric = matrix.isSymmetric(); +class MatrixColumnView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, column) { + super(matrix, matrix.rows, 1); + this.column = column; } - if (isSymmetric) { - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - V[i][j] = value.get(i, j); - } - } - tred2(n, e, d, V); - tql2(n, e, d, V); - } else { - var H = getFilled2DArray(n, n, 0), - ort = new Array(n); - for (j = 0; j < n; j++) { - for (i = 0; i < n; i++) { - H[i][j] = value.get(i, j); - } - } - orthes(n, H, ort, V); - hqr2(n, e, d, V, H); + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.column, value); + return this; } - this.n = n; - this.e = e; - this.d = d; - this.V = V; + get(rowIndex) { + return this.matrix.get(rowIndex, this.column); + } } +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixColumnView; -EigenvalueDecomposition.prototype = { - get realEigenvalues() { - return this.d; - }, - get imaginaryEigenvalues() { - return this.e; - }, - get eigenvectorMatrix() { - if (!Matrix.isMatrix(this.V)) { - this.V = new Matrix(this.V); - } - return this.V; - }, - get diagonalMatrix() { - var n = this.n, - e = this.e, - d = this.d, - X = new Matrix(n, n), - i, j; - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - X[i][j] = 0; - } - X[i][i] = d[i]; - if (e[i] > 0) { - X[i][i + 1] = e[i]; - } else if (e[i] < 0) { - X[i][i - 1] = e[i]; - } - } - return X; - } -}; -function tred2(n, e, d, V) { - var f, g, h, i, j, k, - hh, scale; +/***/ }), +/* 209 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - for (j = 0; j < n; j++) { - d[j] = V[n - 1][j]; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(10); + + +class MatrixFlipColumnView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); } - for (i = n - 1; i > 0; i--) { - scale = 0; - h = 0; - for (k = 0; k < i; k++) { - scale = scale + Math.abs(d[k]); - } + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); + return this; + } - if (scale === 0) { - e[i] = d[i - 1]; - for (j = 0; j < i; j++) { - d[j] = V[i - 1][j]; - V[i][j] = 0; - V[j][i] = 0; - } - } else { - for (k = 0; k < i; k++) { - d[k] /= scale; - h += d[k] * d[k]; - } + get(rowIndex, columnIndex) { + return this.matrix.get(rowIndex, this.columns - columnIndex - 1); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixFlipColumnView; - f = d[i - 1]; - g = Math.sqrt(h); - if (f > 0) { - g = -g; - } - e[i] = scale * g; - h = h - f * g; - d[i - 1] = f - g; - for (j = 0; j < i; j++) { - e[j] = 0; - } - for (j = 0; j < i; j++) { - f = d[j]; - V[j][i] = f; - g = e[j] + V[j][j] * f; - for (k = j + 1; k <= i - 1; k++) { - g += V[k][j] * d[k]; - e[k] += V[k][j] * f; - } - e[j] = g; - } +/***/ }), +/* 210 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - f = 0; - for (j = 0; j < i; j++) { - e[j] /= h; - f += e[j] * d[j]; - } +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(10); - hh = f / (h + h); - for (j = 0; j < i; j++) { - e[j] -= hh * d[j]; - } - for (j = 0; j < i; j++) { - f = d[j]; - g = e[j]; - for (k = j; k <= i - 1; k++) { - V[k][j] -= (f * e[k] + g * d[k]); - } - d[j] = V[i - 1][j]; - V[i][j] = 0; - } - } - d[i] = h; +class MatrixFlipRowView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); } - for (i = 0; i < n - 1; i++) { - V[n - 1][i] = V[i][i]; - V[i][i] = 1; - h = d[i + 1]; - if (h !== 0) { - for (k = 0; k <= i; k++) { - d[k] = V[k][i + 1] / h; - } + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); + return this; + } - for (j = 0; j <= i; j++) { - g = 0; - for (k = 0; k <= i; k++) { - g += V[k][i + 1] * V[k][j]; - } - for (k = 0; k <= i; k++) { - V[k][j] -= g * d[k]; - } - } - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.rows - rowIndex - 1, columnIndex); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixFlipRowView; - for (k = 0; k <= i; k++) { - V[k][i + 1] = 0; - } + + +/***/ }), +/* 211 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(10); + + +class MatrixRowView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, row) { + super(matrix, 1, matrix.columns); + this.row = row; } - for (j = 0; j < n; j++) { - d[j] = V[n - 1][j]; - V[n - 1][j] = 0; + set(rowIndex, columnIndex, value) { + this.matrix.set(this.row, columnIndex, value); + return this; } - V[n - 1][n - 1] = 1; - e[0] = 0; + get(rowIndex, columnIndex) { + return this.matrix.get(this.row, columnIndex); + } } +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixRowView; -function tql2(n, e, d, V) { - var g, h, i, j, k, l, m, p, r, - dl1, c, c2, c3, el1, s, s2, - iter; - for (i = 1; i < n; i++) { - e[i - 1] = e[i]; - } +/***/ }), +/* 212 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - e[n - 1] = 0; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(17); - var f = 0, - tst1 = 0, - eps = Math.pow(2, -52); - for (l = 0; l < n; l++) { - tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); - m = l; - while (m < n) { - if (Math.abs(e[m]) <= eps * tst1) { - break; - } - m++; - } - if (m > l) { - iter = 0; - do { - iter = iter + 1; +class MatrixSelectionView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, rowIndices, columnIndices) { + var indices = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["i" /* checkIndices */])(matrix, rowIndices, columnIndices); + super(matrix, indices.row.length, indices.column.length); + this.rowIndices = indices.row; + this.columnIndices = indices.column; + } - g = d[l]; - p = (d[l + 1] - g) / (2 * e[l]); - r = hypotenuse(p, 1); - if (p < 0) { - r = -r; - } + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); + return this; + } - d[l] = e[l] / (p + r); - d[l + 1] = e[l] * (p + r); - dl1 = d[l + 1]; - h = g - d[l]; - for (i = l + 2; i < n; i++) { - d[i] -= h; - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixSelectionView; - f = f + h; - p = d[m]; - c = 1; - c2 = c; - c3 = c; - el1 = e[l + 1]; - s = 0; - s2 = 0; - for (i = m - 1; i >= l; i--) { - c3 = c2; - c2 = c; - s2 = s; - g = c * e[i]; - h = c * p; - r = hypotenuse(p, e[i]); - e[i + 1] = s * r; - s = e[i] / r; - c = p / r; - p = c * d[i] - s * g; - d[i + 1] = h + s * (c * g + s * d[i]); - for (k = 0; k < n; k++) { - h = V[k][i + 1]; - V[k][i + 1] = s * V[k][i] + c * h; - V[k][i] = c * V[k][i] - s * h; - } - } +/***/ }), +/* 213 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - p = -s * s2 * c3 * el1 * e[l] / dl1; - e[l] = s * p; - d[l] = c * p; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(17); - } - while (Math.abs(e[l]) > eps * tst1); - } - d[l] = d[l] + f; - e[l] = 0; + + +class MatrixSubView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, startRow, endRow, startColumn, endColumn) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["h" /* checkRange */])(matrix, startRow, endRow, startColumn, endColumn); + super(matrix, endRow - startRow + 1, endColumn - startColumn + 1); + this.startRow = startRow; + this.startColumn = startColumn; } - 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]; - } - } + set(rowIndex, columnIndex, value) { + this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); + return this; + } - if (k !== i) { - d[k] = d[i]; - d[i] = p; - for (j = 0; j < n; j++) { - p = V[j][i]; - V[j][i] = V[j][k]; - V[j][k] = p; - } - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); } } +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixSubView; -function orthes(n, H, ort, V) { - var low = 0, - high = n - 1, - f, g, h, i, j, m, - scale; - for (m = low + 1; m <= high - 1; m++) { - scale = 0; - for (i = m; i <= high; i++) { - scale = scale + Math.abs(H[i][m - 1]); - } +/***/ }), +/* 214 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - if (scale !== 0) { - h = 0; - for (i = high; i >= m; i--) { - ort[i] = H[i][m - 1] / scale; - h += ort[i] * ort[i]; - } +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(10); - g = Math.sqrt(h); - if (ort[m] > 0) { - g = -g; - } - h = h - ort[m] * g; - ort[m] = ort[m] - g; +class MatrixTransposeView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.columns, matrix.rows); + } - for (j = m; j < n; j++) { - f = 0; - for (i = high; i >= m; i--) { - f += ort[i] * H[i][j]; - } + set(rowIndex, columnIndex, value) { + this.matrix.set(columnIndex, rowIndex, value); + return this; + } - f = f / h; - for (i = m; i <= high; i++) { - H[i][j] -= f * ort[i]; - } - } + get(rowIndex, columnIndex) { + return this.matrix.get(columnIndex, rowIndex); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixTransposeView; - for (i = 0; i <= high; i++) { - f = 0; - for (j = high; j >= m; j--) { - f += ort[j] * H[i][j]; - } - f = f / h; - for (j = m; j <= high; j++) { - H[i][j] -= f * ort[j]; - } - } - ort[m] = scale * ort[m]; - H[m][m - 1] = scale * g; - } - } +/***/ }), +/* 215 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - V[i][j] = (i === j ? 1 : 0); - } - } +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ml_regression_simple_linear__ = __webpack_require__(34); - for (m = high - 1; m >= low + 1; m--) { - if (H[m][m - 1] !== 0) { - for (i = m + 1; i <= high; i++) { - ort[i] = H[i][m - 1]; - } - for (j = m; j <= high; j++) { - g = 0; - for (i = m; i <= high; i++) { - g += ort[i] * V[i][j]; - } - g = (g / ort[m]) / H[m][m - 1]; - for (i = m; i <= high; i++) { - V[i][j] += g * ort[i]; - } - } +class PowerRegression extends __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["a" /* default */] { + constructor(x, y) { + super(); + if (x === true) { // reloading model + this.A = y.A; + this.B = y.B; + } else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["b" /* checkArrayLength */])(x, y); + regress(this, x, y); } } -} -function hqr2(nn, e, d, V, H) { - var n = nn - 1, - low = 0, - high = nn - 1, - eps = Math.pow(2, -52), - exshift = 0, - norm = 0, - p = 0, - q = 0, - r = 0, - s = 0, - z = 0, - iter = 0, - i, j, k, l, m, t, w, x, y, - ra, sa, vr, vi, - notlast, cdivres; + _predict(newInputs) { + return this.A * Math.pow(newInputs, this.B); + } - for (i = 0; i < nn; i++) { - if (i < low || i > high) { - d[i] = H[i][i]; - e[i] = 0; - } + toJSON() { + return { + name: 'powerRegression', + A: this.A, + B: this.B + }; + } - for (j = Math.max(i - 1, 0); j < nn; j++) { - norm = norm + Math.abs(H[i][j]); + toString(precision) { + return 'f(x) = ' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.A, precision) + ' * x^' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.B, precision); + } + + toLaTeX(precision) { + if (this.B >= 0) { + return 'f(x) = ' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.A, precision) + 'x^{' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.B, precision) + '}'; + } else { + return 'f(x) = \\frac{' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.A, precision) + '}{x^{' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(-this.B, precision) + '}}'; } } - while (n >= low) { - l = n; - while (l > low) { - s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); - if (s === 0) { - s = norm; - } - if (Math.abs(H[l][l - 1]) < eps * s) { - break; - } - l--; + static load(json) { + if (json.name !== 'powerRegression') { + throw new TypeError('not a power regression model'); } + return new PowerRegression(true, json); + } +} +/* harmony export (immutable) */ __webpack_exports__["default"] = PowerRegression; - if (l === n) { - H[n][n] = H[n][n] + exshift; - d[n] = H[n][n]; - e[n] = 0; - n--; - iter = 0; - } else if (l === n - 1) { - w = H[n][n - 1] * H[n - 1][n]; - p = (H[n - 1][n - 1] - H[n][n]) / 2; - q = p * p + w; - z = Math.sqrt(Math.abs(q)); - H[n][n] = H[n][n] + exshift; - H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; - x = H[n][n]; - - if (q >= 0) { - z = (p >= 0) ? (p + z) : (p - z); - d[n - 1] = x + z; - d[n] = d[n - 1]; - if (z !== 0) { - d[n] = x - w / z; - } - e[n - 1] = 0; - e[n] = 0; - x = H[n][n - 1]; - s = Math.abs(x) + Math.abs(z); - p = x / s; - q = z / s; - r = Math.sqrt(p * p + q * q); - p = p / r; - q = q / r; - for (j = n - 1; j < nn; j++) { - z = H[n - 1][j]; - H[n - 1][j] = q * z + p * H[n][j]; - H[n][j] = q * H[n][j] - p * z; - } +function regress(pr, x, y) { + const n = x.length; + const xl = new Array(n); + const yl = new Array(n); + for (let i = 0; i < n; i++) { + xl[i] = Math.log(x[i]); + yl[i] = Math.log(y[i]); + } - for (i = 0; i <= n; i++) { - z = H[i][n - 1]; - H[i][n - 1] = q * z + p * H[i][n]; - H[i][n] = q * H[i][n] - p * z; - } + const linear = new __WEBPACK_IMPORTED_MODULE_1_ml_regression_simple_linear__["default"](xl, yl); + pr.A = Math.exp(linear.intercept); + pr.B = linear.slope; +} - for (i = low; i <= high; i++) { - z = V[i][n - 1]; - V[i][n - 1] = q * z + p * V[i][n]; - V[i][n] = q * V[i][n] - p * z; - } - } else { - d[n - 1] = x + p; - d[n] = x + p; - e[n - 1] = z; - e[n] = -z; - } - n = n - 2; - iter = 0; - } else { - x = H[n][n]; - y = 0; - w = 0; - if (l < n) { - y = H[n - 1][n - 1]; - w = H[n][n - 1] * H[n - 1][n]; - } +/***/ }), +/* 216 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - if (iter === 10) { - exshift += x; - for (i = low; i <= n; i++) { - H[i][i] -= x; - } - s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); - x = y = 0.75 * s; - w = -0.4375 * s * s; - } +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(6); - if (iter === 30) { - s = (y - x) / 2; - s = s * s + w; - if (s > 0) { - s = Math.sqrt(s); - if (y < x) { - s = -s; - } - s = x - w / ((y - x) / 2 + s); - for (i = low; i <= n; i++) { - H[i][i] -= s; - } - exshift += s; - x = y = w = 0.964; - } - } - iter = iter + 1; +// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs +function CholeskyDecomposition(value) { + if (!(this instanceof CholeskyDecomposition)) { + return new CholeskyDecomposition(value); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + if (!value.isSymmetric()) { + throw new Error('Matrix is not symmetric'); + } - m = n - 2; - while (m >= l) { - z = H[m][m]; - r = x - z; - s = y - z; - p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; - q = H[m + 1][m + 1] - z - r - s; - r = H[m + 2][m + 1]; - s = Math.abs(p) + Math.abs(q) + Math.abs(r); - p = p / s; - q = q / s; - r = r / s; - if (m === l) { - break; - } - if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { - break; - } - m--; - } + var a = value, + dimension = a.rows, + l = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](dimension, dimension), + positiveDefinite = true, + i, j, k; - for (i = m + 2; i <= n; i++) { - H[i][i - 2] = 0; - if (i > m + 2) { - H[i][i - 3] = 0; - } + for (j = 0; j < dimension; j++) { + var Lrowj = l[j]; + var d = 0; + for (k = 0; k < j; k++) { + var Lrowk = l[k]; + var s = 0; + for (i = 0; i < k; i++) { + s += Lrowk[i] * Lrowj[i]; } + Lrowj[k] = s = (a[j][k] - s) / l[k][k]; + d = d + s * s; + } - for (k = m; k <= n - 1; k++) { - notlast = (k !== n - 1); - if (k !== m) { - p = H[k][k - 1]; - q = H[k + 1][k - 1]; - r = (notlast ? H[k + 2][k - 1] : 0); - x = Math.abs(p) + Math.abs(q) + Math.abs(r); - if (x !== 0) { - p = p / x; - q = q / x; - r = r / x; - } - } - - if (x === 0) { - break; - } + d = a[j][j] - d; - s = Math.sqrt(p * p + q * q + r * r); - if (p < 0) { - s = -s; - } + positiveDefinite &= (d > 0); + l[j][j] = Math.sqrt(Math.max(d, 0)); + for (k = j + 1; k < dimension; k++) { + l[j][k] = 0; + } + } - if (s !== 0) { - if (k !== m) { - H[k][k - 1] = -s * x; - } else if (l !== m) { - H[k][k - 1] = -H[k][k - 1]; - } + if (!positiveDefinite) { + throw new Error('Matrix is not positive definite'); + } - p = p + s; - x = p / s; - y = q / s; - z = r / s; - q = q / p; - r = r / p; + this.L = l; +} - for (j = k; j < nn; j++) { - p = H[k][j] + q * H[k + 1][j]; - if (notlast) { - p = p + r * H[k + 2][j]; - H[k + 2][j] = H[k + 2][j] - p * z; - } +CholeskyDecomposition.prototype = { + get lowerTriangularMatrix() { + return this.L; + }, + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); - H[k][j] = H[k][j] - p * x; - H[k + 1][j] = H[k + 1][j] - p * y; - } + var l = this.L, + dimension = l.rows; - for (i = 0; i <= Math.min(n, k + 3); i++) { - p = x * H[i][k] + y * H[i][k + 1]; - if (notlast) { - p = p + z * H[i][k + 2]; - H[i][k + 2] = H[i][k + 2] - p * r; - } + if (value.rows !== dimension) { + throw new Error('Matrix dimensions do not match'); + } - H[i][k] = H[i][k] - p; - H[i][k + 1] = H[i][k + 1] - p * q; - } + var count = value.columns, + B = value.clone(), + i, j, k; - for (i = low; i <= high; i++) { - p = x * V[i][k] + y * V[i][k + 1]; - if (notlast) { - p = p + z * V[i][k + 2]; - V[i][k + 2] = V[i][k + 2] - p * r; - } + for (k = 0; k < dimension; k++) { + for (j = 0; j < count; j++) { + for (i = 0; i < k; i++) { + B[k][j] -= B[i][j] * l[k][i]; + } + B[k][j] /= l[k][k]; + } + } - V[i][k] = V[i][k] - p; - V[i][k + 1] = V[i][k + 1] - p * q; - } + for (k = dimension - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + for (i = k + 1; i < dimension; i++) { + B[k][j] -= B[i][j] * l[i][k]; } + B[k][j] /= l[k][k]; } } - } - if (norm === 0) { - return; + return B; } +}; - for (n = nn - 1; n >= 0; n--) { - p = d[n]; - q = e[n]; +/* unused harmony default export */ var _unused_webpack_default_export = (CholeskyDecomposition); - if (q === 0) { - l = n; - H[n][n] = 1; - for (i = n - 1; i >= 0; i--) { - w = H[i][i] - p; - r = 0; - for (j = l; j <= n; j++) { - r = r + H[i][j] * H[j][n]; - } - if (e[i] < 0) { - z = w; - s = r; - } else { - l = i; - if (e[i] === 0) { - H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm)); - } else { - x = H[i][i + 1]; - y = H[i + 1][i]; - q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; - t = (x * s - z * r) / q; - H[i][n] = t; - H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z); - } +/***/ }), +/* 217 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - t = Math.abs(H[i][n]); - if ((eps * t) * t > 1) { - for (j = i; j <= n; j++) { - H[j][n] = H[j][n] / t; - } - } - } - } - } else if (q < 0) { - l = n - 1; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(33); - if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { - H[n - 1][n - 1] = q / H[n][n - 1]; - H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; - } else { - cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); - H[n - 1][n - 1] = cdivres[0]; - H[n - 1][n] = cdivres[1]; - } - H[n][n - 1] = 0; - H[n][n] = 1; - for (i = n - 2; i >= 0; i--) { - ra = 0; - sa = 0; - for (j = l; j <= n; j++) { - ra = ra + H[i][j] * H[j][n - 1]; - sa = sa + H[i][j] * H[j][n]; - } - w = H[i][i] - p; +const defaultOptions = { + assumeSymmetric: false +}; - if (e[i] < 0) { - z = w; - r = ra; - s = sa; - } else { - l = i; - if (e[i] === 0) { - cdivres = cdiv(-ra, -sa, w, q); - H[i][n - 1] = cdivres[0]; - H[i][n] = cdivres[1]; - } else { - x = H[i][i + 1]; - y = H[i + 1][i]; - vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; - vi = (d[i] - p) * 2 * q; - if (vr === 0 && vi === 0) { - vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); - } - cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); - H[i][n - 1] = cdivres[0]; - H[i][n] = cdivres[1]; - if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { - H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; - H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; - } else { - cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); - H[i + 1][n - 1] = cdivres[0]; - H[i + 1][n] = cdivres[1]; - } - } +// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs +function EigenvalueDecomposition(matrix, options) { + options = Object.assign({}, defaultOptions, options); + if (!(this instanceof EigenvalueDecomposition)) { + return new EigenvalueDecomposition(matrix, options); + } + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + if (!matrix.isSquare()) { + throw new Error('Matrix is not a square matrix'); + } - t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); - if ((eps * t) * t > 1) { - for (j = i; j <= n; j++) { - H[j][n - 1] = H[j][n - 1] / t; - H[j][n] = H[j][n] / t; - } - } - } - } - } + var n = matrix.columns, + V = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + d = new Array(n), + e = new Array(n), + value = matrix, + i, j; + + var isSymmetric = false; + if (options.assumeSymmetric) { + isSymmetric = true; + } else { + isSymmetric = matrix.isSymmetric(); } - for (i = 0; i < nn; i++) { - if (i < low || i > high) { - for (j = i; j < nn; j++) { - V[i][j] = H[i][j]; + if (isSymmetric) { + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = value.get(i, j); } } - } - - for (j = nn - 1; j >= low; j--) { - for (i = low; i <= high; i++) { - z = 0; - for (k = low; k <= Math.min(j, high); k++) { - z = z + V[i][k] * H[k][j]; + tred2(n, e, d, V); + tql2(n, e, d, V); + } else { + var H = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + ort = new Array(n); + for (j = 0; j < n; j++) { + for (i = 0; i < n; i++) { + H[i][j] = value.get(i, j); } - V[i][j] = z; } + orthes(n, H, ort, V); + hqr2(n, e, d, V, H); } + + this.n = n; + this.e = e; + this.d = d; + this.V = V; } -function cdiv(xr, xi, yr, yi) { - var r, d; - if (Math.abs(yr) > Math.abs(yi)) { - r = yi / yr; - d = yr + r * yi; - return [(xr + r * xi) / d, (xi - r * xr) / d]; - } else { - r = yr / yi; - d = yi + r * yr; - return [(r * xr + xi) / d, (r * xi - xr) / d]; +EigenvalueDecomposition.prototype = { + get realEigenvalues() { + return this.d; + }, + get imaginaryEigenvalues() { + return this.e; + }, + get eigenvectorMatrix() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.V)) { + this.V = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.V); + } + return this.V; + }, + get diagonalMatrix() { + var n = this.n, + e = this.e, + d = this.d, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + X[i][j] = 0; + } + X[i][i] = d[i]; + if (e[i] > 0) { + X[i][i + 1] = e[i]; + } else if (e[i] < 0) { + X[i][i - 1] = e[i]; + } + } + return X; } -} +}; -module.exports = EigenvalueDecomposition; +function tred2(n, e, d, V) { + var f, g, h, i, j, k, + hh, scale; -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + } -"use strict"; + for (i = n - 1; i > 0; i--) { + scale = 0; + h = 0; + for (k = 0; k < i; k++) { + scale = scale + Math.abs(d[k]); + } + + if (scale === 0) { + e[i] = d[i - 1]; + for (j = 0; j < i; j++) { + d[j] = V[i - 1][j]; + V[i][j] = 0; + V[j][i] = 0; + } + } else { + for (k = 0; k < i; k++) { + d[k] /= scale; + h += d[k] * d[k]; + } + f = d[i - 1]; + g = Math.sqrt(h); + if (f > 0) { + g = -g; + } -var Matrix = __webpack_require__(3).Matrix; -var hypotenuse = __webpack_require__(11).hypotenuse; + e[i] = scale * g; + h = h - f * g; + d[i - 1] = f - g; + for (j = 0; j < i; j++) { + e[j] = 0; + } -//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs -function QrDecomposition(value) { - if (!(this instanceof QrDecomposition)) { - return new QrDecomposition(value); - } - value = Matrix.checkMatrix(value); + for (j = 0; j < i; j++) { + f = d[j]; + V[j][i] = f; + g = e[j] + V[j][j] * f; + for (k = j + 1; k <= i - 1; k++) { + g += V[k][j] * d[k]; + e[k] += V[k][j] * f; + } + e[j] = g; + } + + f = 0; + for (j = 0; j < i; j++) { + e[j] /= h; + f += e[j] * d[j]; + } - var qr = value.clone(), - m = value.rows, - n = value.columns, - rdiag = new Array(n), - i, j, k, s; + hh = f / (h + h); + for (j = 0; j < i; j++) { + e[j] -= hh * d[j]; + } - for (k = 0; k < n; k++) { - var nrm = 0; - for (i = k; i < m; i++) { - nrm = hypotenuse(nrm, qr[i][k]); - } - if (nrm !== 0) { - if (qr[k][k] < 0) { - nrm = -nrm; + for (j = 0; j < i; j++) { + f = d[j]; + g = e[j]; + for (k = j; k <= i - 1; k++) { + V[k][j] -= (f * e[k] + g * d[k]); + } + d[j] = V[i - 1][j]; + V[i][j] = 0; } - for (i = k; i < m; i++) { - qr[i][k] /= nrm; + } + d[i] = h; + } + + for (i = 0; i < n - 1; i++) { + V[n - 1][i] = V[i][i]; + V[i][i] = 1; + h = d[i + 1]; + if (h !== 0) { + for (k = 0; k <= i; k++) { + d[k] = V[k][i + 1] / h; } - qr[k][k] += 1; - for (j = k + 1; j < n; j++) { - s = 0; - for (i = k; i < m; i++) { - s += qr[i][k] * qr[i][j]; + + for (j = 0; j <= i; j++) { + g = 0; + for (k = 0; k <= i; k++) { + g += V[k][i + 1] * V[k][j]; } - s = -s / qr[k][k]; - for (i = k; i < m; i++) { - qr[i][j] += s * qr[i][k]; + for (k = 0; k <= i; k++) { + V[k][j] -= g * d[k]; } } } - rdiag[k] = -nrm; + + for (k = 0; k <= i; k++) { + V[k][i + 1] = 0; + } } - this.QR = qr; - this.Rdiag = rdiag; + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + V[n - 1][j] = 0; + } + + V[n - 1][n - 1] = 1; + e[0] = 0; } -QrDecomposition.prototype = { - solve: function (value) { - value = Matrix.checkMatrix(value); +function tql2(n, e, d, V) { - var qr = this.QR, - m = qr.rows; + var g, h, i, j, k, l, m, p, r, + dl1, c, c2, c3, el1, s, s2, + iter; - if (value.rows !== m) { - throw new Error('Matrix row dimensions must agree'); - } - if (!this.isFullRank()) { - throw new Error('Matrix is rank deficient'); - } + for (i = 1; i < n; i++) { + e[i - 1] = e[i]; + } - var count = value.columns; - var X = value.clone(); - var n = qr.columns; - var i, j, k, s; + e[n - 1] = 0; - for (k = 0; k < n; k++) { - for (j = 0; j < count; j++) { - s = 0; - for (i = k; i < m; i++) { - s += qr[i][k] * X[i][j]; - } - s = -s / qr[k][k]; - for (i = k; i < m; i++) { - X[i][j] += s * qr[i][k]; - } + var f = 0, + tst1 = 0, + eps = Math.pow(2, -52); + + for (l = 0; l < n; l++) { + tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); + m = l; + while (m < n) { + if (Math.abs(e[m]) <= eps * tst1) { + break; } + m++; } - for (k = n - 1; k >= 0; k--) { - for (j = 0; j < count; j++) { - X[k][j] /= this.Rdiag[k]; - } - for (i = 0; i < k; i++) { - for (j = 0; j < count; j++) { - X[i][j] -= X[k][j] * qr[i][k]; + + if (m > l) { + iter = 0; + do { + iter = iter + 1; + + g = d[l]; + p = (d[l + 1] - g) / (2 * e[l]); + r = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(p, 1); + if (p < 0) { + r = -r; } - } - } - return X.subMatrix(0, n - 1, 0, count - 1); - }, - isFullRank: function () { - var columns = this.QR.columns; - for (var i = 0; i < columns; i++) { - if (this.Rdiag[i] === 0) { - return false; - } - } - return true; - }, - get upperTriangularMatrix() { - var qr = this.QR, - n = qr.columns, - X = new Matrix(n, n), - i, j; - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - if (i < j) { - X[i][j] = qr[i][j]; - } else if (i === j) { - X[i][j] = this.Rdiag[i]; - } else { - X[i][j] = 0; + d[l] = e[l] / (p + r); + d[l + 1] = e[l] * (p + r); + dl1 = d[l + 1]; + h = g - d[l]; + for (i = l + 2; i < n; i++) { + d[i] -= h; } - } - } - return X; - }, - get orthogonalMatrix() { - var qr = this.QR, - rows = qr.rows, - columns = qr.columns, - X = new Matrix(rows, columns), - i, j, k, s; - for (k = columns - 1; k >= 0; k--) { - for (i = 0; i < rows; i++) { - X[i][k] = 0; - } - X[k][k] = 1; - for (j = k; j < columns; j++) { - if (qr[k][k] !== 0) { - s = 0; - for (i = k; i < rows; i++) { - s += qr[i][k] * X[i][j]; - } + f = f + h; - s = -s / qr[k][k]; + p = d[m]; + c = 1; + c2 = c; + c3 = c; + el1 = e[l + 1]; + s = 0; + s2 = 0; + for (i = m - 1; i >= l; i--) { + c3 = c2; + c2 = c; + s2 = s; + g = c * e[i]; + h = c * p; + r = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* 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 (i = k; i < rows; i++) { - X[i][j] += s * qr[i][k]; + for (k = 0; k < n; k++) { + h = V[k][i + 1]; + V[k][i + 1] = s * V[k][i] + c * h; + V[k][i] = c * V[k][i] - s * h; } } + + p = -s * s2 * c3 * el1 * e[l] / dl1; + e[l] = s * p; + d[l] = c * p; + } + while (Math.abs(e[l]) > eps * tst1); } - return X; + d[l] = d[l] + f; + e[l] = 0; } -}; - -module.exports = QrDecomposition; - - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + 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]; + } + } -var Matrix = __webpack_require__(3).Matrix; -var util = __webpack_require__(11); -var hypotenuse = util.hypotenuse; -var getFilled2DArray = util.getFilled2DArray; - -// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs -function SingularValueDecomposition(value, options) { - if (!(this instanceof SingularValueDecomposition)) { - return new SingularValueDecomposition(value, options); + if (k !== i) { + d[k] = d[i]; + d[i] = p; + for (j = 0; j < n; j++) { + p = V[j][i]; + V[j][i] = V[j][k]; + V[j][k] = p; + } + } } - value = Matrix.checkMatrix(value); - - options = options || {}; +} - var m = value.rows, - n = value.columns, - nu = Math.min(m, n); +function orthes(n, H, ort, V) { - var wantu = true, wantv = true; - if (options.computeLeftSingularVectors === false) wantu = false; - if (options.computeRightSingularVectors === false) wantv = false; - var autoTranspose = options.autoTranspose === true; + var low = 0, + high = n - 1, + f, g, h, i, j, m, + scale; - var swapped = false; - var a; - if (m < n) { - if (!autoTranspose) { - a = value.clone(); - // eslint-disable-next-line no-console - console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose'); - } else { - a = value.transpose(); - m = a.rows; - n = a.columns; - swapped = true; - var aux = wantu; - wantu = wantv; - wantv = aux; + for (m = low + 1; m <= high - 1; m++) { + scale = 0; + for (i = m; i <= high; i++) { + scale = scale + Math.abs(H[i][m - 1]); } - } else { - a = value.clone(); - } - var s = new Array(Math.min(m + 1, n)), - U = getFilled2DArray(m, nu, 0), - V = getFilled2DArray(n, n, 0), - e = new Array(n), - work = new Array(m); + if (scale !== 0) { + h = 0; + for (i = high; i >= m; i--) { + ort[i] = H[i][m - 1] / scale; + h += ort[i] * ort[i]; + } - var nct = Math.min(m - 1, n); - var nrt = Math.max(0, Math.min(n - 2, m)); + g = Math.sqrt(h); + if (ort[m] > 0) { + g = -g; + } - var i, j, k, p, t, ks, f, cs, sn, max, kase, - scale, sp, spm1, epm1, sk, ek, b, c, shift, g; + h = h - ort[m] * g; + ort[m] = ort[m] - g; - for (k = 0, max = Math.max(nct, nrt); k < max; k++) { - if (k < nct) { - s[k] = 0; - for (i = k; i < m; i++) { - s[k] = hypotenuse(s[k], a[i][k]); - } - if (s[k] !== 0) { - if (a[k][k] < 0) { - s[k] = -s[k]; + for (j = m; j < n; j++) { + f = 0; + for (i = high; i >= m; i--) { + f += ort[i] * H[i][j]; } - for (i = k; i < m; i++) { - a[i][k] /= s[k]; + + f = f / h; + for (i = m; i <= high; i++) { + H[i][j] -= f * ort[i]; } - a[k][k] += 1; } - s[k] = -s[k]; - } - for (j = k + 1; j < n; j++) { - if ((k < nct) && (s[k] !== 0)) { - t = 0; - for (i = k; i < m; i++) { - t += a[i][k] * a[i][j]; + for (i = 0; i <= high; i++) { + f = 0; + for (j = high; j >= m; j--) { + f += ort[j] * H[i][j]; } - t = -t / a[k][k]; - for (i = k; i < m; i++) { - a[i][j] += t * a[i][k]; + + f = f / h; + for (j = m; j <= high; j++) { + H[i][j] -= f * ort[j]; } } - e[j] = a[k][j]; + + ort[m] = scale * ort[m]; + H[m][m - 1] = scale * g; } + } - if (wantu && (k < nct)) { - for (i = k; i < m; i++) { - U[i][k] = a[i][k]; - } + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = (i === j ? 1 : 0); } + } - if (k < nrt) { - e[k] = 0; - for (i = k + 1; i < n; i++) { - e[k] = hypotenuse(e[k], e[i]); - } - if (e[k] !== 0) { - if (e[k + 1] < 0) { - e[k] = 0 - e[k]; - } - for (i = k + 1; i < n; i++) { - e[i] /= e[k]; - } - e[k + 1] += 1; + for (m = high - 1; m >= low + 1; m--) { + if (H[m][m - 1] !== 0) { + for (i = m + 1; i <= high; i++) { + ort[i] = H[i][m - 1]; } - e[k] = -e[k]; - if ((k + 1 < m) && (e[k] !== 0)) { - for (i = k + 1; i < m; i++) { - work[i] = 0; - } - for (j = k + 1; j < n; j++) { - for (i = k + 1; i < m; i++) { - work[i] += e[j] * a[i][j]; - } - } - for (j = k + 1; j < n; j++) { - t = -e[j] / e[k + 1]; - for (i = k + 1; i < m; i++) { - a[i][j] += t * work[i]; - } + + for (j = m; j <= high; j++) { + g = 0; + for (i = m; i <= high; i++) { + g += ort[i] * V[i][j]; } - } - if (wantv) { - for (i = k + 1; i < n; i++) { - V[i][k] = e[i]; + + g = (g / ort[m]) / H[m][m - 1]; + for (i = m; i <= high; i++) { + V[i][j] += g * ort[i]; } } } } +} - p = Math.min(n, m + 1); - if (nct < n) { - s[nct] = a[nct][nct]; - } - if (m < p) { - s[p - 1] = 0; - } - if (nrt + 1 < p) { - e[nrt] = a[nrt][p - 1]; +function hqr2(nn, e, d, V, H) { + var n = nn - 1, + low = 0, + high = nn - 1, + eps = Math.pow(2, -52), + exshift = 0, + norm = 0, + p = 0, + q = 0, + r = 0, + s = 0, + z = 0, + iter = 0, + i, j, k, l, m, t, w, x, y, + ra, sa, vr, vi, + notlast, cdivres; + + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + d[i] = H[i][i]; + e[i] = 0; + } + + for (j = Math.max(i - 1, 0); j < nn; j++) { + norm = norm + Math.abs(H[i][j]); + } } - e[p - 1] = 0; - if (wantu) { - for (j = nct; j < nu; j++) { - for (i = 0; i < m; i++) { - U[i][j] = 0; + while (n >= low) { + l = n; + while (l > low) { + s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); + if (s === 0) { + s = norm; } - U[j][j] = 1; + if (Math.abs(H[l][l - 1]) < eps * s) { + break; + } + l--; } - for (k = nct - 1; k >= 0; k--) { - if (s[k] !== 0) { - for (j = k + 1; j < nu; j++) { - t = 0; - for (i = k; i < m; i++) { - t += U[i][k] * U[i][j]; - } - t = -t / U[k][k]; - for (i = k; i < m; i++) { - U[i][j] += t * U[i][k]; - } + + if (l === n) { + H[n][n] = H[n][n] + exshift; + d[n] = H[n][n]; + e[n] = 0; + n--; + iter = 0; + } else if (l === n - 1) { + w = H[n][n - 1] * H[n - 1][n]; + p = (H[n - 1][n - 1] - H[n][n]) / 2; + q = p * p + w; + z = Math.sqrt(Math.abs(q)); + H[n][n] = H[n][n] + exshift; + H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; + x = H[n][n]; + + if (q >= 0) { + z = (p >= 0) ? (p + z) : (p - z); + d[n - 1] = x + z; + d[n] = d[n - 1]; + if (z !== 0) { + d[n] = x - w / z; } - for (i = k; i < m; i++) { - U[i][k] = -U[i][k]; + e[n - 1] = 0; + e[n] = 0; + x = H[n][n - 1]; + s = Math.abs(x) + Math.abs(z); + p = x / s; + q = z / s; + r = Math.sqrt(p * p + q * q); + p = p / r; + q = q / r; + + for (j = n - 1; j < nn; j++) { + z = H[n - 1][j]; + H[n - 1][j] = q * z + p * H[n][j]; + H[n][j] = q * H[n][j] - p * z; + } + + for (i = 0; i <= n; i++) { + z = H[i][n - 1]; + H[i][n - 1] = q * z + p * H[i][n]; + H[i][n] = q * H[i][n] - p * z; } - U[k][k] = 1 + U[k][k]; - for (i = 0; i < k - 1; i++) { - U[i][k] = 0; + + for (i = low; i <= high; i++) { + z = V[i][n - 1]; + V[i][n - 1] = q * z + p * V[i][n]; + V[i][n] = q * V[i][n] - p * z; } } else { - for (i = 0; i < m; i++) { - U[i][k] = 0; + d[n - 1] = x + p; + d[n] = x + p; + e[n - 1] = z; + e[n] = -z; + } + + n = n - 2; + iter = 0; + } else { + x = H[n][n]; + y = 0; + w = 0; + if (l < n) { + y = H[n - 1][n - 1]; + w = H[n][n - 1] * H[n - 1][n]; + } + + if (iter === 10) { + exshift += x; + for (i = low; i <= n; i++) { + H[i][i] -= x; } - U[k][k] = 1; + s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); + x = y = 0.75 * s; + w = -0.4375 * s * s; } - } - } - if (wantv) { - for (k = n - 1; k >= 0; k--) { - if ((k < nrt) && (e[k] !== 0)) { - for (j = k + 1; j < n; j++) { - t = 0; - for (i = k + 1; i < n; i++) { - t += V[i][k] * V[i][j]; + if (iter === 30) { + s = (y - x) / 2; + s = s * s + w; + if (s > 0) { + s = Math.sqrt(s); + if (y < x) { + s = -s; } - t = -t / V[k + 1][k]; - for (i = k + 1; i < n; i++) { - V[i][j] += t * V[i][k]; + s = x - w / ((y - x) / 2 + s); + for (i = low; i <= n; i++) { + H[i][i] -= s; } + exshift += s; + x = y = w = 0.964; } } - for (i = 0; i < n; i++) { - V[i][k] = 0; - } - V[k][k] = 1; - } - } - var pp = p - 1, - iter = 0, - eps = Math.pow(2, -52); - while (p > 0) { - for (k = p - 2; k >= -1; k--) { - if (k === -1) { - break; - } - if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { - e[k] = 0; - break; - } - } - if (k === p - 2) { - kase = 4; - } else { - for (ks = p - 1; ks >= k; ks--) { - if (ks === k) { + iter = iter + 1; + + m = n - 2; + while (m >= l) { + z = H[m][m]; + r = x - z; + s = y - z; + p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; + q = H[m + 1][m + 1] - z - r - s; + r = H[m + 2][m + 1]; + s = Math.abs(p) + Math.abs(q) + Math.abs(r); + p = p / s; + q = q / s; + r = r / s; + if (m === l) { break; } - t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0); - if (Math.abs(s[ks]) <= eps * t) { - s[ks] = 0; + if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { break; } + m--; } - if (ks === k) { - kase = 3; - } else if (ks === p - 1) { - kase = 1; - } else { - kase = 2; - k = ks; - } - } - - k++; - switch (kase) { - case 1: { - f = e[p - 2]; - e[p - 2] = 0; - for (j = p - 2; j >= k; j--) { - t = hypotenuse(s[j], f); - cs = s[j] / t; - sn = f / t; - s[j] = t; - if (j !== k) { - f = -sn * e[j - 1]; - e[j - 1] = cs * e[j - 1]; - } - if (wantv) { - for (i = 0; i < n; i++) { - t = cs * V[i][j] + sn * V[i][p - 1]; - V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; - V[i][j] = t; - } - } + for (i = m + 2; i <= n; i++) { + H[i][i - 2] = 0; + if (i > m + 2) { + H[i][i - 3] = 0; } - break; } - case 2 : { - f = e[k - 1]; - e[k - 1] = 0; - for (j = k; j < p; j++) { - t = hypotenuse(s[j], f); - cs = s[j] / t; - sn = f / t; - s[j] = t; - f = -sn * e[j]; - e[j] = cs * e[j]; - if (wantu) { - for (i = 0; i < m; i++) { - t = cs * U[i][j] + sn * U[i][k - 1]; - U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; - U[i][j] = t; - } + + for (k = m; k <= n - 1; k++) { + notlast = (k !== n - 1); + if (k !== m) { + p = H[k][k - 1]; + q = H[k + 1][k - 1]; + r = (notlast ? H[k + 2][k - 1] : 0); + x = Math.abs(p) + Math.abs(q) + Math.abs(r); + if (x !== 0) { + p = p / x; + q = q / x; + r = r / x; } } - break; - } - case 3 : { - scale = Math.max(Math.max(Math.max(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])); - sp = s[p - 1] / scale; - spm1 = s[p - 2] / scale; - epm1 = e[p - 2] / scale; - sk = s[k] / scale; - ek = e[k] / scale; - b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2; - c = (sp * epm1) * (sp * epm1); - shift = 0; - if ((b !== 0) || (c !== 0)) { - shift = Math.sqrt(b * b + c); - if (b < 0) { - shift = -shift; - } - shift = c / (b + shift); + + if (x === 0) { + break; } - f = (sk + sp) * (sk - sp) + shift; - g = sk * ek; - for (j = k; j < p - 1; j++) { - t = hypotenuse(f, g); - cs = f / t; - sn = g / t; - if (j !== k) { - e[j - 1] = t; + + s = Math.sqrt(p * p + q * q + r * r); + if (p < 0) { + s = -s; + } + + if (s !== 0) { + if (k !== m) { + H[k][k - 1] = -s * x; + } else if (l !== m) { + H[k][k - 1] = -H[k][k - 1]; } - 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 (i = 0; i < n; i++) { - t = cs * V[i][j] + sn * V[i][j + 1]; - V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; - V[i][j] = t; + + p = p + s; + x = p / s; + y = q / s; + z = r / s; + q = q / p; + r = r / p; + + for (j = k; j < nn; j++) { + p = H[k][j] + q * H[k + 1][j]; + if (notlast) { + p = p + r * H[k + 2][j]; + H[k + 2][j] = H[k + 2][j] - p * z; } + + H[k][j] = H[k][j] - p * x; + H[k + 1][j] = H[k + 1][j] - p * y; } - t = hypotenuse(f, g); - cs = f / t; - sn = g / t; - s[j] = t; - f = cs * e[j] + sn * s[j + 1]; - s[j + 1] = -sn * e[j] + cs * s[j + 1]; - g = sn * e[j + 1]; - e[j + 1] = cs * e[j + 1]; - if (wantu && (j < m - 1)) { - for (i = 0; i < m; i++) { - t = cs * U[i][j] + sn * U[i][j + 1]; - U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; - U[i][j] = t; + + for (i = 0; i <= Math.min(n, k + 3); i++) { + p = x * H[i][k] + y * H[i][k + 1]; + if (notlast) { + p = p + z * H[i][k + 2]; + H[i][k + 2] = H[i][k + 2] - p * r; + } + + H[i][k] = H[i][k] - p; + H[i][k + 1] = H[i][k + 1] - p * q; + } + + for (i = low; i <= high; i++) { + p = x * V[i][k] + y * V[i][k + 1]; + if (notlast) { + p = p + z * V[i][k + 2]; + V[i][k + 2] = V[i][k + 2] - p * r; } + + V[i][k] = V[i][k] - p; + V[i][k + 1] = V[i][k + 1] - p * q; } } - e[p - 2] = f; - iter = iter + 1; - break; } - case 4: { - if (s[k] <= 0) { - s[k] = (s[k] < 0 ? -s[k] : 0); - if (wantv) { - for (i = 0; i <= pp; i++) { - V[i][k] = -V[i][k]; + } + } + + if (norm === 0) { + return; + } + + for (n = nn - 1; n >= 0; n--) { + p = d[n]; + q = e[n]; + + if (q === 0) { + l = n; + H[n][n] = 1; + for (i = n - 1; i >= 0; i--) { + w = H[i][i] - p; + r = 0; + for (j = l; j <= n; j++) { + r = r + H[i][j] * H[j][n]; + } + + if (e[i] < 0) { + z = w; + s = r; + } else { + l = i; + if (e[i] === 0) { + H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm)); + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; + t = (x * s - z * r) / q; + H[i][n] = t; + H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z); + } + + t = Math.abs(H[i][n]); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n] = H[j][n] / t; } } } - while (k < pp) { - if (s[k] >= s[k + 1]) { - break; - } - t = s[k]; - s[k] = s[k + 1]; - s[k + 1] = t; - if (wantv && (k < n - 1)) { - for (i = 0; i < n; i++) { - t = V[i][k + 1]; - V[i][k + 1] = V[i][k]; - V[i][k] = t; + } + } else if (q < 0) { + l = n - 1; + + if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { + H[n - 1][n - 1] = q / H[n][n - 1]; + H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; + } else { + cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); + H[n - 1][n - 1] = cdivres[0]; + H[n - 1][n] = cdivres[1]; + } + + H[n][n - 1] = 0; + H[n][n] = 1; + for (i = n - 2; i >= 0; i--) { + ra = 0; + sa = 0; + for (j = l; j <= n; j++) { + ra = ra + H[i][j] * H[j][n - 1]; + sa = sa + H[i][j] * H[j][n]; + } + + w = H[i][i] - p; + + if (e[i] < 0) { + z = w; + r = ra; + s = sa; + } else { + l = i; + if (e[i] === 0) { + cdivres = cdiv(-ra, -sa, w, q); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; + vi = (d[i] - p) * 2 * q; + if (vr === 0 && vi === 0) { + vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); + } + cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { + H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; + H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; + } else { + cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); + H[i + 1][n - 1] = cdivres[0]; + H[i + 1][n] = cdivres[1]; } } - if (wantu && (k < m - 1)) { - for (i = 0; i < m; i++) { - t = U[i][k + 1]; - U[i][k + 1] = U[i][k]; - U[i][k] = t; + + t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n - 1] = H[j][n - 1] / t; + H[j][n] = H[j][n] / t; } } - k++; } - iter = 0; - p--; - break; } - // no default } } - if (swapped) { - var tmp = V; - V = U; - U = tmp; + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + for (j = i; j < nn; j++) { + V[i][j] = H[i][j]; + } + } + } + + for (j = nn - 1; j >= low; j--) { + for (i = low; i <= high; i++) { + z = 0; + for (k = low; k <= Math.min(j, high); k++) { + z = z + V[i][k] * H[k][j]; + } + V[i][j] = z; + } + } +} + +function cdiv(xr, xi, yr, yi) { + var r, d; + if (Math.abs(yr) > Math.abs(yi)) { + r = yi / yr; + d = yr + r * yi; + return [(xr + r * xi) / d, (xi - r * xr) / d]; + } else { + r = yr / yi; + d = yi + r * yr; + return [(r * xr + xi) / d, (r * xi - xr) / d]; + } +} + +/* unused harmony default export */ var _unused_webpack_default_export = (EigenvalueDecomposition); + + +/***/ }), +/* 218 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* unused harmony export inverse */ +/* harmony export (immutable) */ __webpack_exports__["a"] = solve; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__dc_lu__ = __webpack_require__(32); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__dc_qr__ = __webpack_require__(69); + + + + + +function inverse(matrix) { + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + return solve(matrix, __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].eye(matrix.rows)); +} + +function solve(leftHandSide, rightHandSide) { + leftHandSide = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(leftHandSide); + rightHandSide = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(rightHandSide); + return leftHandSide.isSquare() ? new __WEBPACK_IMPORTED_MODULE_1__dc_lu__["a" /* default */](leftHandSide).solve(rightHandSide) : new __WEBPACK_IMPORTED_MODULE_2__dc_qr__["a" /* default */](leftHandSide).solve(rightHandSide); +} + + +/***/ }), +/* 219 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(6); +/* unused harmony reexport default */ +/* unused harmony reexport Matrix */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__abstractMatrix__ = __webpack_require__(31); +/* unused harmony reexport abstractMatrix */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__decompositions__ = __webpack_require__(218); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_2__decompositions__["a"]; }); +/* unused harmony reexport inverse */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__dc_svd_js__ = __webpack_require__(70); +/* unused harmony reexport SingularValueDecomposition */ +/* unused harmony reexport SVD */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__dc_evd_js__ = __webpack_require__(217); +/* unused harmony reexport EigenvalueDecomposition */ +/* unused harmony reexport EVD */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__dc_cholesky_js__ = __webpack_require__(216); +/* unused harmony reexport CholeskyDecomposition */ +/* unused harmony reexport CHO */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__dc_lu_js__ = __webpack_require__(32); +/* unused harmony reexport LuDecomposition */ +/* unused harmony reexport LU */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__dc_qr_js__ = __webpack_require__(69); +/* unused harmony reexport QrDecomposition */ +/* unused harmony reexport QR */ + + + + + + + + + + + +/***/ }), +/* 220 */ +/***/ (function(module, exports) { + +if (!Symbol.species) { + Symbol.species = Symbol.for('@@species'); +} + + +/***/ }), +/* 221 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(11); + + +class MatrixColumnView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, column) { + super(matrix, matrix.rows, 1); + this.column = column; + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.column, value); + return this; + } + + get(rowIndex) { + return this.matrix.get(rowIndex, this.column); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixColumnView; + + + +/***/ }), +/* 222 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(11); + + +class MatrixFlipColumnView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(rowIndex, this.columns - columnIndex - 1); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixFlipColumnView; + + + +/***/ }), +/* 223 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(11); + + +class MatrixFlipRowView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); + return this; } - this.m = m; - this.n = n; - this.s = s; - this.U = U; - this.V = V; + get(rowIndex, columnIndex) { + return this.matrix.get(this.rows - rowIndex - 1, columnIndex); + } } +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixFlipRowView; -SingularValueDecomposition.prototype = { - get condition() { - return this.s[0] / this.s[Math.min(this.m, this.n) - 1]; - }, - get norm2() { - return this.s[0]; - }, - get rank() { - var eps = Math.pow(2, -52), - tol = Math.max(this.m, this.n) * this.s[0] * eps, - r = 0, - s = this.s; - for (var i = 0, ii = s.length; i < ii; i++) { - if (s[i] > tol) { - r++; - } - } - return r; - }, - get diagonal() { - return this.s; - }, - // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs - get threshold() { - return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0]; - }, - get leftSingularVectors() { - if (!Matrix.isMatrix(this.U)) { - this.U = new Matrix(this.U); - } - return this.U; - }, - get rightSingularVectors() { - if (!Matrix.isMatrix(this.V)) { - this.V = new Matrix(this.V); - } - return this.V; - }, - get diagonalMatrix() { - return Matrix.diag(this.s); - }, - solve: function (value) { - var Y = value, - e = this.threshold, - scols = this.s.length, - Ls = Matrix.zeros(scols, scols), - i; - for (i = 0; i < scols; i++) { - if (Math.abs(this.s[i]) <= e) { - Ls[i][i] = 0; - } else { - Ls[i][i] = 1 / this.s[i]; - } - } +/***/ }), +/* 224 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var U = this.U; - var V = this.rightSingularVectors; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(11); - var VL = V.mmul(Ls), - vrows = V.rows, - urows = U.length, - VLU = Matrix.zeros(vrows, urows), - j, k, sum; - for (i = 0; i < vrows; i++) { - for (j = 0; j < urows; j++) { - sum = 0; - for (k = 0; k < scols; k++) { - sum += VL[i][k] * U[j][k]; - } - VLU[i][j] = sum; - } - } +class MatrixRowView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, row) { + super(matrix, 1, matrix.columns); + this.row = row; + } - return VLU.mmul(Y); - }, - solveForDiagonal: function (value) { - return this.solve(Matrix.diag(value)); - }, - inverse: function () { - var V = this.V; - var e = this.threshold, - vrows = V.length, - vcols = V[0].length, - X = new Matrix(vrows, this.s.length), - i, j; + set(rowIndex, columnIndex, value) { + this.matrix.set(this.row, columnIndex, value); + return this; + } - for (i = 0; i < vrows; i++) { - for (j = 0; j < vcols; j++) { - if (Math.abs(this.s[j]) > e) { - X[i][j] = V[i][j] / this.s[j]; - } else { - X[i][j] = 0; - } - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.row, columnIndex); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixRowView; + + + +/***/ }), +/* 225 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(18); + + + +class MatrixSelectionView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, rowIndices, columnIndices) { + var indices = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["i" /* checkIndices */])(matrix, rowIndices, columnIndices); + super(matrix, indices.row.length, indices.column.length); + this.rowIndices = indices.row; + this.columnIndices = indices.column; + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixSelectionView; + + + +/***/ }), +/* 226 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(18); + + + +class MatrixSubView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, startRow, endRow, startColumn, endColumn) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["h" /* checkRange */])(matrix, startRow, endRow, startColumn, endColumn); + super(matrix, endRow - startRow + 1, endColumn - startColumn + 1); + this.startRow = startRow; + this.startColumn = startColumn; + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixSubView; + + + +/***/ }), +/* 227 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(11); + + +class MatrixTransposeView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.columns, matrix.rows); + } + + set(rowIndex, columnIndex, value) { + this.matrix.set(columnIndex, rowIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(columnIndex, rowIndex); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixTransposeView; + + + +/***/ }), +/* 228 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ml_matrix__ = __webpack_require__(219); + + + +class RobustPolynomialRegression extends __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["a" /* default */] { + constructor(x, y, degree) { + super(); + if (x === true) { + this.degree = y.degree; + this.powers = y.powers; + this.coefficients = y.coefficients; + } else { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["b" /* checkArrayLength */])(x, y); + robustPolynomial(this, x, y, degree); } + } - var U = this.U; + toJSON() { + return { + name: 'robustPolynomialRegression', + degree: this.degree, + powers: this.powers, + coefficients: this.coefficients + }; + } - var urows = U.length, - ucols = U[0].length, - Y = new Matrix(vrows, urows), - k, sum; + _predict(x) { + return predict(x, this.powers, this.coefficients); + } - for (i = 0; i < vrows; i++) { - for (j = 0; j < urows; j++) { - sum = 0; - for (k = 0; k < ucols; k++) { - sum += X[i][k] * U[j][k]; + toString(precision) { + return this._toFormula(precision, false); + } + + toLaTeX(precision) { + return this._toFormula(precision, true); + } + + _toFormula(precision, isLaTeX) { + let sup = '^'; + let closeSup = ''; + let times = ' * '; + if (isLaTeX) { + sup = '^{'; + closeSup = '}'; + times = ''; + } + + 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 = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.coefficients[k], precision); + } else { + if (this.powers[k] === 1) { + str = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.coefficients[k], precision) + times + 'x'; + } else { + str = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* 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; } - Y[i][j] = sum; } + fn = str + fn; + } + if (fn.charAt(0) === '+') { + fn = fn.slice(1); } - return Y; + return 'f(x) = ' + fn; } -}; -module.exports = SingularValueDecomposition; + static load(json) { + if (json.name !== 'robustPolynomialRegression') { + throw new TypeError('not a RobustPolynomialRegression model'); + } + return new RobustPolynomialRegression(true, json); + } +} +/* harmony export (immutable) */ __webpack_exports__["default"] = RobustPolynomialRegression; -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { +function robustPolynomial(regression, x, y, degree) { + let powers = new Array(degree); + for (let k = 0; k < degree; k++) { + powers[k] = k; + } -"use strict"; + const tuples = getRandomTuples(x, y, degree); + var min; + for (var i = 0; i < tuples.length; i++) { + var tuple = tuples[i]; + var coefficients = calcCoefficients(tuple, powers); -var Matrix = __webpack_require__(3).Matrix; + var residuals = x.slice(); + for (var j = 0; j < x.length; j++) { + residuals[j] = y[j] - predict(x[j], powers, coefficients); + residuals[j] = { + residual: residuals[j] * residuals[j], + coefficients + }; + } -var SingularValueDecomposition = __webpack_require__(137); -var EigenvalueDecomposition = __webpack_require__(135); -var LuDecomposition = __webpack_require__(38); -var QrDecomposition = __webpack_require__(136); -var CholeskyDecomposition = __webpack_require__(134); + var median = residualsMedian(residuals); + if (!min || median.residual < min.residual) { + min = median; + } + } -function inverse(matrix) { - matrix = Matrix.checkMatrix(matrix); - return solve(matrix, Matrix.eye(matrix.rows)); + regression.degree = degree; + regression.powers = powers; + regression.coefficients = min.coefficients; } /** - * Returns the inverse - * @memberOf Matrix - * @static - * @param {Matrix} matrix - * @return {Matrix} matrix - * @alias inv + * @ignore + * @param {Array} x + * @param {Array} y + * @param {number} degree + * @return {Array<{x:number,y:number}>} */ -Matrix.inverse = Matrix.inv = inverse; +function getRandomTuples(x, y, degree) { + var len = Math.floor(x.length / degree); + var tuples = new Array(len); + + for (var i = 0; i < x.length; i++) { + var pos = Math.floor(Math.random() * len); + + var counter = 0; + while (counter < x.length) { + if (!tuples[pos]) { + tuples[pos] = [{ + x: x[i], + y: y[i] + }]; + break; + } else if (tuples[pos].length < degree) { + tuples[pos].push({ + x: x[i], + y: y[i] + }); + break; + } else { + counter++; + pos = (pos + 1) % len; + } + } + + if (counter === x.length) { + return tuples; + } + } + return tuples; +} /** - * Returns the inverse - * @memberOf Matrix - * @static - * @param {Matrix} matrix - * @return {Matrix} matrix - * @alias inv + * @ignore + * @param {{x:number,y:number}} tuple + * @param {Array} powers + * @return {Array} */ -Matrix.prototype.inverse = Matrix.prototype.inv = function () { - return inverse(this); -}; +function calcCoefficients(tuple, powers) { + var X = tuple.slice(); + var Y = tuple.slice(); + for (var i = 0; i < X.length; i++) { + Y[i] = [tuple[i].y]; + X[i] = new Array(powers.length); + for (var j = 0; j < powers.length; j++) { + X[i][j] = Math.pow(tuple[i].x, powers[j]); + } + } -function solve(leftHandSide, rightHandSide) { - leftHandSide = Matrix.checkMatrix(leftHandSide); - rightHandSide = Matrix.checkMatrix(rightHandSide); - return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide); + return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_ml_matrix__["a" /* solve */])(X, Y).to1DArray(); } -Matrix.solve = solve; -Matrix.prototype.solve = function (other) { - return solve(this, other); -}; +function predict(x, powers, coefficients) { + let y = 0; + for (let k = 0; k < powers.length; k++) { + y += coefficients[k] * Math.pow(x, powers[k]); + } + return y; +} -module.exports = { - SingularValueDecomposition: SingularValueDecomposition, - SVD: SingularValueDecomposition, - EigenvalueDecomposition: EigenvalueDecomposition, - EVD: EigenvalueDecomposition, - LuDecomposition: LuDecomposition, - LU: LuDecomposition, - QrDecomposition: QrDecomposition, - QR: QrDecomposition, - CholeskyDecomposition: CholeskyDecomposition, - CHO: CholeskyDecomposition, - inverse: inverse, - solve: solve -}; +function residualsMedian(residuals) { + residuals.sort((a, b) => a.residual - b.residual); + + var l = residuals.length; + var half = Math.floor(l / 2); + if (l % 2 === 0) { + return residuals[half - 1]; + } else { + return residuals[half]; + } +} /***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { +/* 229 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ml_stat__ = __webpack_require__(2); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ml_stat___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_ml_stat__); -if (!Symbol.species) { - Symbol.species = Symbol.for('@@species'); -} +const median = __WEBPACK_IMPORTED_MODULE_1_ml_stat__["array"].median; +class TheilSenRegression extends __WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["a" /* default */] { -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Theil–Sen estimator + * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator + * @param {Array|boolean} x + * @param {Array|object} y + * @constructor + */ + constructor(x, y) { + super(); + if (x === true) { + // loads the model + this.slope = y.slope; + this.intercept = y.intercept; + this.coefficients = y.coefficients; + } else { + // creates the model + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["b" /* checkArrayLength */])(x, y); + theilSen(this, x, y); + } -"use strict"; + } + toJSON() { + return { + name: 'TheilSenRegression', + slope: this.slope, + intercept: this.intercept + }; + } -var BaseView = __webpack_require__(5); + _predict(input) { + return this.slope * input + this.intercept; + } -class MatrixColumnView extends BaseView { - constructor(matrix, column) { - super(matrix, matrix.rows, 1); - this.column = column; + computeX(input) { + return (input - this.intercept) / this.slope; } - set(rowIndex, columnIndex, value) { - this.matrix.set(rowIndex, this.column, value); - return this; + toString(precision) { + var result = 'f(x) = '; + if (this.slope) { + var xFactor = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.slope, precision); + result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x'; + if (this.intercept) { + var absIntercept = Math.abs(this.intercept); + var operator = absIntercept === this.intercept ? '+' : '-'; + result += ' ' + operator + ' ' + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(absIntercept, precision); + } + } else { + result += __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_ml_regression_base__["c" /* maybeToPrecision */])(this.intercept, precision); + } + return result; } - get(rowIndex) { - return this.matrix.get(rowIndex, this.column); + toLaTeX(precision) { + return this.toString(precision); + } + + static load(json) { + if (json.name !== 'TheilSenRegression') { + throw new TypeError('not a Theil-Sen model'); + } + return new TheilSenRegression(true, json); } } +/* harmony export (immutable) */ __webpack_exports__["default"] = TheilSenRegression; -module.exports = MatrixColumnView; + +function theilSen(regression, x, y) { + let len = x.length; + let slopes = new Array(len * len); + let count = 0; + for (let i = 0; i < len; ++i) { + for (let j = i + 1; j < len; ++j) { + if (x[i] !== x[j]) { + slopes[count++] = (y[j] - y[i]) / (x[j] - x[i]); + } + } + } + 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]; + } + + regression.slope = medianSlope; + regression.intercept = median(cuts); + regression.coefficients = [regression.intercept, regression.slope]; +} /***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { +/* 230 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(7); -var BaseView = __webpack_require__(5); - -class MatrixFlipColumnView extends BaseView { - constructor(matrix) { - super(matrix, matrix.rows, matrix.columns); +// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs +function CholeskyDecomposition(value) { + if (!(this instanceof CholeskyDecomposition)) { + return new CholeskyDecomposition(value); + } + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + if (!value.isSymmetric()) { + throw new Error('Matrix is not symmetric'); } - set(rowIndex, columnIndex, value) { - this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); - return this; + var a = value, + dimension = a.rows, + l = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](dimension, dimension), + positiveDefinite = true, + i, j, k; + + for (j = 0; j < dimension; j++) { + var Lrowj = l[j]; + var d = 0; + for (k = 0; k < j; k++) { + var Lrowk = l[k]; + var s = 0; + for (i = 0; i < k; i++) { + s += Lrowk[i] * Lrowj[i]; + } + Lrowj[k] = s = (a[j][k] - s) / l[k][k]; + d = d + s * s; + } + + d = a[j][j] - d; + + positiveDefinite &= (d > 0); + l[j][j] = Math.sqrt(Math.max(d, 0)); + for (k = j + 1; k < dimension; k++) { + l[j][k] = 0; + } } - get(rowIndex, columnIndex) { - return this.matrix.get(rowIndex, this.columns - columnIndex - 1); + if (!positiveDefinite) { + throw new Error('Matrix is not positive definite'); } + + this.L = l; } -module.exports = MatrixFlipColumnView; +CholeskyDecomposition.prototype = { + get lowerTriangularMatrix() { + return this.L; + }, + solve: function (value) { + value = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(value); + + var l = this.L, + dimension = l.rows; + + if (value.rows !== dimension) { + throw new Error('Matrix dimensions do not match'); + } + + var count = value.columns, + B = value.clone(), + i, j, k; + + for (k = 0; k < dimension; k++) { + for (j = 0; j < count; j++) { + for (i = 0; i < k; i++) { + B[k][j] -= B[i][j] * l[k][i]; + } + B[k][j] /= l[k][k]; + } + } + + for (k = dimension - 1; k >= 0; k--) { + for (j = 0; j < count; j++) { + for (i = k + 1; i < dimension; i++) { + B[k][j] -= B[i][j] * l[i][k]; + } + B[k][j] /= l[k][k]; + } + } + + return B; + } +}; + +/* harmony default export */ __webpack_exports__["a"] = (CholeskyDecomposition); /***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { +/* 231 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(37); + + + +const defaultOptions = { + assumeSymmetric: false +}; +// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs +function EigenvalueDecomposition(matrix, options) { + options = Object.assign({}, defaultOptions, options); + if (!(this instanceof EigenvalueDecomposition)) { + return new EigenvalueDecomposition(matrix, options); + } + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + if (!matrix.isSquare()) { + throw new Error('Matrix is not a square matrix'); + } -var BaseView = __webpack_require__(5); + var n = matrix.columns, + V = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + d = new Array(n), + e = new Array(n), + value = matrix, + i, j; -class MatrixFlipRowView extends BaseView { - constructor(matrix) { - super(matrix, matrix.rows, matrix.columns); + var isSymmetric = false; + if (options.assumeSymmetric) { + isSymmetric = true; + } else { + isSymmetric = matrix.isSymmetric(); } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); - return this; + if (isSymmetric) { + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = value.get(i, j); + } + } + tred2(n, e, d, V); + tql2(n, e, d, V); + } else { + var H = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["b" /* getFilled2DArray */])(n, n, 0), + ort = new Array(n); + for (j = 0; j < n; j++) { + for (i = 0; i < n; i++) { + H[i][j] = value.get(i, j); + } + } + orthes(n, H, ort, V); + hqr2(n, e, d, V, H); } - get(rowIndex, columnIndex) { - return this.matrix.get(this.rows - rowIndex - 1, columnIndex); - } + this.n = n; + this.e = e; + this.d = d; + this.V = V; } -module.exports = MatrixFlipRowView; - +EigenvalueDecomposition.prototype = { + get realEigenvalues() { + return this.d; + }, + get imaginaryEigenvalues() { + return this.e; + }, + get eigenvectorMatrix() { + if (!__WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].isMatrix(this.V)) { + this.V = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](this.V); + } + return this.V; + }, + get diagonalMatrix() { + var n = this.n, + e = this.e, + d = this.d, + X = new __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */](n, n), + i, j; + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + X[i][j] = 0; + } + X[i][i] = d[i]; + if (e[i] > 0) { + X[i][i + 1] = e[i]; + } else if (e[i] < 0) { + X[i][i - 1] = e[i]; + } + } + return X; + } +}; -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { +function tred2(n, e, d, V) { -"use strict"; + var f, g, h, i, j, k, + hh, scale; + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + } -var BaseView = __webpack_require__(5); + for (i = n - 1; i > 0; i--) { + scale = 0; + h = 0; + for (k = 0; k < i; k++) { + scale = scale + Math.abs(d[k]); + } -class MatrixRowView extends BaseView { - constructor(matrix, row) { - super(matrix, 1, matrix.columns); - this.row = row; - } + if (scale === 0) { + e[i] = d[i - 1]; + for (j = 0; j < i; j++) { + d[j] = V[i - 1][j]; + V[i][j] = 0; + V[j][i] = 0; + } + } else { + for (k = 0; k < i; k++) { + d[k] /= scale; + h += d[k] * d[k]; + } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.row, columnIndex, value); - return this; - } + f = d[i - 1]; + g = Math.sqrt(h); + if (f > 0) { + g = -g; + } - get(rowIndex, columnIndex) { - return this.matrix.get(this.row, columnIndex); - } -} + e[i] = scale * g; + h = h - f * g; + d[i - 1] = f - g; + for (j = 0; j < i; j++) { + e[j] = 0; + } -module.exports = MatrixRowView; + for (j = 0; j < i; j++) { + f = d[j]; + V[j][i] = f; + g = e[j] + V[j][j] * f; + for (k = j + 1; k <= i - 1; k++) { + g += V[k][j] * d[k]; + e[k] += V[k][j] * f; + } + e[j] = g; + } + f = 0; + for (j = 0; j < i; j++) { + e[j] /= h; + f += e[j] * d[j]; + } -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { + hh = f / (h + h); + for (j = 0; j < i; j++) { + e[j] -= hh * d[j]; + } -"use strict"; + for (j = 0; j < i; j++) { + f = d[j]; + g = e[j]; + for (k = j; k <= i - 1; k++) { + V[k][j] -= (f * e[k] + g * d[k]); + } + d[j] = V[i - 1][j]; + V[i][j] = 0; + } + } + d[i] = h; + } + for (i = 0; i < n - 1; i++) { + V[n - 1][i] = V[i][i]; + V[i][i] = 1; + h = d[i + 1]; + if (h !== 0) { + for (k = 0; k <= i; k++) { + d[k] = V[k][i + 1] / h; + } -var BaseView = __webpack_require__(5); -var util = __webpack_require__(7); + for (j = 0; j <= i; j++) { + g = 0; + for (k = 0; k <= i; k++) { + g += V[k][i + 1] * V[k][j]; + } + for (k = 0; k <= i; k++) { + V[k][j] -= g * d[k]; + } + } + } -class MatrixSelectionView extends BaseView { - constructor(matrix, rowIndices, columnIndices) { - var indices = util.checkIndices(matrix, rowIndices, columnIndices); - super(matrix, indices.row.length, indices.column.length); - this.rowIndices = indices.row; - this.columnIndices = indices.column; + for (k = 0; k <= i; k++) { + V[k][i + 1] = 0; + } } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); - return this; + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + V[n - 1][j] = 0; } - get(rowIndex, columnIndex) { - return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); - } + V[n - 1][n - 1] = 1; + e[0] = 0; } -module.exports = MatrixSelectionView; - - -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { +function tql2(n, e, d, V) { -"use strict"; + var g, h, i, j, k, l, m, p, r, + dl1, c, c2, c3, el1, s, s2, + iter; + for (i = 1; i < n; i++) { + e[i - 1] = e[i]; + } -var BaseView = __webpack_require__(5); -var util = __webpack_require__(7); + e[n - 1] = 0; -class MatrixSubView extends BaseView { - constructor(matrix, startRow, endRow, startColumn, endColumn) { - util.checkRange(matrix, startRow, endRow, startColumn, endColumn); - super(matrix, endRow - startRow + 1, endColumn - startColumn + 1); - this.startRow = startRow; - this.startColumn = startColumn; - } + var f = 0, + tst1 = 0, + eps = Math.pow(2, -52); - set(rowIndex, columnIndex, value) { - this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); - return this; - } + for (l = 0; l < n; l++) { + tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); + m = l; + while (m < n) { + if (Math.abs(e[m]) <= eps * tst1) { + break; + } + m++; + } - get(rowIndex, columnIndex) { - return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); - } -} + if (m > l) { + iter = 0; + do { + iter = iter + 1; -module.exports = MatrixSubView; + g = d[l]; + p = (d[l + 1] - g) / (2 * e[l]); + r = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(p, 1); + if (p < 0) { + r = -r; + } + d[l] = e[l] / (p + r); + d[l + 1] = e[l] * (p + r); + dl1 = d[l + 1]; + h = g - d[l]; + for (i = l + 2; i < n; i++) { + d[i] -= h; + } -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { + f = f + h; -"use strict"; + p = d[m]; + c = 1; + c2 = c; + c3 = c; + el1 = e[l + 1]; + s = 0; + s2 = 0; + for (i = m - 1; i >= l; i--) { + c3 = c2; + c2 = c; + s2 = s; + g = c * e[i]; + h = c * p; + r = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["a" /* hypotenuse */])(p, e[i]); + e[i + 1] = s * r; + s = e[i] / r; + c = p / r; + p = c * d[i] - s * g; + d[i + 1] = h + s * (c * g + s * d[i]); + for (k = 0; k < n; k++) { + h = V[k][i + 1]; + V[k][i + 1] = s * V[k][i] + c * h; + V[k][i] = c * V[k][i] - s * h; + } + } -var BaseView = __webpack_require__(5); + p = -s * s2 * c3 * el1 * e[l] / dl1; + e[l] = s * p; + d[l] = c * p; -class MatrixTransposeView extends BaseView { - constructor(matrix) { - super(matrix, matrix.columns, matrix.rows); + } + while (Math.abs(e[l]) > eps * tst1); + } + d[l] = d[l] + f; + e[l] = 0; } - set(rowIndex, columnIndex, value) { - this.matrix.set(columnIndex, rowIndex, value); - return this; - } + 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]; + } + } - get(rowIndex, columnIndex) { - return this.matrix.get(columnIndex, rowIndex); + if (k !== i) { + d[k] = d[i]; + d[i] = p; + for (j = 0; j < n; j++) { + p = V[j][i]; + V[j][i] = V[j][k]; + V[j][k] = p; + } + } } } -module.exports = MatrixTransposeView; +function orthes(n, H, ort, V) { + var low = 0, + high = n - 1, + f, g, h, i, j, m, + scale; -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { + for (m = low + 1; m <= high - 1; m++) { + scale = 0; + for (i = m; i <= high; i++) { + scale = scale + Math.abs(H[i][m - 1]); + } -"use strict"; + if (scale !== 0) { + h = 0; + for (i = high; i >= m; i--) { + ort[i] = H[i][m - 1] / scale; + h += ort[i] * ort[i]; + } + g = Math.sqrt(h); + if (ort[m] > 0) { + g = -g; + } -const squaredDistance = __webpack_require__(1).squared; + h = h - ort[m] * g; + ort[m] = ort[m] - g; -const defaultOptions = { - distanceFunction: squaredDistance, - similarityFunction: false, - returnVector: false -}; + for (j = m; j < n; j++) { + f = 0; + for (i = high; i >= m; i--) { + f += ort[i] * H[i][j]; + } -/** - * Find the nearest vector in a list to a sample vector - * @param {Array>} listVectors - List of vectors with same dimensions - * @param {Array} vector - Reference vector to "classify" - * @param {object} [options] - Options object - * @param {function} [options.distanceFunction = squaredDistance] - Function that receives two vectors and return their distance value as number - * @param {function} [options.similarityFunction = undefined] - Function that receives two vectors and return their similarity value as number - * @param {boolean} [options.returnVector = false] - Return the nearest vector instead of its index - * @return {number|Array} - The index or the content of the nearest vector - */ -function nearestVector(listVectors, vector, options) { - options = options || defaultOptions; - const distanceFunction = options.distanceFunction || defaultOptions.distanceFunction; - const similarityFunction = options.similarityFunction || defaultOptions.similarityFunction; - const returnVector = options.returnVector || defaultOptions.returnVector; + f = f / h; + for (i = m; i <= high; i++) { + H[i][j] -= f * ort[i]; + } + } - var vectorIndex = -1; - if (typeof similarityFunction === 'function') { + for (i = 0; i <= high; i++) { + f = 0; + for (j = high; j >= m; j--) { + f += ort[j] * H[i][j]; + } - // maximum similarity - var maxSim = Number.MIN_VALUE; - for (var j = 0; j < listVectors.length; j++) { - var sim = similarityFunction(vector, listVectors[j]); - if (sim > maxSim) { - maxSim = sim; - vectorIndex = j; + f = f / h; + for (j = m; j <= high; j++) { + H[i][j] -= f * ort[j]; + } } + + ort[m] = scale * ort[m]; + H[m][m - 1] = scale * g; } - } else if (typeof distanceFunction === 'function') { + } - // minimum distance - var minDist = Number.MAX_VALUE; - for (var i = 0; i < listVectors.length; i++) { - var dist = distanceFunction(vector, listVectors[i]); - if (dist < minDist) { - minDist = dist; - vectorIndex = i; - } + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = (i === j ? 1 : 0); } - } else { - throw new Error('A similarity or distance function it\'s required'); } - if (returnVector) { - return listVectors[vectorIndex]; - } else { - return vectorIndex; + for (m = high - 1; m >= low + 1; m--) { + if (H[m][m - 1] !== 0) { + for (i = m + 1; i <= high; i++) { + ort[i] = H[i][m - 1]; + } + + for (j = m; j <= high; j++) { + g = 0; + for (i = m; i <= high; i++) { + g += ort[i] * V[i][j]; + } + + g = (g / ort[m]) / H[m][m - 1]; + for (i = m; i <= high; i++) { + V[i][j] += g * ort[i]; + } + } + } } } -module.exports = nearestVector; +function hqr2(nn, e, d, V, H) { + var n = nn - 1, + low = 0, + high = nn - 1, + eps = Math.pow(2, -52), + exshift = 0, + norm = 0, + p = 0, + q = 0, + r = 0, + s = 0, + z = 0, + iter = 0, + i, j, k, l, m, t, w, x, y, + ra, sa, vr, vi, + notlast, cdivres; + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + d[i] = H[i][i]; + e[i] = 0; + } -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { + for (j = Math.max(i - 1, 0); j < nn; j++) { + norm = norm + Math.abs(H[i][j]); + } + } -"use strict"; + while (n >= low) { + l = n; + while (l > low) { + s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); + if (s === 0) { + s = norm; + } + if (Math.abs(H[l][l - 1]) < eps * s) { + break; + } + l--; + } + + if (l === n) { + H[n][n] = H[n][n] + exshift; + d[n] = H[n][n]; + e[n] = 0; + n--; + iter = 0; + } else if (l === n - 1) { + w = H[n][n - 1] * H[n - 1][n]; + p = (H[n - 1][n - 1] - H[n][n]) / 2; + q = p * p + w; + z = Math.sqrt(Math.abs(q)); + H[n][n] = H[n][n] + exshift; + H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; + x = H[n][n]; + if (q >= 0) { + z = (p >= 0) ? (p + z) : (p - z); + d[n - 1] = x + z; + d[n] = d[n - 1]; + if (z !== 0) { + d[n] = x - w / z; + } + e[n - 1] = 0; + e[n] = 0; + x = H[n][n - 1]; + s = Math.abs(x) + Math.abs(z); + p = x / s; + q = z / s; + r = Math.sqrt(p * p + q * q); + p = p / r; + q = q / r; -// Accuracy -exports.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 result; -}; + for (j = n - 1; j < nn; j++) { + z = H[n - 1][j]; + H[n - 1][j] = q * z + p * H[n][j]; + H[n][j] = q * H[n][j] - p * z; + } -// Error rate -exports.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 result; -}; + for (i = 0; i <= n; i++) { + z = H[i][n - 1]; + H[i][n - 1] = q * z + p * H[i][n]; + H[i][n] = q * H[i][n] - p * z; + } -// False positive rate -exports.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 result; -}; + for (i = low; i <= high; i++) { + z = V[i][n - 1]; + V[i][n - 1] = q * z + p * V[i][n]; + V[i][n] = q * V[i][n] - p * z; + } + } else { + d[n - 1] = x + p; + d[n] = x + p; + e[n - 1] = z; + e[n] = -z; + } -// True positive rate -exports.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 result; -}; + n = n - 2; + iter = 0; + } else { + x = H[n][n]; + y = 0; + w = 0; + if (l < n) { + y = H[n - 1][n - 1]; + w = H[n][n - 1] * H[n - 1][n]; + } -// False negative rate -exports.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 result; -}; + if (iter === 10) { + exshift += x; + for (i = low; i <= n; i++) { + H[i][i] -= x; + } + s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); + x = y = 0.75 * s; + w = -0.4375 * s * s; + } -// True negative rate -exports.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 result; -}; + if (iter === 30) { + s = (y - x) / 2; + s = s * s + w; + if (s > 0) { + s = Math.sqrt(s); + if (y < x) { + s = -s; + } + s = x - w / ((y - x) / 2 + s); + for (i = low; i <= n; i++) { + H[i][i] -= s; + } + exshift += s; + x = y = w = 0.964; + } + } -// Positive predictive value -exports.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 result; -}; + iter = iter + 1; -// Negative predictive value -exports.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 result; -}; + m = n - 2; + while (m >= l) { + z = H[m][m]; + r = x - z; + s = y - z; + p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; + q = H[m + 1][m + 1] - z - r - s; + r = H[m + 2][m + 1]; + s = Math.abs(p) + Math.abs(q) + Math.abs(r); + p = p / s; + q = q / s; + r = r / s; + if (m === l) { + break; + } + if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { + break; + } + m--; + } -// Prediction conditioned fallout -exports.pcfall = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1; - } - return result; -}; + for (i = m + 2; i <= n; i++) { + H[i][i - 2] = 0; + if (i > m + 2) { + H[i][i - 3] = 0; + } + } -// Prediction conditioned miss -exports.pcmiss = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1; - } - return result; -}; + for (k = m; k <= n - 1; k++) { + notlast = (k !== n - 1); + if (k !== m) { + p = H[k][k - 1]; + q = H[k + 1][k - 1]; + r = (notlast ? H[k + 2][k - 1] : 0); + x = Math.abs(p) + Math.abs(q) + Math.abs(r); + if (x !== 0) { + p = p / x; + q = q / x; + r = r / x; + } + } -// Lift value -exports.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 result; -}; + if (x === 0) { + break; + } -// Rate of positive predictions -exports.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 result; -}; + s = Math.sqrt(p * p + q * q + r * r); + if (p < 0) { + s = -s; + } -// Rate of negative predictions -exports.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 result; -}; + if (s !== 0) { + if (k !== m) { + H[k][k - 1] = -s * x; + } else if (l !== m) { + H[k][k - 1] = -H[k][k - 1]; + } -// Threshold -exports.threshold = pred => { - const clone = pred.cutoffs.slice(); - clone[0] = clone[1]; // Remove the infinite value - return clone; -}; + p = p + s; + x = p / s; + y = q / s; + z = r / s; + q = q / p; + r = r / p; + for (j = k; j < nn; j++) { + p = H[k][j] + q * H[k + 1][j]; + if (notlast) { + p = p + r * H[k + 2][j]; + H[k + 2][j] = H[k + 2][j] - p * z; + } -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { + H[k][j] = H[k][j] - p * x; + H[k + 1][j] = H[k + 1][j] - p * y; + } -"use strict"; + for (i = 0; i <= Math.min(n, k + 3); i++) { + p = x * H[i][k] + y * H[i][k + 1]; + if (notlast) { + p = p + z * H[i][k + 2]; + H[i][k + 2] = H[i][k + 2] - p * r; + } + H[i][k] = H[i][k] - p; + H[i][k + 1] = H[i][k + 1] - p * q; + } -var Matrix = __webpack_require__(0); -var Utils = __webpack_require__(12); + for (i = low; i <= high; i++) { + p = x * V[i][k] + y * V[i][k + 1]; + if (notlast) { + p = p + z * V[i][k + 2]; + V[i][k + 2] = V[i][k + 2] - p * r; + } -module.exports = OPLS; + V[i][k] = V[i][k] - p; + V[i][k + 1] = V[i][k + 1] - p * q; + } + } + } + } + } -function OPLS(dataset, predictions, numberOSC) { - var X = new Matrix(dataset); - var y = new Matrix(predictions); + if (norm === 0) { + return; + } - X = Utils.featureNormalize(X).result; - y = Utils.featureNormalize(y).result; + for (n = nn - 1; n >= 0; n--) { + p = d[n]; + q = e[n]; - var rows = X.rows; - var columns = X.columns; + if (q === 0) { + l = n; + H[n][n] = 1; + for (i = n - 1; i >= 0; i--) { + w = H[i][i] - p; + r = 0; + for (j = l; j <= n; j++) { + r = r + H[i][j] * H[j][n]; + } - var sumOfSquaresX = X.clone().mul(X).sum(); - var w = X.transpose().mmul(y); - w.div(Utils.norm(w)); + if (e[i] < 0) { + z = w; + s = r; + } else { + l = i; + if (e[i] === 0) { + H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm)); + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; + t = (x * s - z * r) / q; + H[i][n] = t; + H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z); + } - var orthoW = new Array(numberOSC); - var orthoT = new Array(numberOSC); - var orthoP = new Array(numberOSC); - for (var i = 0; i < numberOSC; i++) { - var t = X.mmul(w); + t = Math.abs(H[i][n]); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n] = H[j][n] / t; + } + } + } + } + } else if (q < 0) { + l = n - 1; - var numerator = X.transpose().mmul(t); - var denominator = t.transpose().mmul(t)[0][0]; - var p = numerator.div(denominator); + if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { + H[n - 1][n - 1] = q / H[n][n - 1]; + H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; + } else { + cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); + H[n - 1][n - 1] = cdivres[0]; + H[n - 1][n] = cdivres[1]; + } - numerator = w.transpose().mmul(p)[0][0]; - denominator = w.transpose().mmul(w)[0][0]; - var wOsc = p.sub(w.clone().mul(numerator / denominator)); - wOsc.div(Utils.norm(wOsc)); + H[n][n - 1] = 0; + H[n][n] = 1; + for (i = n - 2; i >= 0; i--) { + ra = 0; + sa = 0; + for (j = l; j <= n; j++) { + ra = ra + H[i][j] * H[j][n - 1]; + sa = sa + H[i][j] * H[j][n]; + } - var tOsc = X.mmul(wOsc); + w = H[i][i] - p; - numerator = X.transpose().mmul(tOsc); - denominator = tOsc.transpose().mmul(tOsc)[0][0]; - var pOsc = numerator.div(denominator); + if (e[i] < 0) { + z = w; + r = ra; + s = sa; + } else { + l = i; + if (e[i] === 0) { + cdivres = cdiv(-ra, -sa, w, q); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; + vi = (d[i] - p) * 2 * q; + if (vr === 0 && vi === 0) { + vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); + } + cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { + H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; + H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; + } else { + cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); + H[i + 1][n - 1] = cdivres[0]; + H[i + 1][n] = cdivres[1]; + } + } - X.sub(tOsc.mmul(pOsc.transpose())); - orthoW[i] = wOsc.getColumn(0); - orthoT[i] = tOsc.getColumn(0); - orthoP[i] = pOsc.getColumn(0); + t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n - 1] = H[j][n - 1] / t; + H[j][n] = H[j][n] / t; + } + } + } + } + } } - this.Xosc = X; - - var sumOfSquaresXosx = this.Xosc.clone().mul(this.Xosc).sum(); - this.R2X = 1 - sumOfSquaresXosx/sumOfSquaresX; + for (i = 0; i < nn; i++) { + if (i < low || i > high) { + for (j = i; j < nn; j++) { + V[i][j] = H[i][j]; + } + } + } - this.W = orthoW; - this.T = orthoT; - this.P = orthoP; - this.numberOSC = numberOSC; + for (j = nn - 1; j >= low; j--) { + for (i = low; i <= high; i++) { + z = 0; + for (k = low; k <= Math.min(j, high); k++) { + z = z + V[i][k] * H[k][j]; + } + V[i][j] = z; + } + } } -OPLS.prototype.correctDataset = function (dataset) { - var X = new Matrix(dataset); - - var sumOfSquaresX = X.clone().mul(X).sum(); - for (var i = 0; i < this.numberOSC; i++) { - var currentW = this.W.getColumnVector(i); - var currentP = this.P.getColumnVector(i); - - var t = X.mmul(currentW); - X.sub(t.mmul(currentP)); +function cdiv(xr, xi, yr, yi) { + var r, d; + if (Math.abs(yr) > Math.abs(yi)) { + r = yi / yr; + d = yr + r * yi; + return [(xr + r * xi) / d, (xi - r * xr) / d]; + } else { + r = yr / yi; + d = yi + r * yr; + return [(r * xr + xi) / d, (r * xi - xr) / d]; } - var sumOfSquaresXosx = X.clone().mul(X).sum(); +} - var R2X = 1 - sumOfSquaresXosx / sumOfSquaresX; +/* harmony default export */ __webpack_exports__["a"] = (EigenvalueDecomposition); - return { - datasetOsc: X, - R2Dataset: R2X - }; -}; /***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { +/* 232 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony export (immutable) */ __webpack_exports__["b"] = inverse; +/* harmony export (immutable) */ __webpack_exports__["a"] = solve; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__matrix__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__dc_lu__ = __webpack_require__(36); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__dc_qr__ = __webpack_require__(71); -var Matrix = __webpack_require__(0); -var Utils = __webpack_require__(12); - -class PLS { - constructor(X, Y) { - if (X === true) { - const model = Y; - 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; - } else { - if (X.length !== Y.length) - throw new RangeError('The number of X rows must be equal to the number of Y rows'); - - const resultX = Utils.featureNormalize(X); - this.X = resultX.result; - this.meanX = resultX.means; - this.stdDevX = resultX.std; - const resultY = Utils.featureNormalize(Y); - this.Y = resultY.result; - this.meanY = resultY.means; - this.stdDevY = resultY.std; - } - } - /** - * 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 {Object} options - recieves the latentVectors and the tolerance of each step of the PLS - */ - train(options) { - if(options === undefined) options = {}; - var latentVectors = options.latentVectors; - if (latentVectors === undefined) { - latentVectors = Math.min(this.X.length - 1, this.X[0].length); - } +function inverse(matrix) { + matrix = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(matrix); + return solve(matrix, __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].eye(matrix.rows)); +} - var tolerance = options.tolerance; - if (tolerance === undefined) { - tolerance = 1e-5; - } - - var X = this.X; - var Y = this.Y; +function solve(leftHandSide, rightHandSide) { + leftHandSide = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(leftHandSide); + rightHandSide = __WEBPACK_IMPORTED_MODULE_0__matrix__["a" /* default */].checkMatrix(rightHandSide); + return leftHandSide.isSquare() ? new __WEBPACK_IMPORTED_MODULE_1__dc_lu__["a" /* default */](leftHandSide).solve(rightHandSide) : new __WEBPACK_IMPORTED_MODULE_2__dc_qr__["a" /* default */](leftHandSide).solve(rightHandSide); +} - var rx = X.rows; - var cx = X.columns; - var ry = Y.rows; - var cy = Y.columns; - var ssqXcal = X.clone().mul(X).sum(); // for the r² - var sumOfSquaresY = Y.clone().mul(Y).sum(); +/***/ }), +/* 233 */ +/***/ (function(module, exports) { - var n = latentVectors; //Math.max(cx, cy); // components of the pls - 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; +if (!Symbol.species) { + Symbol.species = Symbol.for('@@species'); +} - while(Utils.norm(Y) > tolerance && k < n) { - var transposeX = X.transpose(); - var transposeY = Y.transpose(); - var tIndex = maxSumColIndex(X.clone().mulM(X)); - var uIndex = maxSumColIndex(Y.clone().mulM(Y)); +/***/ }), +/* 234 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - var t1 = X.getColumnVector(tIndex); - var u = Y.getColumnVector(uIndex); - var t = Matrix.zeros(rx, 1); +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(12); - while(Utils.norm(t1.clone().sub(t)) > tolerance) { - var w = transposeX.mmul(u); - w.div(Utils.norm(w)); - t = t1; - t1 = X.mmul(w); - var q = transposeY.mmul(t1); - q.div(Utils.norm(q)); - u = Y.mmul(q); - } - t = t1; - var num = transposeX.mmul(t); - var den = (t.transpose().mmul(t))[0][0]; - var p = num.div(den); - var pnorm = Utils.norm(p); - p.div(pnorm); - t.mul(pnorm); - w.mul(pnorm); +class MatrixColumnView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, column) { + super(matrix, matrix.rows, 1); + this.column = column; + } - num = u.transpose().mmul(t); - den = (t.transpose().mmul(t))[0][0]; - var b = (num.div(den))[0][0]; - X.sub(t.mmul(p.transpose())); - Y.sub(t.clone().mul(b).mmul(q.transpose())); + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.column, value); + return this; + } - T.setColumn(k, t); - P.setColumn(k, p); - U.setColumn(k, u); - Q.setColumn(k, q); - W.setColumn(k, w); + get(rowIndex) { + return this.matrix.get(rowIndex, this.column); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixColumnView; - B[k][k] = b; - k++; - } - k--; - T = T.subMatrix(0, T.rows - 1, 0, k); - P = P.subMatrix(0, P.rows - 1, 0, k); - U = U.subMatrix(0, U.rows - 1, 0, k); - Q = Q.subMatrix(0, Q.rows - 1, 0, k); - W = W.subMatrix(0, W.rows - 1, 0, k); - B = B.subMatrix(0, k, 0, k); - // TODO: review of R2Y - //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0]; +/***/ }), +/* 235 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - this.ssqYcal = sumOfSquaresY; - this.E = X; - this.F = Y; - this.T = T; - this.P = P; - this.U = U; - this.Q = Q; - this.W = W; - this.B = B; - this.PBQ = P.mmul(B).mmul(Q.transpose()); - this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0]; +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(12); + + +class MatrixFlipColumnView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); } - /** - * Predicts the behavior of the given dataset. - * @param dataset - data to be predicted. - * @returns {Matrix} - predictions of each element of the dataset. - */ - predict(dataset) { - var X = Matrix.checkMatrix(dataset); - X = X.subRowVector(this.meanX).divRowVector(this.stdDevX); - var Y = X.mmul(this.PBQ); - Y = Y.mulRowVector(this.stdDevY).addRowVector(this.meanY); - return Y; + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); + return this; } - /** - * Returns the explained variance on training of the PLS model - * @return {number} - */ - getExplainedVariance() { - return this.R2X; + get(rowIndex, columnIndex) { + return this.matrix.get(rowIndex, this.columns - columnIndex - 1); } - - toJSON() { - return { - name: 'PLS', - R2X: this.R2X, - meanX: this.meanX, - stdDevX: this.stdDevX, - meanY: this.meanY, - stdDevY: this.stdDevY, - PBQ: this.PBQ, - }; +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixFlipColumnView; + + + +/***/ }), +/* 236 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(12); + + +class MatrixFlipRowView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); } - /** - * Load a PLS model from a JSON Object - * @param model - * @return {PLS} - PLS object from the given model - */ - static load(model) { - if (model.name !== 'PLS') - throw new RangeError('Invalid model: ' + model.name); - return new PLS(true, model); + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(this.rows - rowIndex - 1, columnIndex); } } +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixFlipRowView; -module.exports = PLS; -/** - * Retrieves the sum at the column of the given matrix. - * @param matrix - * @param column - * @returns {number} - */ -function getColSum(matrix, column) { - var sum = 0; - for (var i = 0; i < matrix.rows; i++) { - sum += matrix[i][column]; + +/***/ }), +/* 237 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(12); + + +class MatrixRowView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, row) { + super(matrix, 1, matrix.columns); + this.row = row; } - return sum; -} -/** - * Function that returns the index where the sum of each - * column vector is maximum. - * @param {Matrix} data - * @returns {number} index of the maximum - */ -function maxSumColIndex(data) { - var maxIndex = 0; - var maxSum = -Infinity; - for(var i = 0; i < data.columns; ++i) { - var currentSum = getColSum(data, i); - if(currentSum > maxSum) { - maxSum = currentSum; - maxIndex = i; - } + set(rowIndex, columnIndex, value) { + this.matrix.set(this.row, columnIndex, value); + return this; + } + + get(rowIndex, columnIndex) { + return this.matrix.get(this.row, columnIndex); } - return maxIndex; } +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixRowView; + /***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { +/* 238 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(12); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(19); -/* - * Function that calculate the linear fit in the form f(x) = Ce^(A * x) and - * return the A and C coefficient of the given formula. - * - * @param {Vector} X - Vector of the x positions of the points. - * @param {Vector} Y - Vector of the y positions of the points. - * @return {Object} coefficients - The A and C coefficients. - * - * Created by acastillo on 5/12/16. - */ -const maybeToPrecision = __webpack_require__(6).maybeToPrecision; -const SimpleLinearRegression = __webpack_require__(13); -const BaseRegression = __webpack_require__(4); +class MatrixSelectionView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, rowIndices, columnIndices) { + var indices = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["i" /* checkIndices */])(matrix, rowIndices, columnIndices); + super(matrix, indices.row.length, indices.column.length); + this.rowIndices = indices.row; + this.columnIndices = indices.column; + } -class ExpRegression extends BaseRegression { - /** - * @constructor - * @param {Array} x - Independent variable - * @param {Array} y - Dependent variable - * @param {object} options - */ - constructor(x, y, options) { - super(); - let opt = options || {}; - if (x === true) { // reloading model - this.A = y.A; - this.C = y.C; - if (y.quality) { - this.quality = y.quality; - } - } else { - var n = x.length; - if (n !== y.length) { - throw new RangeError('input and output array have a different length'); - } - var yl = new Array(n); - for (var i = 0; i < n; i++) { - yl[i] = Math.log(y[i]); - } + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); + return this; + } - var linear = new SimpleLinearRegression(x, yl, {computeCoefficient: false}); - this.A = linear.slope; - this.C = Math.exp(linear.intercept); - if (opt.computeQuality) { - this.quality = this.modelQuality(x, y); - } - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixSelectionView; + + + +/***/ }), +/* 239 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(12); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util__ = __webpack_require__(19); + + + +class MatrixSubView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix, startRow, endRow, startColumn, endColumn) { + __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__util__["h" /* checkRange */])(matrix, startRow, endRow, startColumn, endColumn); + super(matrix, endRow - startRow + 1, endColumn - startColumn + 1); + this.startRow = startRow; + this.startColumn = startColumn; } - _predict(newInputs) { - return this.C * Math.exp(newInputs * this.A); + set(rowIndex, columnIndex, value) { + this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); + return this; } - toJSON() { - var out = {name: 'expRegression', A: this.A, C: this.C}; - if (this.quality) { - out.quality = this.quality; - } - return out; + get(rowIndex, columnIndex) { + return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixSubView; - toString(precision) { - return 'f(x) = ' + maybeToPrecision(this.C, precision) + ' * exp(' + maybeToPrecision(this.A, precision) + ' * x)'; - } - toLaTeX(precision) { - if (this.A >= 0) { - return 'f(x) = ' + maybeToPrecision(this.C, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}'; - } else { - return 'f(x) = \\frac{' + maybeToPrecision(this.C, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}'; - } +/***/ }), +/* 240 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__base__ = __webpack_require__(12); + + +class MatrixTransposeView extends __WEBPACK_IMPORTED_MODULE_0__base__["a" /* default */] { + constructor(matrix) { + super(matrix, matrix.columns, matrix.rows); } - static load(json) { - if (json.name !== 'expRegression') { - throw new TypeError('not a exp regression model'); - } - return new ExpRegression(true, json); + set(rowIndex, columnIndex, value) { + this.matrix.set(columnIndex, rowIndex, value); + return this; } -} + get(rowIndex, columnIndex) { + return this.matrix.get(columnIndex, rowIndex); + } +} +/* harmony export (immutable) */ __webpack_exports__["a"] = MatrixTransposeView; -module.exports = ExpRegression; /***/ }), -/* 152 */ +/* 241 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const Matrix = __webpack_require__(0); -const Kernel = __webpack_require__(8); +const matrixLib = __webpack_require__(73); +const Matrix = matrixLib.Matrix; +const solve = matrixLib.solve; +const Kernel = __webpack_require__(20); -const BaseRegression = __webpack_require__(4); +const BaseRegression = __webpack_require__(38); const defaultOptions = { lambda: 0.1, @@ -15554,7 +33178,7 @@ class KernelRidgeRegression extends BaseRegression { const n = inputs.length; K.add(Matrix.eye(n, n).mul(options.lambda)); - this.alpha = K.solve(outputs); + this.alpha = solve(K, outputs); this.inputs = inputs; this.kernelType = options.kernelType; this.kernelOptions = options.kernelOptions; @@ -15596,15 +33220,16 @@ module.exports = KernelRidgeRegression; /***/ }), -/* 153 */ +/* 242 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const Matrix = __webpack_require__(0); -const SVD = Matrix.DC.SingularValueDecomposition; -const BaseRegression = __webpack_require__(4); +const matrixLib = __webpack_require__(73); +const Matrix = matrixLib.Matrix; +const SVD = matrixLib.SVD; +const BaseRegression = __webpack_require__(38); const defaultOptions = { order: 2 @@ -15802,7 +33427,7 @@ function abs(i, j) { /***/ }), -/* 154 */ +/* 243 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -15819,10 +33444,10 @@ function abs(i, j) { * Created by acastillo on 5/12/16. */ -const maybeToPrecision = __webpack_require__(6).maybeToPrecision; -const PolynomialRegression = __webpack_require__(40); +const maybeToPrecision = __webpack_require__(244).maybeToPrecision; +const PolynomialRegression = __webpack_require__(68); // const PowerRegression = require('./power-regression'); -const BaseRegression = __webpack_require__(4); +const BaseRegression = __webpack_require__(38); class PotentialRegression extends BaseRegression { /** @@ -15847,7 +33472,7 @@ class PotentialRegression extends BaseRegression { throw new RangeError('input and output array have a different length'); } - var linear = new PolynomialRegression(x, y, [M], {computeCoefficient: true}); + var linear = new PolynomialRegression(x, y, [M]); this.A = linear.coefficients[0]; this.M = M; if (opt.computeQuality) { @@ -15893,230 +33518,48 @@ module.exports = PotentialRegression; /***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/** - * This class implements the power regression f(x)=A*x^B - * Created by acastillo on 5/12/16. - */ - -const maybeToPrecision = __webpack_require__(6).maybeToPrecision; -const SimpleLinearRegression = __webpack_require__(13); -const BaseRegression = __webpack_require__(4); - -class PowerRegression extends BaseRegression { - /** - * @constructor - * @param x: Independent variable - * @param y: Dependent variable - * @param options - */ - constructor(x, y, options) { - super(); - let opt = options || {}; - if (x === true) { // reloading model - this.A = y.A; - this.B = y.B; - this.quality = y.quality || {}; - if (y.quality.r) { - this.quality.r = y.quality.r; - this.quality.r2 = y.quality.r2; - } - if (y.quality.chi2) { - this.quality.chi2 = y.quality.chi2; - } - } else { - var n = x.length; - if (n !== y.length) { - throw new RangeError('input and output array have a different length'); - } - var xl = new Array(n), yl = new Array(n); - for (var i = 0; i < n; i++) { - xl[i] = Math.log(x[i]); - yl[i] = Math.log(y[i]); - } - - var linear = new SimpleLinearRegression(xl, yl, {computeCoefficient: false}); - this.A = Math.exp(linear.intercept); - this.B = linear.slope; - if (opt.computeQuality) { - this.quality = this.modelQuality(x, y); - } - } - } - - _predict(newInputs) { - return this.A * Math.pow(newInputs, this.B); - } - - toJSON() { - var out = {name: 'powerRegression', A: this.A, B: this.B}; - if (this.quality) { - out.quality = this.quality; - } - return out; - } - - toString(precision) { - return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + maybeToPrecision(this.B, precision); - } - - toLaTeX(precision) { - if (this.B >= 0) { - return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}'; - } else { - return 'f(x) = \\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + maybeToPrecision(-this.B, precision) + '}}'; - } - } - - static load(json) { - if (json.name !== 'powerRegression') { - throw new TypeError('not a power regression model'); - } - return new PowerRegression(true, json); - } -} - -module.exports = PowerRegression; - - -/***/ }), -/* 156 */ +/* 244 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const BaseRegression = __webpack_require__(4); -const maybeToPrecision = __webpack_require__(6).maybeToPrecision; -const median = __webpack_require__(14).median; - -class TheilSenRegression extends BaseRegression { - - /** - * Theil–Sen estimator - * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator - * @param {Array} x - * @param {Array} y - * @param {object} options - * @constructor - */ - constructor(x, y, options) { - options = options || {}; - super(); - if (x === true) { - // loads the model - this.slope = y.slope; - this.intercept = y.intercept; - this.quality = Object.assign({}, y.quality, this.quality); +exports.maybeToPrecision = function maybeToPrecision(value, digits) { + if (value < 0) { + value = -1 * value; + if (digits) { + return '- ' + value.toPrecision(digits); } else { - // creates the model - let len = x.length; - if (len !== y.length) { - throw new RangeError('Input and output array have a different length'); - } - - let slopes = new Array(len * len); - let count = 0; - for (let i = 0; i < len; ++i) { - for (let j = i + 1; j < len; ++j) { - if (x[i] !== x[j]) { - slopes[count++] = (y[j] - y[i]) / (x[j] - x[i]); - } - } - } - 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]; - } - - this.slope = medianSlope; - this.intercept = median(cuts); - this.coefficients = [this.intercept, this.slope]; - if (options.computeQuality) { - this.quality = this.modelQuality(x, y); - } - } - - } - - toJSON() { - var out = { - name: 'TheilSenRegression', - slope: this.slope, - intercept: this.intercept - }; - if (this.quality) { - out.quality = this.quality; + return '- ' + value.toString(); } - - return out; - } - - _predict(input) { - return this.slope * input + this.intercept; - } - - computeX(input) { - return (input - this.intercept) / this.slope; - } - - toString(precision) { - var result = 'f(x) = '; - if (this.slope) { - var xFactor = maybeToPrecision(this.slope, precision); - result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x'; - if (this.intercept) { - var absIntercept = Math.abs(this.intercept); - var operator = absIntercept === this.intercept ? '+' : '-'; - result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision); - } + } else { + if (digits) { + return value.toPrecision(digits); } else { - result += maybeToPrecision(this.intercept, precision); - } - return result; - } - - toLaTeX(precision) { - return this.toString(precision); - } - - static load(json) { - if (json.name !== 'TheilSenRegression') { - throw new TypeError('not a Theil-Sen model'); + return value.toString(); } - return new TheilSenRegression(true, json); } -} - -module.exports = TheilSenRegression; +}; /***/ }), -/* 157 */ +/* 245 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -exports.array = __webpack_require__(41); -exports.matrix = __webpack_require__(158); +exports.array = __webpack_require__(74); +exports.matrix = __webpack_require__(246); /***/ }), -/* 158 */ +/* 246 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var arrayStat = __webpack_require__(41); +var arrayStat = __webpack_require__(74); // https://github.com/accord-net/framework/blob/development/Sources/Accord.Statistics/Tools.cs @@ -16638,10 +34081,10 @@ module.exports = { /***/ }), -/* 159 */ +/* 247 */ /***/ (function(module, exports, __webpack_require__) { -var NodeSquare = __webpack_require__(42); +var NodeSquare = __webpack_require__(75); function NodeHexagonal(x, y, weights, som) { @@ -16673,13 +34116,13 @@ NodeHexagonal.prototype.getPosition = function getPosition() { module.exports = NodeHexagonal; /***/ }), -/* 160 */ +/* 248 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var arrayStat = __webpack_require__(14); +var arrayStat = __webpack_require__(76); function compareNumbers(a, b) { return a - b; @@ -17291,7 +34734,7 @@ exports.weightedScatter = function weightedScatter(matrix, weights, means, facto /***/ }), -/* 161 */ +/* 249 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -17414,7 +34857,7 @@ module.exports = { }; /***/ }), -/* 162 */ +/* 250 */ /***/ (function(module, exports) { module.exports = newArray @@ -17430,7 +34873,7 @@ function newArray (n, value) { /***/ }), -/* 163 */ +/* 251 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -17441,7 +34884,7 @@ module.exports = Number.isNaN || function (x) { /***/ }), -/* 164 */ +/* 252 */ /***/ (function(module, exports) { // shim for using process in browser @@ -17614,6 +35057,10 @@ process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); @@ -17627,7 +35074,7 @@ process.umask = function() { return 0; }; /***/ }), -/* 165 */ +/* 253 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { @@ -17656,7 +35103,7 @@ if (typeof Object.create === 'function') { /***/ }), -/* 166 */ +/* 254 */ /***/ (function(module, exports) { module.exports = function isBuffer(arg) { @@ -17667,7 +35114,7 @@ module.exports = function isBuffer(arg) { } /***/ }), -/* 167 */ +/* 255 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. @@ -18195,7 +35642,7 @@ function isPrimitive(arg) { } exports.isPrimitive = isPrimitive; -exports.isBuffer = __webpack_require__(166); +exports.isBuffer = __webpack_require__(254); function objectToString(o) { return Object.prototype.toString.call(o); @@ -18239,7 +35686,7 @@ exports.log = function() { * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ -exports.inherits = __webpack_require__(165); +exports.inherits = __webpack_require__(253); exports._extend = function(origin, add) { // Don't do anything if add isn't an object @@ -18257,10 +35704,10 @@ function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(168), __webpack_require__(164))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(256), __webpack_require__(252))) /***/ }), -/* 168 */ +/* 256 */ /***/ (function(module, exports) { var g; @@ -18286,79 +35733,6 @@ try { module.exports = g; -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// Root packages -exports.ArrayUtils = exports.AU = __webpack_require__(16); -exports.BitArray = __webpack_require__(43); -exports.HashTable = __webpack_require__(19); -exports.Matrix = __webpack_require__(0); -exports.PadArray = __webpack_require__(20); -exports.Regression = __webpack_require__(55); -exports.binarySearch = __webpack_require__(15); -exports.numSort = __webpack_require__(21); - - -// Math packages -var Math = exports.Math = {}; - -var distance = __webpack_require__(18); -Math.Distance = distance.distance; -Math.Similarity = distance.similarity; -Math.DistanceMatrix = __webpack_require__(45); -Math.SG = __webpack_require__(57); -Math.SGG = __webpack_require__(56); -Math.Matrix = exports.Matrix; -Math.SparseMatrix = __webpack_require__(59); -Math.BellOptimizer = __webpack_require__(51); -Math.CurveFitting = __webpack_require__(17); -Math.Kernel = __webpack_require__(8); - - -// Statistics packages -var Stat = exports.Stat = {}; - -Stat.array = __webpack_require__(2).array; -Stat.matrix = __webpack_require__(2).matrix; -Stat.PCA = __webpack_require__(52); -Stat.Performance = __webpack_require__(53); - - -// Random number generation -var RNG = exports.RNG = {}; -RNG.XSadd = __webpack_require__(61); - - -// Supervised learning -var SL = exports.SL = {}; - -SL.CV = __webpack_require__(44); -SL.CrossValidation = SL.CV; // Alias -SL.SVM = __webpack_require__(60); -SL.KNN = __webpack_require__(49); -SL.NaiveBayes = __webpack_require__(50); -SL.PLS = __webpack_require__(54); - - -// Clustering -var Clust = exports.Clust = {}; - -Clust.kmeans = __webpack_require__(48); -Clust.hclust = __webpack_require__(47); - - -// Neural networks -var NN = exports.NN = exports.nn = {}; - -NN.SOM = __webpack_require__(58); -NN.FNN = __webpack_require__(46); - - /***/ }) /******/ ]); }); \ No newline at end of file diff --git a/dist/ml.min.js b/dist/ml.min.js index 4d857df..105ce97 100644 --- a/dist/ml.min.js +++ b/dist/ml.min.js @@ -1,9 +1,9 @@ -(function(R,D){'object'==typeof exports&&'object'==typeof module?module.exports=D():'function'==typeof define&&define.amd?define([],D):'object'==typeof exports?exports.ML=D():R.ML=D()})(this,function(){return function(I){function R(O){if(D[O])return D[O].exports;var E=D[O]={i:O,l:!1,exports:{}};return I[O].call(E.exports,E,E.exports,R),E.l=!0,E.exports}var D={};return R.m=I,R.c=D,R.i=function(O){return O},R.d=function(O,E,G){R.o(O,E)||Object.defineProperty(O,E,{configurable:!1,enumerable:!0,get:G})},R.n=function(O){var E=O&&O.__esModule?function(){return O['default']}:function(){return O};return R.d(E,'a',E),E},R.o=function(O,E){return Object.prototype.hasOwnProperty.call(O,E)},R.p='',R(R.s=169)}([function(I,R,D){'use strict';I.exports=D(3).Matrix,I.exports.Decompositions=I.exports.DC=D(138)},function(I){'use strict';function O(G,Z){for(var $=0,ee=0;eeE?(E=-1*E,G?'- '+E.toPrecision(G):'- '+E.toString()):G?E.toPrecision(G):E.toString()}},function(I,R,D){'use strict';var O=D(3);R.checkRowIndex=function(G,Z,$){var ee=$?G.rows:G.rows-1;if(0>Z||Z>ee)throw new RangeError('Row index out of range')},R.checkColumnIndex=function(G,Z,$){var ee=$?G.columns:G.columns-1;if(0>Z||Z>ee)throw new RangeError('Column index out of range')},R.checkRowVector=function(G,Z){if(Z.to1DArray&&(Z=Z.to1DArray()),Z.length!==G.columns)throw new RangeError('vector size must be the same as the number of columns');return Z},R.checkColumnVector=function(G,Z){if(Z.to1DArray&&(Z=Z.to1DArray()),Z.length!==G.rows)throw new RangeError('vector size must be the same as the number of rows');return Z},R.checkIndices=function(G,Z,$){var ee=Z.some(ie=>{return 0>ie||ie>=G.rows}),te=$.some(ie=>{return 0>ie||ie>=G.columns});if(ee||te)throw new RangeError('Indices are out of range');if('object'!=typeof Z||'object'!=typeof $)throw new TypeError('Unexpected type for row/column indices');return Array.isArray(Z)||(Z=Array.from(Z)),Array.isArray($)||(Z=Array.from($)),{row:Z,column:$}},R.checkRange=function(G,Z,$,ee,te){if(5!==arguments.length)throw new TypeError('Invalid argument type');var ie=Array.from(arguments).slice(1).some(function(ne){return'number'!=typeof ne});if(ie)throw new TypeError('Invalid argument type');if(Z>$||ee>te||0>Z||Z>=G.rows||0>$||$>=G.rows||0>ee||ee>=G.columns||0>te||te>=G.columns)throw new RangeError('Submatrix indices are out of range')},R.getRange=function(G,Z){for(var $=Array(Z-G+1),ee=0;ee<$.length;ee++)$[ee]=G+ee;return $},R.sumByRow=function(G){for(var Z=O.Matrix.zeros(G.rows,1),$=0;$G)throw new RangeError('Threshold too small');var Z=new O;Z.children=this.children,Z.distance=this.distance,Z.index=this.index;for(var $=[Z],ee=[],te;0<$.length;)te=$.shift(),G>=te.distance?ee.push(te):$=$.concat(te.children);return ee},O.prototype.group=function(G){if(!Number.isInteger(G)||1>G)throw new RangeError('Number of groups must be a positive integer');const Z=new E(function(te,ie){return ie.distance-te.distance});for(Z.push(this);Z.size()Z.push(te))}var ee=new O;return ee.children=Z.toArray(),ee.distance=this.distance,ee},I.exports=O},function(I,R){'use strict';R.hypotenuse=function(E,G){var Z;return Math.abs(E)>Math.abs(G)?(Z=G/E,Math.abs(E)*Math.sqrt(1+Z*Z)):0===G?0:(Z=E/G,Math.abs(G)*Math.sqrt(1+Z*Z))},R.getEmpty2DArray=function(O,E){for(var G=Array(O),Z=0;ZMath.abs(ee-1)?'':ee+' * ')+'x',this.intercept){var te=Math.abs(this.intercept),ie=te===this.intercept?'+':'-';$+=' '+ie+' '+O(te,Z)}}else $+=O(this.intercept,Z);return $}toLaTeX(Z){return this.toString(Z)}static load(Z){if('simpleLinearRegression'!==Z.name)throw new TypeError('not a SLR model');return new G(!0,Z)}}I.exports=G},function(I,R){'use strict';function O(E,G){return E-G}R.sum=function(G){for(var E=0,Z=0;ZE&&(E=G[$]);return E},R.min=function(G){for(var E=G[0],Z=G.length,$=1;$$&&($=G[te]);return{min:Z,max:$}},R.arithmeticMean=function(G){for(var Z=0,$=G.length,ee=0;ee<$;ee++)Z+=G[ee];return Z/$},R.mean=R.arithmeticMean,R.geometricMean=function(G){for(var Z=1,$=G.length,ee=0;ee<$;ee++)Z*=G[ee];return Math.pow(Z,1/$)},R.logMean=function(G){for(var Z=0,$=G.length,ee=0;ee<$;ee++)Z+=Math.log(G[ee]);return Z/$},R.grandMean=function(G,Z){for(var $=0,ee=0,te=G.length,ie=0;ie$)throw new RangeError('sum of values is negative');return Z/$},R.median=function(G,Z){Z===void 0&&(Z=!1),Z||(G=[].concat(G).sort(O));var $=G.length,ee=Math.floor($/2);return 0==$%2?0.5*(G[ee-1]+G[ee]):G[ee]},R.variance=function(G,Z){Z===void 0&&(Z=!0);for(var $=R.mean(G),ee=0,te=G.length,ie=0,ne;ieoe&&(oe=$[ee],se=ee);return te[se]},R.covariance=function(G,Z,$){'undefined'==typeof $&&($=!0);var ee=R.mean(G),te=R.mean(Z);if(G.length!==Z.length)throw'Vectors do not have the same dimensions';for(var ie=0,ne=G.length,oe=0;oeG||G>=D.length)throw new RangeError('invalid lower bound');if(void 0===Z)Z=D.length-1;else if(Z|=0,Z=D.length)throw new RangeError('invalid upper bound');for(;G<=Z;)if($=G+(Z-G>>1),ee=+E(D[$],O,$,D),0>ee)G=$+1;else if(0me)throw new RangeError(`initial capacity must not be less than zero: ${me}`);const ge=ue.minLoadFactor===void 0?1/6:ue.minLoadFactor,pe=ue.maxLoadFactor===void 0?2/3:ue.maxLoadFactor;if(0>ge||1<=ge)throw new RangeError(`invalid minLoadFactor: ${ge}`);if(0>=pe||1<=pe)throw new RangeError(`invalid maxLoadFactor: ${pe}`);if(ge>=pe)throw new RangeError(`minLoadFactor (${ge}) must be smaller than maxLoadFactor (${pe})`);let he=me;he=0|he/pe,he=te(he),0===he&&(he=1),this.table=$(he,0),this.values=$(he,0),this.state=$(he,0),this.minLoadFactor=ge,this.maxLoadFactor=he===ie?1:pe,this.distinct=0,this.freeEntries=he,this.lowWaterMark=0,this.highWaterMark=E(he,this.maxLoadFactor)}clone(){return new ce(this)}get size(){return this.distinct}get(ue){const me=this.indexOfKey(ue);return 0>me?0:this.values[me]}set(ue,me){let ge=this.indexOfInsertion(ue);if(0>ge)return ge=-ge-1,this.values[ge]=me,!1;if(this.distinct>this.highWaterMark){const pe=G(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);return this.rehash(pe),this.set(ue,me)}if(this.table[ge]=ue,this.values[ge]=me,this.state[ge]===ne&&this.freeEntries--,this.state[ge]=oe,this.distinct++,1>this.freeEntries){const pe=G(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);this.rehash(pe)}return!0}remove(ue,me){const ge=this.indexOfKey(ue);return!(0>ge)&&(this.state[ge]=se,this.distinct--,me||this.maybeShrinkCapacity(),!0)}delete(ue,me){const ge=this.indexOfKey(ue);return!(0>ge)&&(this.state[ge]=ne,this.distinct--,me||this.maybeShrinkCapacity(),!0)}maybeShrinkCapacity(){if(this.distinctxe&&(xe+=pe);return ge[xe]===ne?-1:xe}containsValue(ue){return 0<=this.indexOfValue(ue)}indexOfValue(ue){const me=this.values,ge=this.state;for(var pe=0;pexe&&(xe+=pe);if(ge[xe]===se){const ye=xe;for(;ge[xe]!==ne&&(ge[xe]===se||me[xe]!==ue);)xe-=fe,0>xe&&(xe+=pe);ge[xe]===ne&&(xe=ye)}return ge[xe]===oe?-xe-1:xe}ensureCapacity(ue){if(this.table.lengthie||te.size[1]>ie)throw new RangeError('expanded value should not be bigger than the data length');for(se=0;seye[be][ve]?fe[be][ve]:ye[be][ve];return we},solve:function(fe,ye){return fe.solve(ye)},inv:function(fe){return'number'==typeof fe?1/fe:fe.inverse()},sqrt:function(fe){if('number'==typeof fe)return Math.sqrt(fe);for(var ye=fe.rows,je=fe.columns,ke=new xe(ye,je),we=0;weee.activation(oe,$.activationParam):ee.activation,ne=1ee.derivate(oe,$.activationParam):ee.derivate;this.activationFunction=function(oe,se){this[oe][se]=ie(this[oe][se])},this.derivate=function(oe,se){this[oe][se]=ne(this[oe][se])},$.model?(this.W=O.checkMatrix($.W),this.b=O.checkMatrix($.b)):(this.W=O.rand(this.inputSize,this.outputSize),this.b=O.zeros(1,this.outputSize),this.W.apply(function(oe,se){this[oe][se]/=Math.sqrt($.inputSize)}))}forward($){var ee=$.mmul(this.W).addRowVector(this.b);return ee.apply(this.activationFunction),this.a=ee.clone(),ee}backpropagation($,ee){this.dW=ee.transposeView().mmul($),this.db=E.sumCol($);var te=ee.clone();return $.mmul(this.W.transposeView()).mul(te.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($){if('Layer'!==$.model)throw new RangeError('the current model is not a Layer model');return new Z($)}}I.exports=Z},function(I){'use strict';function O(ee){return 1/(1+Math.exp(-ee))}function E(ee,te){return 0>ee?te*(Math.exp(ee)-1):ee}const $={tanh:{activation:Math.tanh,derivate:ee=>1-ee*ee},identity:{activation:ee=>ee,derivate:()=>1},logistic:{activation:O,derivate:ee=>O(ee)*(1-O(ee))},arctan:{activation:Math.atan,derivate:ee=>1/(ee*ee+1)},softsign:{activation:ee=>ee/(1+Math.abs(ee)),derivate:ee=>1/((1+Math.abs(ee))*(1+Math.abs(ee)))},relu:{activation:ee=>0>ee?0:ee,derivate:ee=>0>ee?0:1},softplus:{activation:ee=>Math.log(1+Math.exp(ee)),derivate:ee=>1/(1+Math.exp(-ee))},bent:{activation:ee=>(Math.sqrt(ee*ee+1)-1)/2+ee,derivate:ee=>ee/(2*Math.sqrt(ee*ee+1))+1},sinusoid:{activation:Math.sin,derivate:Math.cos},sinc:{activation:ee=>0===ee?1:Math.sin(ee)/ee,derivate:ee=>0===ee?0:Math.cos(ee)/ee-Math.sin(ee)/(ee*ee)},gaussian:{activation:ee=>Math.exp(-(ee*ee)),derivate:ee=>-2*ee*Math.exp(-(ee*ee))},'parametric-relu':{activation:(ee,te)=>0>ee?te*ee:ee,derivate:(ee,te)=>0>ee?te:1},'exponential-elu':{activation:E,derivate:(ee,te)=>0>ee?E(ee,te)+te:1},'soft-exponential':{activation:function(ee,te){return 0>te?-Math.log(1-te*(ee+te))/te:0te?1/(1-te*(te+ee)):Math.exp(te*ee)}}};I.exports=$},function(I,R,D){'use strict';var Z=D(0);I.exports={dictOutputs:function($){for(var ee={},te={},ie=$.length,ne=0,oe=0;oene)return!1;return!0}},function(module,exports,__webpack_require__){'use strict';function abstractMatrix(superCtor){function checkDimensions(I,R){if(I.rows!==R.rows||I.columns!==R.columns)throw new RangeError('Matrices dimensions must be equal')}function compareNumbers(I,R){return I-R}function fillTemplateFunction(I,R){for(var D in R)I=I.replace(new RegExp('%'+D+'%','g'),R[D]);return I}superCtor===void 0&&(superCtor=Object);class I extends superCtor{static get[Symbol.species](){return this}static from1DArray(R,D,O){if(R*D!==O.length)throw new RangeError('Data length does not match given dimensions');for(var G=new this(R,D),Z=0;ZR&&(R=this.get(D,O));return R}maxIndex(){for(var R=this.get(0,0),D=[0,0],O=0;OR&&(R=this.get(O,E),D[0]=O,D[1]=E);return D}min(){for(var R=this.get(0,0),D=0;DD&&(D=this.get(R,O));return D}maxRowIndex(R){util.checkRowIndex(this,R);for(var D=this.get(R,0),O=[R,0],E=1;ED&&(D=this.get(R,E),O[1]=E);return O}minRow(R){util.checkRowIndex(this,R);for(var D=this.get(R,0),O=1;OD&&(D=this.get(O,R));return D}maxColumnIndex(R){util.checkColumnIndex(this,R);for(var D=this.get(0,R),O=[0,R],E=1;ED&&(D=this.get(E,R),O[0]=E);return O}minColumn(R){util.checkColumnIndex(this,R);for(var D=this.get(0,R),O=1;O=se||512>=ae)return ne.mmul(oe);1==se%2&&1==ae%2?(ne=D(ne,se+1,ae+1),oe=D(oe,se+1,ae+1)):1==se%2?(ne=D(ne,se+1,ae),oe=D(oe,se+1,ae)):1==ae%2&&(ne=D(ne,se,ae+1),oe=D(oe,se,ae+1));var le=parseInt(ne.rows/2),de=parseInt(ne.columns/2),ce=ne.subMatrix(0,le-1,0,de-1),ue=oe.subMatrix(0,le-1,0,de-1),me=ne.subMatrix(0,le-1,de,ne.columns-1),ge=oe.subMatrix(0,le-1,de,oe.columns-1),pe=ne.subMatrix(le,ne.rows-1,0,de-1),he=oe.subMatrix(le,oe.rows-1,0,de-1),xe=ne.subMatrix(le,ne.rows-1,de,ne.columns-1),fe=oe.subMatrix(le,oe.rows-1,de,oe.columns-1),ye=O(I.add(ce,xe),I.add(ue,fe),le,de),je=O(I.add(pe,xe),ue,le,de),ke=O(ce,I.sub(ge,fe),le,de),we=O(xe,I.sub(he,ue),le,de),be=O(I.add(ce,me),fe,le,de),ve=O(I.sub(pe,ce),I.add(ue,ge),le,de),Me=O(I.sub(me,xe),I.add(he,fe),le,de),ze=I.add(ye,we);ze.sub(be),ze.add(Me);var Se=I.add(ke,be),qe=I.add(je,we),Ce=I.sub(ye,je);Ce.add(ke),Ce.add(ve);var Ie=I.zeros(2*ze.rows,2*ze.columns);return Ie=Ie.setSubMatrix(ze,0,0),Ie=Ie.setSubMatrix(Se,ze.rows,0),Ie=Ie.setSubMatrix(qe,0,ze.columns),Ie=Ie.setSubMatrix(Ce,ze.rows,ze.columns),Ie.subMatrix(0,se-1,0,ae-1)}var E=this.clone(),G=E.rows,Z=E.columns,$=R.rows,ee=R.columns;Z!==$&&console.warn(`Multiplying ${G} x ${Z} and ${$} x ${ee} matrix: dimensions do not match.`);var te=Math.max(G,$),ie=Math.max(Z,ee);return E=D(E,te,ie),R=D(R,te,ie),O(E,R,te,ie)}scaleRows(R,D){if(R=void 0===R?0:R,D=void 0===D?1:D,R>=D)throw new RangeError('min should be strictly smaller than max');for(var O=this.constructor.empty(this.rows,this.columns),E=0,G;E=D)throw new RangeError('min should be strictly smaller than max');for(var O=this.constructor.empty(this.rows,this.columns),E=0,G;EO||0>D||D>=this.columns||0>O||O>=this.columns)throw new RangeError('Argument out of range');for(var E=new this.constructor[Symbol.species](R.length,O-D+1),G=0;GR[G]||R[G]>=this.rows)throw new RangeError('Row index out of range: '+R[G]);E.set(G,Z-D,this.get(R[G],Z))}return E}subMatrixColumn(R,D,O){if(void 0===D&&(D=0),void 0===O&&(O=this.rows-1),D>O||0>D||D>=this.rows||0>O||O>=this.rows)throw new RangeError('Argument out of range');for(var E=new this.constructor[Symbol.species](O-D+1,R.length),G=0;GR[G]||R[G]>=this.columns)throw new RangeError('Column index out of range: '+R[G]);E.set(Z-D,G,this.get(Z,R[G]))}return E}setSubMatrix(R,D,O){R=this.constructor.checkMatrix(R);var E=D+R.rows-1,G=O+R.columns-1;util.checkRange(this,D,E,O,G);for(var Z=0;Zi||i>n)throw new RangeError('Row index out of range')},i.c=function(e,i,t){var n=t?e.columns:e.columns-1;if(0>i||i>n)throw new RangeError('Column index out of range')},i.b=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.columns)throw new RangeError('vector size must be the same as the number of columns');return i},i.d=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.rows)throw new RangeError('vector size must be the same as the number of rows');return i},i.i=function(e,i,t){var n=i.some((i)=>{return 0>i||i>=e.rows}),o=t.some((i)=>{return 0>i||i>=e.columns});if(n||o)throw new RangeError('Indices are out of range');if('object'!=typeof i||'object'!=typeof t)throw new TypeError('Unexpected type for row/column indices');return Array.isArray(i)||(i=Array.from(i)),Array.isArray(t)||(i=Array.from(t)),{row:i,column:t}},i.h=function(e,i,t,n,o){if(5!==arguments.length)throw new TypeError('Invalid argument type');var s=Array.from(arguments).slice(1).some(function(e){return'number'!=typeof e});if(s)throw new TypeError('Invalid argument type');if(i>t||n>o||0>i||i>=e.rows||0>t||t>=e.rows||0>n||n>=e.columns||0>o||o>=e.columns)throw new RangeError('Submatrix indices are out of range')},i.e=function(e){for(var t=n.a.zeros(e.rows,1),o=0;oi||i>n)throw new RangeError('Row index out of range')},i.checkColumnIndex=function(e,i,t){var n=t?e.columns:e.columns-1;if(0>i||i>n)throw new RangeError('Column index out of range')},i.checkRowVector=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.columns)throw new RangeError('vector size must be the same as the number of columns');return i},i.checkColumnVector=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.rows)throw new RangeError('vector size must be the same as the number of rows');return i},i.checkIndices=function(e,i,t){var n=i.some((i)=>{return 0>i||i>=e.rows}),o=t.some((i)=>{return 0>i||i>=e.columns});if(n||o)throw new RangeError('Indices are out of range');if('object'!=typeof i||'object'!=typeof t)throw new TypeError('Unexpected type for row/column indices');return Array.isArray(i)||(i=Array.from(i)),Array.isArray(t)||(i=Array.from(t)),{row:i,column:t}},i.checkRange=function(e,i,t,n,o){if(5!==arguments.length)throw new TypeError('Invalid argument type');var s=Array.from(arguments).slice(1).some(function(e){return'number'!=typeof e});if(s)throw new TypeError('Invalid argument type');if(i>t||n>o||0>i||i>=e.rows||0>t||t>=e.rows||0>n||n>=e.columns||0>o||o>=e.columns)throw new RangeError('Submatrix indices are out of range')},i.getRange=function(e,t){for(var n=Array(t-e+1),o=0;oi||i>n)throw new RangeError('Row index out of range')},i.c=function(e,i,t){var n=t?e.columns:e.columns-1;if(0>i||i>n)throw new RangeError('Column index out of range')},i.b=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.columns)throw new RangeError('vector size must be the same as the number of columns');return i},i.d=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.rows)throw new RangeError('vector size must be the same as the number of rows');return i},i.i=function(e,i,t){var n=i.some((i)=>{return 0>i||i>=e.rows}),o=t.some((i)=>{return 0>i||i>=e.columns});if(n||o)throw new RangeError('Indices are out of range');if('object'!=typeof i||'object'!=typeof t)throw new TypeError('Unexpected type for row/column indices');return Array.isArray(i)||(i=Array.from(i)),Array.isArray(t)||(i=Array.from(t)),{row:i,column:t}},i.h=function(e,i,t,n,o){if(5!==arguments.length)throw new TypeError('Invalid argument type');var s=Array.from(arguments).slice(1).some(function(e){return'number'!=typeof e});if(s)throw new TypeError('Invalid argument type');if(i>t||n>o||0>i||i>=e.rows||0>t||t>=e.rows||0>n||n>=e.columns||0>o||o>=e.columns)throw new RangeError('Submatrix indices are out of range')},i.e=function(e){for(var t=n.a.zeros(e.rows,1),o=0;oi||i>n)throw new RangeError('Row index out of range')},i.c=function(e,i,t){var n=t?e.columns:e.columns-1;if(0>i||i>n)throw new RangeError('Column index out of range')},i.b=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.columns)throw new RangeError('vector size must be the same as the number of columns');return i},i.d=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.rows)throw new RangeError('vector size must be the same as the number of rows');return i},i.i=function(e,i,t){var n=i.some((i)=>{return 0>i||i>=e.rows}),o=t.some((i)=>{return 0>i||i>=e.columns});if(n||o)throw new RangeError('Indices are out of range');if('object'!=typeof i||'object'!=typeof t)throw new TypeError('Unexpected type for row/column indices');return Array.isArray(i)||(i=Array.from(i)),Array.isArray(t)||(i=Array.from(t)),{row:i,column:t}},i.h=function(e,i,t,n,o){if(5!==arguments.length)throw new TypeError('Invalid argument type');var s=Array.from(arguments).slice(1).some(function(e){return'number'!=typeof e});if(s)throw new TypeError('Invalid argument type');if(i>t||n>o||0>i||i>=e.rows||0>t||t>=e.rows||0>n||n>=e.columns||0>o||o>=e.columns)throw new RangeError('Submatrix indices are out of range')},i.e=function(e){for(var t=n.a.zeros(e.rows,1),o=0;oi||i>n)throw new RangeError('Row index out of range')},i.c=function(e,i,t){var n=t?e.columns:e.columns-1;if(0>i||i>n)throw new RangeError('Column index out of range')},i.b=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.columns)throw new RangeError('vector size must be the same as the number of columns');return i},i.d=function(e,i){if(i.to1DArray&&(i=i.to1DArray()),i.length!==e.rows)throw new RangeError('vector size must be the same as the number of rows');return i},i.i=function(e,i,t){var n=i.some((i)=>{return 0>i||i>=e.rows}),o=t.some((i)=>{return 0>i||i>=e.columns});if(n||o)throw new RangeError('Indices are out of range');if('object'!=typeof i||'object'!=typeof t)throw new TypeError('Unexpected type for row/column indices');return Array.isArray(i)||(i=Array.from(i)),Array.isArray(t)||(i=Array.from(t)),{row:i,column:t}},i.h=function(e,i,t,n,o){if(5!==arguments.length)throw new TypeError('Invalid argument type');var s=Array.from(arguments).slice(1).some(function(e){return'number'!=typeof e});if(s)throw new TypeError('Invalid argument type');if(i>t||n>o||0>i||i>=e.rows||0>t||t>=e.rows||0>n||n>=e.columns||0>o||o>=e.columns)throw new RangeError('Submatrix indices are out of range')},i.e=function(e){for(var t=n.a.zeros(e.rows,1),o=0;oe)throw new RangeError('Threshold too small');var i=new n;i.children=this.children,i.distance=this.distance,i.index=this.index;for(var t=[i],o=[];0=s.distance?o.push(s):t=t.concat(s.children)}return o},n.prototype.group=function(e){if(!m(e)||1>e)throw new RangeError('Number of groups must be a positive integer');const i=new o(function(e,i){return i.distance-e.distance});for(i.push(this);i.size()i.push(e))}var s=new n;return s.children=i.toArray(),s.distance=this.distance,s},n.prototype.traverse=function(e){function t(e,n){if(n(e),e.children)for(var o=e.children.length-1;0<=o;o--)t(e.children[o],n)}t(this,e)},e.exports=n},function(e,i,t){'use strict';i.a=function(e){function r(e,i){return e-i}function x(e,i){for(var t in i)e=e.replace(new RegExp('%'+t+'%','g'),i[t]);return e}e===void 0&&(e=Object);class w extends e{static get[Symbol.species](){return this}static from1DArray(e,i,t){if(e*i!==t.length)throw new RangeError('Data length does not match given dimensions');for(var n=new this(e,i),o=0;oe&&(e=this.get(t,i));return e}maxIndex(){for(var e=this.get(0,0),t=[0,0],n=0;ne&&(e=this.get(n,i),t[0]=n,t[1]=i);return t}min(){for(var e=this.get(0,0),t=0;tt&&(t=this.get(e,n));return t}maxRowIndex(e){l.a(this,e);for(var t=this.get(e,0),n=[e,0],o=1;ot&&(t=this.get(e,o),n[1]=o);return n}minRow(e){l.a(this,e);for(var t=this.get(e,0),n=1;nt&&(t=this.get(n,e));return t}maxColumnIndex(e){l.c(this,e);for(var t=this.get(0,e),n=[0,e],o=1;ot&&(t=this.get(o,e),n[0]=o);return n}minColumn(e){l.c(this,e);for(var t=this.get(0,e),n=1;n=o||512>=s)return e.mmul(n);1==o%2&&1==s%2?(e=i(e,o+1,s+1),n=i(n,o+1,s+1)):1==o%2?(e=i(e,o+1,s),n=i(n,o+1,s)):1==s%2&&(e=i(e,o,s+1),n=i(n,o,s+1));var r=parseInt(e.rows/2),a=parseInt(e.columns/2),l=e.subMatrix(0,r-1,0,a-1),c=n.subMatrix(0,r-1,0,a-1),m=e.subMatrix(0,r-1,a,e.columns-1),u=n.subMatrix(0,r-1,a,n.columns-1),d=e.subMatrix(r,e.rows-1,0,a-1),g=n.subMatrix(r,n.rows-1,0,a-1),p=e.subMatrix(r,e.rows-1,a,e.columns-1),h=n.subMatrix(r,n.rows-1,a,n.columns-1),j=t(w.add(l,p),w.add(c,h),r,a),k=t(w.add(d,p),c,r,a),x=t(l,w.sub(u,h),r,a),f=t(p,w.sub(g,c),r,a),y=t(w.add(l,m),h,r,a),b=t(w.sub(d,l),w.add(c,u),r,a),v=t(w.sub(m,p),w.add(g,h),r,a),M=w.add(j,f);M.sub(y),M.add(v);var S=w.add(x,y),z=w.add(k,f),R=w.sub(j,k);R.add(x),R.add(b);var V=w.zeros(2*M.rows,2*M.columns);return V=V.setSubMatrix(M,0,0),V=V.setSubMatrix(S,M.rows,0),V=V.setSubMatrix(z,0,M.columns),V=V.setSubMatrix(R,M.rows,M.columns),V.subMatrix(0,o-1,0,s-1)}var n=this.clone(),o=n.rows,s=n.columns,a=e.rows,l=e.columns;s!==a&&console.warn(`Multiplying ${o} x ${s} and ${a} x ${l} matrix: dimensions do not match.`);var m=v(o,a),r=v(s,l);return n=i(n,m,r),e=i(e,m,r),t(n,e,m,r)}scaleRows(e,n){if(e=void 0===e?0:e,n=void 0===n?1:n,e>=n)throw new RangeError('min should be strictly smaller than max');for(var o=this.constructor.empty(this.rows,this.columns),r=0,i;r=n)throw new RangeError('min should be strictly smaller than max');for(var o=this.constructor.empty(this.rows,this.columns),r=0,i;rn||0>t||t>=this.columns||0>n||n>=this.columns)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](e.length,n-t+1),s=0;se[s]||e[s]>=this.rows)throw new RangeError('Row index out of range: '+e[s]);o.set(s,i-t,this.get(e[s],i))}return o}subMatrixColumn(e,t,n){if(void 0===t&&(t=0),void 0===n&&(n=this.rows-1),t>n||0>t||t>=this.rows||0>n||n>=this.rows)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](n-t+1,e.length),s=0;se[s]||e[s]>=this.columns)throw new RangeError('Column index out of range: '+e[s]);o.set(i-t,s,this.get(i,e[s]))}return o}setSubMatrix(e,t,n){e=this.constructor.checkMatrix(e);var o=t+e.rows-1,s=n+e.columns-1;l.h(this,t,o,n,s);for(var r=0;re?1/l[s]:0;return l=this.constructor[Symbol.species].diag(l),r.mmul(l.mmul(n.transposeView()))}}w.prototype.klass='Matrix',w.random=w.rand,w.diagonal=w.diag,w.prototype.diagonal=w.prototype.diag,w.identity=w.eye,w.prototype.negate=w.prototype.neg,w.prototype.tensorProduct=w.prototype.kroneckerProduct,w.prototype.determinant=w.prototype.det;var f=` (function %name%(value) { if (typeof value === 'number') return this.%name%S(value); return this.%name%M(value); }) -`,inplaceOperatorScalar=` +`,y=` (function %name%S(value) { for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { @@ -12,7 +12,363 @@ } return this; }) -`,inplaceOperatorMatrix=` +`,b=` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); + } + } + return this; +}) +`,S=` +(function %name%(matrix, value) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(value); +}) +`,z=` +(function %name%() { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j))); + } + } + return this; +}) +`,R=` +(function %name%(matrix) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(); +}) +`,V=` +(function %name%(%args%) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), %args%)); + } + } + return this; +}) +`,I=` +(function %name%(matrix, %args%) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(%args%); +}) +`,D=` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), value)); + } + } + return this; +}) +`,C=` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); + } + } + return this; +}) +`,P=` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`,A=[['+','add'],['-','sub','subtract'],['*','mul','multiply'],['/','div','divide'],['%','mod','modulus'],['&','and'],['|','or'],['^','xor'],['<<','leftShift'],['>>','signPropagatingRightShift'],['>>>','rightShift','zeroFillRightShift']],L=eval,U;for(var i of A){var _=L(x(f,{name:i[1],op:i[0]})),q=L(x(y,{name:i[1]+'S',op:i[0]})),F=L(x(b,{name:i[1]+'M',op:i[0]})),O=L(x(S,{name:i[1]}));for(U=1;Uu(k[h])&&(h=d);if(h!==i){for(g=0;gi?e[r][i]:r===i?1:0;return s},get upperTriangularMatrix(){for(var e=this.LU,t=e.rows,n=e.columns,s=new o.a(t,n),r=0;ru(i)?(t=i/e,u(e)*S(1+t*t)):0===i?0:(t=e/i,u(i)*S(1+t*t))},i.b=function(e,t,n){for(var o=Array(e),s=0;su(i)?(t=i/e,u(e)*S(1+t*t)):0===i?0:(t=e/i,u(i)*S(1+t*t))},i.getEmpty2DArray=function(e,t){for(var n=Array(e),o=0;oe&&(e=this.get(t,i));return e}maxIndex(){for(var e=this.get(0,0),t=[0,0],n=0;ne&&(e=this.get(n,i),t[0]=n,t[1]=i);return t}min(){for(var e=this.get(0,0),t=0;tt&&(t=this.get(e,n));return t}maxRowIndex(e){l.a(this,e);for(var t=this.get(e,0),n=[e,0],o=1;ot&&(t=this.get(e,o),n[1]=o);return n}minRow(e){l.a(this,e);for(var t=this.get(e,0),n=1;nt&&(t=this.get(n,e));return t}maxColumnIndex(e){l.c(this,e);for(var t=this.get(0,e),n=[0,e],o=1;ot&&(t=this.get(o,e),n[0]=o);return n}minColumn(e){l.c(this,e);for(var t=this.get(0,e),n=1;n=o||512>=s)return e.mmul(n);1==o%2&&1==s%2?(e=i(e,o+1,s+1),n=i(n,o+1,s+1)):1==o%2?(e=i(e,o+1,s),n=i(n,o+1,s)):1==s%2&&(e=i(e,o,s+1),n=i(n,o,s+1));var r=parseInt(e.rows/2),a=parseInt(e.columns/2),l=e.subMatrix(0,r-1,0,a-1),c=n.subMatrix(0,r-1,0,a-1),m=e.subMatrix(0,r-1,a,e.columns-1),u=n.subMatrix(0,r-1,a,n.columns-1),d=e.subMatrix(r,e.rows-1,0,a-1),g=n.subMatrix(r,n.rows-1,0,a-1),p=e.subMatrix(r,e.rows-1,a,e.columns-1),h=n.subMatrix(r,n.rows-1,a,n.columns-1),j=t(w.add(l,p),w.add(c,h),r,a),k=t(w.add(d,p),c,r,a),x=t(l,w.sub(u,h),r,a),f=t(p,w.sub(g,c),r,a),y=t(w.add(l,m),h,r,a),b=t(w.sub(d,l),w.add(c,u),r,a),v=t(w.sub(m,p),w.add(g,h),r,a),M=w.add(j,f);M.sub(y),M.add(v);var S=w.add(x,y),z=w.add(k,f),R=w.sub(j,k);R.add(x),R.add(b);var V=w.zeros(2*M.rows,2*M.columns);return V=V.setSubMatrix(M,0,0),V=V.setSubMatrix(S,M.rows,0),V=V.setSubMatrix(z,0,M.columns),V=V.setSubMatrix(R,M.rows,M.columns),V.subMatrix(0,o-1,0,s-1)}var n=this.clone(),o=n.rows,s=n.columns,a=e.rows,l=e.columns;s!==a&&console.warn(`Multiplying ${o} x ${s} and ${a} x ${l} matrix: dimensions do not match.`);var m=v(o,a),r=v(s,l);return n=i(n,m,r),e=i(e,m,r),t(n,e,m,r)}scaleRows(e,n){if(e=void 0===e?0:e,n=void 0===n?1:n,e>=n)throw new RangeError('min should be strictly smaller than max');for(var o=this.constructor.empty(this.rows,this.columns),r=0,i;r=n)throw new RangeError('min should be strictly smaller than max');for(var o=this.constructor.empty(this.rows,this.columns),r=0,i;rn||0>t||t>=this.columns||0>n||n>=this.columns)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](e.length,n-t+1),s=0;se[s]||e[s]>=this.rows)throw new RangeError('Row index out of range: '+e[s]);o.set(s,i-t,this.get(e[s],i))}return o}subMatrixColumn(e,t,n){if(void 0===t&&(t=0),void 0===n&&(n=this.rows-1),t>n||0>t||t>=this.rows||0>n||n>=this.rows)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](n-t+1,e.length),s=0;se[s]||e[s]>=this.columns)throw new RangeError('Column index out of range: '+e[s]);o.set(i-t,s,this.get(i,e[s]))}return o}setSubMatrix(e,t,n){e=this.constructor.checkMatrix(e);var o=t+e.rows-1,s=n+e.columns-1;l.h(this,t,o,n,s);for(var r=0;re?1/l[s]:0;return l=this.constructor[Symbol.species].diag(l),r.mmul(l.mmul(n.transposeView()))}}w.prototype.klass='Matrix',w.random=w.rand,w.diagonal=w.diag,w.prototype.diagonal=w.prototype.diag,w.identity=w.eye,w.prototype.negate=w.prototype.neg,w.prototype.tensorProduct=w.prototype.kroneckerProduct,w.prototype.determinant=w.prototype.det;var f=` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`,y=` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% value); + } + } + return this; +}) +`,b=` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); + } + } + return this; +}) +`,S=` +(function %name%(matrix, value) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(value); +}) +`,z=` +(function %name%() { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j))); + } + } + return this; +}) +`,R=` +(function %name%(matrix) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(); +}) +`,V=` +(function %name%(%args%) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), %args%)); + } + } + return this; +}) +`,I=` +(function %name%(matrix, %args%) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(%args%); +}) +`,D=` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), value)); + } + } + return this; +}) +`,C=` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); + } + } + return this; +}) +`,P=` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`,A=[['+','add'],['-','sub','subtract'],['*','mul','multiply'],['/','div','divide'],['%','mod','modulus'],['&','and'],['|','or'],['^','xor'],['<<','leftShift'],['>>','signPropagatingRightShift'],['>>>','rightShift','zeroFillRightShift']],L=eval,U;for(var i of A){var _=L(x(f,{name:i[1],op:i[0]})),q=L(x(y,{name:i[1]+'S',op:i[0]})),F=L(x(b,{name:i[1]+'M',op:i[0]})),O=L(x(S,{name:i[1]}));for(U=1;Uu(k[h])&&(h=d);if(h!==i){for(g=0;gi?e[r][i]:r===i?1:0;return s},get upperTriangularMatrix(){for(var e=this.LU,t=e.rows,n=e.columns,s=new o.a(t,n),r=0;ru(i)?(t=i/e,u(e)*S(1+t*t)):0===i?0:(t=e/i,u(i)*S(1+t*t))},i.b=function(e,t,n){for(var o=Array(e),s=0;se&&(e=this.get(t,i));return e}maxIndex(){for(var e=this.get(0,0),t=[0,0],n=0;ne&&(e=this.get(n,i),t[0]=n,t[1]=i);return t}min(){for(var e=this.get(0,0),t=0;tt&&(t=this.get(e,n));return t}maxRowIndex(e){l.a(this,e);for(var t=this.get(e,0),n=[e,0],o=1;ot&&(t=this.get(e,o),n[1]=o);return n}minRow(e){l.a(this,e);for(var t=this.get(e,0),n=1;nt&&(t=this.get(n,e));return t}maxColumnIndex(e){l.c(this,e);for(var t=this.get(0,e),n=[0,e],o=1;ot&&(t=this.get(o,e),n[0]=o);return n}minColumn(e){l.c(this,e);for(var t=this.get(0,e),n=1;n=o||512>=s)return e.mmul(n);1==o%2&&1==s%2?(e=i(e,o+1,s+1),n=i(n,o+1,s+1)):1==o%2?(e=i(e,o+1,s),n=i(n,o+1,s)):1==s%2&&(e=i(e,o,s+1),n=i(n,o,s+1));var r=parseInt(e.rows/2),a=parseInt(e.columns/2),l=e.subMatrix(0,r-1,0,a-1),c=n.subMatrix(0,r-1,0,a-1),m=e.subMatrix(0,r-1,a,e.columns-1),u=n.subMatrix(0,r-1,a,n.columns-1),d=e.subMatrix(r,e.rows-1,0,a-1),g=n.subMatrix(r,n.rows-1,0,a-1),p=e.subMatrix(r,e.rows-1,a,e.columns-1),h=n.subMatrix(r,n.rows-1,a,n.columns-1),j=t(w.add(l,p),w.add(c,h),r,a),k=t(w.add(d,p),c,r,a),x=t(l,w.sub(u,h),r,a),f=t(p,w.sub(g,c),r,a),y=t(w.add(l,m),h,r,a),b=t(w.sub(d,l),w.add(c,u),r,a),v=t(w.sub(m,p),w.add(g,h),r,a),M=w.add(j,f);M.sub(y),M.add(v);var S=w.add(x,y),z=w.add(k,f),R=w.sub(j,k);R.add(x),R.add(b);var V=w.zeros(2*M.rows,2*M.columns);return V=V.setSubMatrix(M,0,0),V=V.setSubMatrix(S,M.rows,0),V=V.setSubMatrix(z,0,M.columns),V=V.setSubMatrix(R,M.rows,M.columns),V.subMatrix(0,o-1,0,s-1)}var n=this.clone(),o=n.rows,s=n.columns,a=e.rows,l=e.columns;s!==a&&console.warn(`Multiplying ${o} x ${s} and ${a} x ${l} matrix: dimensions do not match.`);var m=v(o,a),r=v(s,l);return n=i(n,m,r),e=i(e,m,r),t(n,e,m,r)}scaleRows(e,n){if(e=void 0===e?0:e,n=void 0===n?1:n,e>=n)throw new RangeError('min should be strictly smaller than max');for(var o=this.constructor.empty(this.rows,this.columns),r=0,i;r=n)throw new RangeError('min should be strictly smaller than max');for(var o=this.constructor.empty(this.rows,this.columns),r=0,i;rn||0>t||t>=this.columns||0>n||n>=this.columns)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](e.length,n-t+1),s=0;se[s]||e[s]>=this.rows)throw new RangeError('Row index out of range: '+e[s]);o.set(s,i-t,this.get(e[s],i))}return o}subMatrixColumn(e,t,n){if(void 0===t&&(t=0),void 0===n&&(n=this.rows-1),t>n||0>t||t>=this.rows||0>n||n>=this.rows)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](n-t+1,e.length),s=0;se[s]||e[s]>=this.columns)throw new RangeError('Column index out of range: '+e[s]);o.set(i-t,s,this.get(i,e[s]))}return o}setSubMatrix(e,t,n){e=this.constructor.checkMatrix(e);var o=t+e.rows-1,s=n+e.columns-1;l.h(this,t,o,n,s);for(var r=0;re?1/l[s]:0;return l=this.constructor[Symbol.species].diag(l),r.mmul(l.mmul(n.transposeView()))}}w.prototype.klass='Matrix',w.random=w.rand,w.diagonal=w.diag,w.prototype.diagonal=w.prototype.diag,w.identity=w.eye,w.prototype.negate=w.prototype.neg,w.prototype.tensorProduct=w.prototype.kroneckerProduct,w.prototype.determinant=w.prototype.det;var f=` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`,y=` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% value); + } + } + return this; +}) +`,b=` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); + } + } + return this; +}) +`,S=` +(function %name%(matrix, value) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(value); +}) +`,z=` +(function %name%() { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j))); + } + } + return this; +}) +`,R=` +(function %name%(matrix) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(); +}) +`,V=` +(function %name%(%args%) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), %args%)); + } + } + return this; +}) +`,I=` +(function %name%(matrix, %args%) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(%args%); +}) +`,D=` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), value)); + } + } + return this; +}) +`,C=` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); + } + } + return this; +}) +`,P=` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`,A=[['+','add'],['-','sub','subtract'],['*','mul','multiply'],['/','div','divide'],['%','mod','modulus'],['&','and'],['|','or'],['^','xor'],['<<','leftShift'],['>>','signPropagatingRightShift'],['>>>','rightShift','zeroFillRightShift']],L=eval,U;for(var i of A){var _=L(x(f,{name:i[1],op:i[0]})),q=L(x(y,{name:i[1]+'S',op:i[0]})),F=L(x(b,{name:i[1]+'M',op:i[0]})),O=L(x(S,{name:i[1]}));for(U=1;Uu(k[h])&&(h=d);if(h!==i){for(g=0;gi?e[r][i]:r===i?1:0;return s},get upperTriangularMatrix(){for(var e=this.LU,t=e.rows,n=e.columns,s=new o.a(t,n),r=0;ru(i)?(t=i/e,u(e)*S(1+t*t)):0===i?0:(t=e/i,u(i)*S(1+t*t))},i.b=function(e,t,n){for(var o=Array(e),s=0;se&&(e=this.get(t,i));return e}maxIndex(){for(var e=this.get(0,0),t=[0,0],n=0;ne&&(e=this.get(n,i),t[0]=n,t[1]=i);return t}min(){for(var e=this.get(0,0),t=0;tt&&(t=this.get(e,n));return t}maxRowIndex(e){l.a(this,e);for(var t=this.get(e,0),n=[e,0],o=1;ot&&(t=this.get(e,o),n[1]=o);return n}minRow(e){l.a(this,e);for(var t=this.get(e,0),n=1;nt&&(t=this.get(n,e));return t}maxColumnIndex(e){l.c(this,e);for(var t=this.get(0,e),n=[0,e],o=1;ot&&(t=this.get(o,e),n[0]=o);return n}minColumn(e){l.c(this,e);for(var t=this.get(0,e),n=1;n=o||512>=s)return e.mmul(n);1==o%2&&1==s%2?(e=i(e,o+1,s+1),n=i(n,o+1,s+1)):1==o%2?(e=i(e,o+1,s),n=i(n,o+1,s)):1==s%2&&(e=i(e,o,s+1),n=i(n,o,s+1));var r=parseInt(e.rows/2),a=parseInt(e.columns/2),l=e.subMatrix(0,r-1,0,a-1),c=n.subMatrix(0,r-1,0,a-1),m=e.subMatrix(0,r-1,a,e.columns-1),u=n.subMatrix(0,r-1,a,n.columns-1),d=e.subMatrix(r,e.rows-1,0,a-1),g=n.subMatrix(r,n.rows-1,0,a-1),p=e.subMatrix(r,e.rows-1,a,e.columns-1),h=n.subMatrix(r,n.rows-1,a,n.columns-1),j=t(w.add(l,p),w.add(c,h),r,a),k=t(w.add(d,p),c,r,a),x=t(l,w.sub(u,h),r,a),f=t(p,w.sub(g,c),r,a),y=t(w.add(l,m),h,r,a),b=t(w.sub(d,l),w.add(c,u),r,a),v=t(w.sub(m,p),w.add(g,h),r,a),M=w.add(j,f);M.sub(y),M.add(v);var S=w.add(x,y),z=w.add(k,f),R=w.sub(j,k);R.add(x),R.add(b);var V=w.zeros(2*M.rows,2*M.columns);return V=V.setSubMatrix(M,0,0),V=V.setSubMatrix(S,M.rows,0),V=V.setSubMatrix(z,0,M.columns),V=V.setSubMatrix(R,M.rows,M.columns),V.subMatrix(0,o-1,0,s-1)}var n=this.clone(),o=n.rows,s=n.columns,a=e.rows,l=e.columns;s!==a&&console.warn(`Multiplying ${o} x ${s} and ${a} x ${l} matrix: dimensions do not match.`);var m=v(o,a),r=v(s,l);return n=i(n,m,r),e=i(e,m,r),t(n,e,m,r)}scaleRows(e,n){if(e=void 0===e?0:e,n=void 0===n?1:n,e>=n)throw new RangeError('min should be strictly smaller than max');for(var o=this.constructor.empty(this.rows,this.columns),r=0,i;r=n)throw new RangeError('min should be strictly smaller than max');for(var o=this.constructor.empty(this.rows,this.columns),r=0,i;rn||0>t||t>=this.columns||0>n||n>=this.columns)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](e.length,n-t+1),s=0;se[s]||e[s]>=this.rows)throw new RangeError('Row index out of range: '+e[s]);o.set(s,i-t,this.get(e[s],i))}return o}subMatrixColumn(e,t,n){if(void 0===t&&(t=0),void 0===n&&(n=this.rows-1),t>n||0>t||t>=this.rows||0>n||n>=this.rows)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](n-t+1,e.length),s=0;se[s]||e[s]>=this.columns)throw new RangeError('Column index out of range: '+e[s]);o.set(i-t,s,this.get(i,e[s]))}return o}setSubMatrix(e,t,n){e=this.constructor.checkMatrix(e);var o=t+e.rows-1,s=n+e.columns-1;l.h(this,t,o,n,s);for(var r=0;re?1/l[s]:0;return l=this.constructor[Symbol.species].diag(l),r.mmul(l.mmul(n.transposeView()))}}w.prototype.klass='Matrix',w.random=w.rand,w.diagonal=w.diag,w.prototype.diagonal=w.prototype.diag,w.identity=w.eye,w.prototype.negate=w.prototype.neg,w.prototype.tensorProduct=w.prototype.kroneckerProduct,w.prototype.determinant=w.prototype.det;var f=` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`,y=` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% value); + } + } + return this; +}) +`,b=` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% matrix.get(i, j)); + } + } + return this; +}) +`,S=` +(function %name%(matrix, value) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(value); +}) +`,z=` +(function %name%() { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j))); + } + } + return this; +}) +`,R=` +(function %name%(matrix) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(); +}) +`,V=` +(function %name%(%args%) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), %args%)); + } + } + return this; +}) +`,I=` +(function %name%(matrix, %args%) { + var newMatrix = new this[Symbol.species](matrix); + return newMatrix.%name%(%args%); +}) +`,D=` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), value)); + } + } + return this; +}) +`,C=` +(function %name%M(matrix) { + matrix = this.constructor.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, %method%(this.get(i, j), matrix.get(i, j))); + } + } + return this; +}) +`,P=` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`,A=[['+','add'],['-','sub','subtract'],['*','mul','multiply'],['/','div','divide'],['%','mod','modulus'],['&','and'],['|','or'],['^','xor'],['<<','leftShift'],['>>','signPropagatingRightShift'],['>>>','rightShift','zeroFillRightShift']],L=eval,U;for(var i of A){var _=L(x(f,{name:i[1],op:i[0]})),q=L(x(y,{name:i[1]+'S',op:i[0]})),F=L(x(b,{name:i[1]+'M',op:i[0]})),O=L(x(S,{name:i[1]}));for(U=1;Uu(k[h])&&(h=d);if(h!==i){for(g=0;gi?e[r][i]:r===i?1:0;return s},get upperTriangularMatrix(){for(var e=this.LU,t=e.rows,n=e.columns,s=new o.a(t,n),r=0;ru(i)?(t=i/e,u(e)*S(1+t*t)):0===i?0:(t=e/i,u(i)*S(1+t*t))},i.b=function(e,t,n){for(var o=Array(e),s=0;sn||n>=e.length)throw new RangeError('invalid lower bound');if(void 0===o)o=e.length-1;else if(o|=0,o=e.length)throw new RangeError('invalid upper bound');for(;n<=o;)if(s=n+(o-n>>1),r=+t(e[s],i,s,e),0>r)n=s+1;else if(0Array.from({length:n}));for(let s=0;si)throw new RangeError(`initial capacity must not be less than zero: ${i}`);const t=e.minLoadFactor===void 0?1/6:e.minLoadFactor,n=e.maxLoadFactor===void 0?2/3:e.maxLoadFactor;if(0>t||1<=t)throw new RangeError(`invalid minLoadFactor: ${t}`);if(0>=n||1<=n)throw new RangeError(`invalid maxLoadFactor: ${n}`);if(t>=n)throw new RangeError(`minLoadFactor (${t}) must be smaller than maxLoadFactor (${n})`);let s=i;s=0|s/n,s=c(s),0===s&&(s=1),this.table=a(s,0),this.values=a(s,0),this.state=a(s,0),this.minLoadFactor=t,this.maxLoadFactor=s===m?1:n,this.distinct=0,this.freeEntries=s,this.lowWaterMark=0,this.highWaterMark=o(s,this.maxLoadFactor)}clone(){return new p(this)}get size(){return this.distinct}get(e){const t=this.indexOfKey(e);return 0>t?0:this.values[t]}set(e,t){let n=this.indexOfInsertion(e);if(0>n)return n=-n-1,this.values[n]=t,!1;if(this.distinct>this.highWaterMark){const i=s(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);return this.rehash(i),this.set(e,t)}if(this.table[n]=e,this.values[n]=t,this.state[n]===u&&this.freeEntries--,this.state[n]=d,this.distinct++,1>this.freeEntries){const e=s(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);this.rehash(e)}return!0}remove(e,t){const n=this.indexOfKey(e);return!(0>n)&&(this.state[n]=g,this.distinct--,t||this.maybeShrinkCapacity(),!0)}delete(e,t){const n=this.indexOfKey(e);return!(0>n)&&(this.state[n]=u,this.distinct--,t||this.maybeShrinkCapacity(),!0)}maybeShrinkCapacity(){if(this.distinctr&&(r+=o);return n[r]===u?-1:r}containsValue(e){return 0<=this.indexOfValue(e)}indexOfValue(e){const t=this.values,n=this.state;for(var o=0;or&&(r+=o);if(n[r]===g){const i=r;for(;n[r]!==u&&(n[r]===g||t[r]!==e);)r-=a,0>r&&(r+=o);n[r]===u&&(r=i)}return n[r]===d?-r-1:r}ensureCapacity(e){if(this.table.lengthn||t.size[1]>n)throw new RangeError('expanded value should not be bigger than the data length');for(r=0;rt[a][i]?e[a][i]:t[a][i];return r},solve:function(e,i){return e.solve(i)},inv:function(e){return'number'==typeof e?1/e:e.inverse()},sqrt:function(e){if('number'==typeof e)return S(e);for(var t=e.rows,o=e.columns,s=new n(t,o),r=0;ri.activation(t,e.activationParam):i.activation,r=1i.derivate(t,e.activationParam):i.derivate;this.activationFunction=function(e,i){this[e][i]=o(this[e][i])},this.derivate=function(e,i){this[e][i]=r(this[e][i])},e.model?(this.W=n.checkMatrix(e.W),this.b=n.checkMatrix(e.b)):(this.W=n.rand(this.inputSize,this.outputSize),this.b=n.zeros(1,this.outputSize),this.W.apply(function(t,i){this[t][i]/=S(e.inputSize)}))}forward(e){var i=e.mmul(this.W).addRowVector(this.b);return i.apply(this.activationFunction),this.a=i.clone(),i}backpropagation(e,i){this.dW=i.transposeView().mmul(e),this.db=o.sumCol(e);var t=i.clone();return e.mmul(this.W.transposeView()).mul(t.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(e){if('Layer'!==e.model)throw new RangeError('the current model is not a Layer model');return new r(e)}}e.exports=r},function(e){'use strict';function i(e){return 1/(1+l(-e))}function t(e,i){return 0>e?i*(l(e)-1):e}var n=Math.cos,r=Math.sin;const a={tanh:{activation:o,derivate:(e)=>1-e*e},identity:{activation:(e)=>e,derivate:()=>1},logistic:{activation:i,derivate:(e)=>i(e)*(1-i(e))},arctan:{activation:Math.atan,derivate:(e)=>1/(e*e+1)},softsign:{activation:(e)=>e/(1+u(e)),derivate:(e)=>1/((1+u(e))*(1+u(e)))},relu:{activation:(e)=>0>e?0:e,derivate:(e)=>0>e?0:1},softplus:{activation:(e)=>s(1+l(e)),derivate:(e)=>1/(1+l(-e))},bent:{activation:(e)=>(S(e*e+1)-1)/2+e,derivate:(e)=>e/(2*S(e*e+1))+1},sinusoid:{activation:r,derivate:n},sinc:{activation:(e)=>0===e?1:r(e)/e,derivate:(e)=>0===e?0:n(e)/e-r(e)/(e*e)},gaussian:{activation:(e)=>l(-(e*e)),derivate:(e)=>-2*e*l(-(e*e))},"parametric-relu":{activation:(e,i)=>0>e?i*e:e,derivate:(e,i)=>0>e?i:1},"exponential-elu":{activation:t,derivate:(e,i)=>0>e?t(e,i)+i:1},"soft-exponential":{activation:function(e,i){return 0>i?-s(1-i*(e+i))/i:0i?1/(1-i*(i+e)):l(i*e)}}};e.exports=a},function(e,i,t){'use strict';var n=t(0);e.exports={dictOutputs:function(e){for(var t={},n={},o=e.length,s=0,r=0;ra[d][d]&&(p=-p),u=d;uD[j][j]&&(C[j]=-C[j]),U=j;UV[j+1]&&(V[j]=0-V[j]),U=j+1;U=j&&_!==j;_--)if(p=(_===k?0:u(V[_]))+(_===j+1?0:u(V[_-1])),u(C[_])<=K*p){C[_]=0;break}_===j?N=3:_===k-1?N=1:(N=2,j=_)}switch(j++,N){case 1:{for(q=V[k-2],V[k-2]=0,i=k-2;i>=j;i--)if(p=o.i(d.a)(C[i],q),f=C[i]/p,F=q/p,C[i]=p,i!==j&&(q=-F*V[i-1],V[i-1]=f*V[i-1]),z)for(U=0;UJ&&(c=-c),c=b/(J+c)),q=(B+W)*(B-W)+c,Y=B*Q,i=j;i=C[j]&&(C[j]=0>C[j]?-C[j]:0,z))for(U=0;U<=g;U++)P[U][j]=-P[U][j];for(;j=C[j+1]);){if(p=C[j],C[j]=C[j+1],C[j+1]=p,z&&je&&t++;return t},get diagonal(){return this.s},get threshold(){return 2.220446049250313e-16/2*v(this.m,this.n)*this.s[0]},get leftSingularVectors(){return l.a.isMatrix(this.U)||(this.U=new l.a(this.U)),this.U},get rightSingularVectors(){return l.a.isMatrix(this.V)||(this.V=new l.a(this.V)),this.V},get diagonalMatrix(){return l.a.diag(this.s)},solve:function(t){var n=this.threshold,e=this.s.length,o=l.a.zeros(e,e),s;for(s=0;sn?t[r][i]/this.s[i]:0;var a=this.U,c=a.length,m=a[0].length,d=new l.a(e,c),g,p;for(r=0;ro)return!1;return!0}},function(e,i,t){'use strict';function n(e){function t(e,i){if(e.rows!==i.rows||e.columns!==i.columns)throw new RangeError('Matrices dimensions must be equal')}function n(e,i){return e-i}function x(e,i){for(var t in i)e=e.replace(new RegExp('%'+t+'%','g'),i[t]);return e}e===void 0&&(e=Object);class w extends e{static get[Symbol.species](){return this}static from1DArray(e,i,t){if(e*i!==t.length)throw new RangeError('Data length does not match given dimensions');for(var n=new this(e,i),o=0;oe&&(e=this.get(t,i));return e}maxIndex(){for(var e=this.get(0,0),t=[0,0],n=0;ne&&(e=this.get(n,i),t[0]=n,t[1]=i);return t}min(){for(var e=this.get(0,0),t=0;tt&&(t=this.get(e,n));return t}maxRowIndex(e){l.checkRowIndex(this,e);for(var t=this.get(e,0),n=[e,0],o=1;ot&&(t=this.get(e,o),n[1]=o);return n}minRow(e){l.checkRowIndex(this,e);for(var t=this.get(e,0),n=1;nt&&(t=this.get(n,e));return t}maxColumnIndex(e){l.checkColumnIndex(this,e);for(var t=this.get(0,e),n=[0,e],o=1;ot&&(t=this.get(o,e),n[0]=o);return n}minColumn(e){l.checkColumnIndex(this,e);for(var t=this.get(0,e),n=1;n=o||512>=s)return e.mmul(n);1==o%2&&1==s%2?(e=i(e,o+1,s+1),n=i(n,o+1,s+1)):1==o%2?(e=i(e,o+1,s),n=i(n,o+1,s)):1==s%2&&(e=i(e,o,s+1),n=i(n,o,s+1));var r=parseInt(e.rows/2),a=parseInt(e.columns/2),l=e.subMatrix(0,r-1,0,a-1),c=n.subMatrix(0,r-1,0,a-1),m=e.subMatrix(0,r-1,a,e.columns-1),u=n.subMatrix(0,r-1,a,n.columns-1),d=e.subMatrix(r,e.rows-1,0,a-1),g=n.subMatrix(r,n.rows-1,0,a-1),p=e.subMatrix(r,e.rows-1,a,e.columns-1),h=n.subMatrix(r,n.rows-1,a,n.columns-1),j=t(w.add(l,p),w.add(c,h),r,a),k=t(w.add(d,p),c,r,a),x=t(l,w.sub(u,h),r,a),f=t(p,w.sub(g,c),r,a),y=t(w.add(l,m),h,r,a),b=t(w.sub(d,l),w.add(c,u),r,a),v=t(w.sub(m,p),w.add(g,h),r,a),M=w.add(j,f);M.sub(y),M.add(v);var S=w.add(x,y),z=w.add(k,f),R=w.sub(j,k);R.add(x),R.add(b);var V=w.zeros(2*M.rows,2*M.columns);return V=V.setSubMatrix(M,0,0),V=V.setSubMatrix(S,M.rows,0),V=V.setSubMatrix(z,0,M.columns),V=V.setSubMatrix(R,M.rows,M.columns),V.subMatrix(0,o-1,0,s-1)}var n=this.clone(),o=n.rows,s=n.columns,a=e.rows,l=e.columns;s!==a&&console.warn(`Multiplying ${o} x ${s} and ${a} x ${l} matrix: dimensions do not match.`);var m=v(o,a),r=v(s,l);return n=i(n,m,r),e=i(e,m,r),t(n,e,m,r)}scaleRows(e,t){if(e=void 0===e?0:e,t=void 0===t?1:t,e>=t)throw new RangeError('min should be strictly smaller than max');for(var n=this.constructor.empty(this.rows,this.columns),o=0,i;o=t)throw new RangeError('min should be strictly smaller than max');for(var n=this.constructor.empty(this.rows,this.columns),o=0,i;on||0>t||t>=this.columns||0>n||n>=this.columns)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](e.length,n-t+1),s=0;se[s]||e[s]>=this.rows)throw new RangeError('Row index out of range: '+e[s]);o.set(s,i-t,this.get(e[s],i))}return o}subMatrixColumn(e,t,n){if(void 0===t&&(t=0),void 0===n&&(n=this.rows-1),t>n||0>t||t>=this.rows||0>n||n>=this.rows)throw new RangeError('Argument out of range');for(var o=new this.constructor[Symbol.species](n-t+1,e.length),s=0;se[s]||e[s]>=this.columns)throw new RangeError('Column index out of range: '+e[s]);o.set(i-t,s,this.get(i,e[s]))}return o}setSubMatrix(e,t,n){e=this.constructor.checkMatrix(e);var o=t+e.rows-1,s=n+e.columns-1;l.checkRange(this,t,o,n,s);for(var r=0;re?1/l[s]:0;return l=this.constructor[Symbol.species].diag(l),o.mmul(l.mmul(n.transposeView()))}}w.prototype.klass='Matrix',w.random=w.rand,w.diagonal=w.diag,w.prototype.diagonal=w.prototype.diag,w.identity=w.eye,w.prototype.negate=w.prototype.neg,w.prototype.tensorProduct=w.prototype.kroneckerProduct,w.prototype.determinant=w.prototype.det;var f=` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`,y=` +(function %name%S(value) { + for (var i = 0; i < this.rows; i++) { + for (var j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) %op% value); + } + } + return this; +}) +`,b=` (function %name%M(matrix) { matrix = this.constructor.checkMatrix(matrix); checkDimensions(this, matrix); @@ -23,12 +379,12 @@ } return this; }) -`,staticOperator=` +`,S=` (function %name%(matrix, value) { var newMatrix = new this[Symbol.species](matrix); return newMatrix.%name%(value); }) -`,inplaceMethod=` +`,z=` (function %name%() { for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { @@ -37,12 +393,12 @@ } return this; }) -`,staticMethod=` +`,R=` (function %name%(matrix) { var newMatrix = new this[Symbol.species](matrix); return newMatrix.%name%(); }) -`,inplaceMethodWithArgs=` +`,V=` (function %name%(%args%) { for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { @@ -51,12 +407,12 @@ } return this; }) -`,staticMethodWithArgs=` +`,I=` (function %name%(matrix, %args%) { var newMatrix = new this[Symbol.species](matrix); return newMatrix.%name%(%args%); }) -`,inplaceMethodWithOneArgScalar=` +`,D=` (function %name%S(value) { for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { @@ -65,7 +421,7 @@ } return this; }) -`,inplaceMethodWithOneArgMatrix=` +`,C=` (function %name%M(matrix) { matrix = this.constructor.checkMatrix(matrix); checkDimensions(this, matrix); @@ -76,22 +432,22 @@ } return this; }) -`,inplaceMethodWithOneArg=` +`,P=` (function %name%(value) { if (typeof value === 'number') return this.%name%S(value); return this.%name%M(value); }) -`,staticMethodWithOneArg=staticMethodWithArgs,operators=[['+','add'],['-','sub','subtract'],['*','mul','multiply'],['/','div','divide'],['%','mod','modulus'],['&','and'],['|','or'],['^','xor'],['<<','leftShift'],['>>','signPropagatingRightShift'],['>>>','rightShift','zeroFillRightShift']],i;for(var operator of operators){var inplaceOp=eval(fillTemplateFunction(inplaceOperator,{name:operator[1],op:operator[0]})),inplaceOpS=eval(fillTemplateFunction(inplaceOperatorScalar,{name:operator[1]+'S',op:operator[0]})),inplaceOpM=eval(fillTemplateFunction(inplaceOperatorMatrix,{name:operator[1]+'M',op:operator[0]})),staticOp=eval(fillTemplateFunction(staticOperator,{name:operator[1]}));for(i=1;iMath.abs(me[ae])&&(ae=ne);if(ae!==oe){for(se=0;seie?G[te][ie]:te===ie?1:0;return ee},get upperTriangularMatrix(){for(var G=this.LU,Z=G.rows,$=G.columns,ee=new E.Matrix(Z,$),te=0;teoe&&(oe=le,se=ae)}return se}function G(te,ie,ne,oe){var te=te-ie;return Math.log(ne*Math.exp(te*te/oe))}function Z(te,ie){for(var ne=te.columns,oe=0,se=Array(100),ae=0;aeE&&(E=G[$]);return E},R.min=function(G){for(var E=Infinity,Z=G.length,$=0;$$&&($=G[te]);return{min:Z,max:$}},R.arithmeticMean=function(G){for(var Z=0,$=G.length,ee=0;ee<$;ee++)Z+=G[ee];return Z/$},R.mean=R.arithmeticMean,R.geometricMean=function(G){for(var Z=1,$=G.length,ee=0;ee<$;ee++)Z*=G[ee];return Math.pow(Z,1/$)},R.logMean=function(G){for(var Z=0,$=G.length,ee=0;ee<$;ee++)Z+=Math.log(G[ee]);return Z/$},R.grandMean=function(G,Z){for(var $=0,ee=0,te=G.length,ie=0;ie$)throw new RangeError('sum of values is negative');return Z/$},R.median=function(G,Z){Z===void 0&&(Z=!1),Z||(G=G.slice().sort(O));var $=G.length,ee=Math.floor($/2);return 0==$%2?0.5*(G[ee-1]+G[ee]):G[ee]},R.variance=function(G,Z){Z===void 0&&(Z=!0);for(var $=R.mean(G),ee=0,te=G.length,ie=0,ne;ieoe&&(oe=$[ee],se=ee);return te[se]},R.covariance=function(G,Z,$){'undefined'==typeof $&&($=!0);var ee=R.mean(G),te=R.mean(Z);if(G.length!==Z.length)throw'Vectors do not have the same dimensions';for(var ie=0,ne=G.length,oe=0;oe>>0).toString(2),ce+='00000000000000000000000000000000'.substr(me.length)+me;return ce}var le=D(68);I.exports={count:function(de){for(var ce=0,ue=0;ue>8]+le[255&de[ue]>>16]+le[255&de[ue]>>24];return ce},and:function(de,ce){for(var ue=Array(de.length),me=0;me>5]&1<<31-ce%32)},setBit:function(de,ce,ue){var me=ce>>5,ge=1<<31-ce%32;return de[me]=ue?ge|de[me]:~ge&de[me],de},toBinaryString:ie,parseBinaryString:function(de){for(var ce=de.length/32,ue=Array(ce),me=0;me>>0).toString(16),ce+='00000000'.substr(me.length)+me;return ce},parseHexString:function(de){for(var ce=de.length/8,ue=Array(ce),me=0;mege;ge+=4)ue+=' '+ce.substr(32*me+ge,4);meArray(ne).fill(0))}function G(ie){var ne=new Set;for(let oe=0;oeArray.from({length:Z}));for(let ee=0;ee=oe||oe>ne.length||!Number.isInteger(oe))throw new Error('K should be a positive integer bigger than the number of points');var ae;if(!Array.isArray(se.initialization))switch(se.initialization){case'random':ae=$.random(ne,oe);break;case'mostDistant':ae=$.mostDistant(ne,oe,Z.calculateDistanceMatrix(ne,se.distanceFunction));break;default:throw new Error('Unknown initialization method: "'+se.initialization+'"');}else if(se.initialization.length!==oe)throw new Error('The initial centers should have the same length as K');else ae=se.initialization;0===se.maxIterations&&(se.maxIterations=Number.MAX_VALUE);var le=Array(ne.length);if(se.withIterations)return E(ae,ne,le,oe,se);for(var de=!1,ce=0,ue;!de&&cepe[0].rows)return null;var he=pe[0],xe=pe[1],fe=pe[2],ye=he.rows,ke=[ye/Math.sqrt(xe.dot(xe))],ge=Object.create(ge.LMOptions||[3,100,0.001,0.001,0.001,0.01,0.01,11,9,1]),be=Math.abs(he[0][0]-he[1][0]),ve=new ce([[-be/1e4],[-0.001],[-be/1e4]]),Me=new ce([[me.x],[1],[me.width]]),ze=new ce([[me.x-be],[0.75],[me.width/4]]),Se=new ce([[me.x+be],[1.25],[4*me.width]]),qe=le.optimize(G,Me,he,xe,ke,ve,ze,Se,[],ge);return qe=qe.p,[qe[0],[qe[1][0]*fe],qe[2]]}function ee(ue,me,ge){ge=ge||{};var pe=se(ue,ge.percentage||0);if(null===pe||3>pe[0].rows)return null;var he=pe[0],xe=pe[1],fe=pe[2],ye=he.rows,ke=[ye/Math.sqrt(xe.dot(xe))],ge=Object.create(ge.LMOptions||[3,100,0.001,0.001,0.001,0.01,0.01,11,9,1]),be=Math.abs(he[0][0]-he[1][0]),ve=new ce([[-be/1e4],[-0.001],[-be/1e4]]),ve=new ce([[-Math.abs(he[0][0]-he[1][0])/1e3],[-0.001],[-me.width/1e3]]),Me=new ce([[me.x],[1],[me.width]]),ze=new ce([[me.x-be],[0.75],[me.width/4]]),Se=new ce([[me.x+be],[1.25],[4*me.width]]),qe=le.optimize(Z,Me,he,xe,ke,ve,ze,Se,[],ge);return qe=qe.p,[qe[0],[qe[1][0]*fe],qe[2]]}function se(ue,me){var ge=ue.length,pe=null,he=null,xe,fe,ye=0,je;if(2==ge){var we=ue[0].length;if(pe=Array(we),he=Array(we),xe=ue[0],fe=ue[1],'number'==typeof xe[0])for(je=0;jeye&&(ye=fe[je]);else if('object'==typeof xe[0])for(je=0;jeye&&(ye=fe[je][0])}else{var we=ge;for(pe=Array(we),he=Array(we),je=0;jeye&&(ye=he[je])}for(je=0;jepe[0].rows)return null;var he=pe[0],xe=pe[1],fe=pe[2],ye=he.rows,je,ke=[ye/de.sqrt(xe.dot(xe))],ge=Object.create(ge||[3,100,0.001,0.001,0.001,0.01,0.01,11,9,1]),be=me.length,ve=new ce(3*be,1),Me=new ce(3*be,1),ze=new ce(3*be,1),Se=new ce(3*be,1),qe=Math.abs(he[0][0]-he[1][0]);for(je=0;jepe[0].rows)return null;var he=pe[0],xe=pe[1],fe=pe[2],ye=he.rows,je,ke=new ce(ye,1),we=ye/de.sqrt(xe.dot(xe));for(je=0;jepe[0].rows)return null;for(var he=pe[0],xe=pe[1],fe=pe[2],ye=0,je=he.length,ve=[],ze=0,ke,we,be,fe,Me;zepe[0].rows)return null;for(var he=pe[0],xe=pe[1],fe=pe[2],ye=0,je=he.length,ve=[],ze=0,ke,we,be,fe,Me;zene[0].length,se){ne=this._adjust(ne,oe);const de=ne.transposeView().mmul(ne).div(ne.rows-1);this._computeFromCovarianceMatrix(de)}else{ne=this._adjust(ne,oe);var ae=new G(ne,{computeLeftSingularVectors:!1,computeRightSingularVectors:!0,autoTranspose:!0});this.U=ae.rightSingularVectors;const de=ae.diagonal,ce=Array(de.length);for(var le=0;lese/ne)}getCumulativeVariance(){for(var ne=this.getExplainedVariance(),oe=1;oeMath.sqrt(ne))}getLoadings(){return this.U.transpose()}toJSON(){return{name:'PCA',center:this.center,scale:this.scale,means:this.means,stdevs:this.stdevs,U:this.U,S:this.S}}_adjust(ne,oe){if(this.center=!!oe.center,this.scale=!!oe.scale,ne=new O(ne),this.center){const ae=$(ne),le=this.scale?ee(ne,ae,!0):null;if(this.means=ae,ne.subRowVector(ae),this.scale){for(var se=0;seee||ee!==te)throw new Error('When "all" option is false, the prediction matrix must be square and have at least 3 columns');for(var oe=0;oeke.pred-we.pred):ne.sort((ke,we)=>we.pred-ke.pred);const ae=this.cutoffs=[ie?Number.MIN_VALUE:Number.MAX_VALUE],le=this.fp=[0],de=this.tp=[0];for(var ce=0,ue=0,me=ne[0].pred,ge=0,pe=0,oe=0;oe=se)for(var le=oe-se+1;le<=oe;le++)ae*=le;return ae}function $(oe,se,ae,le,de){for(var ce=0,ue=0;ue<=le;ue++)ce+=(2*ue+1)*(Z(2*ae,ue)/Z(2*ae+ue+1,ue+1))*G(oe,ae,ue,0)*G(se,ae,ue,de);return ce}function ee(oe,se,ae){for(var le=Array(oe),de=Math.floor(oe/2),ce=-de;ce<=de;ce++){le[ce+de]=Array(oe);for(var ue=-de;ue<=de;ue++)le[ce+de][ue+de]=$(ue,ce,de,se,ae)}return le}var te=D(9),ie=D(157),ne={windowSize:9,derivative:0,polynomial:3};I.exports=function(oe,se,ae){if(ae=te({},ne,ae),0==ae.windowSize%2||5>ae.windowSize||!Number.isInteger(ae.windowSize))throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');if(ae.windowSize>oe.length)throw new RangeError('Window size is higher than the data length '+ae.windowSize+'>'+oe.length);if(0>ae.derivative||!Number.isInteger(ae.derivative))throw new RangeError('Derivative should be a positive integer');if(1>ae.polynomial||!Number.isInteger(ae.polynomial))throw new RangeError('Polynomial should be a positive integer');6<=ae.polynomial&&console.warn('You should not use polynomial grade higher than 5 if you are not sure that your data arises from such a model. Possible polynomial oscillation problems');var le=ae.windowSize,de=Math.floor(le/2),ce=oe.length,ue=Array(ce),me=ee(le,ae.polynomial,ae.derivative),ge=0,pe=!0;'[object Array]'===Object.prototype.toString.call(se)?pe=!1:ge=Math.pow(se,ae.derivative);for(var he=0;heie.windowSize||!Number.isInteger(ie.windowSize))throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');if(0>ie.derivative||!Number.isInteger(ie.derivative))throw new RangeError('Derivative should be a positive integer');if(1>ie.polynomial||!Number.isInteger(ie.polynomial))throw new RangeError('Polynomial should be a positive integer');var se=Math.floor(ie.windowSize/2),ne,oe;'pre'===ie.pad&&(ee=G(ee,{size:se,value:ie.padValue}));var ae=Array(ee.length-2*se);if(5===ie.windowSize&&2===ie.polynomial&&(1===ie.derivative||2===ie.derivative))1===ie.derivative?(ne=[-2,-1,0,1,2],oe=10):(ne=[2,-1,-2,-1,2],oe=7);else{for(var le=E.ones(ie.windowSize,ie.polynomial+1),de=-(ie.windowSize-1)/2,ce=0;ceE?le+=this.x:E>=this.x&&(le-=this.x),G=se;G<=ae;G++){var de=G;0>G?de+=this.y:G>=this.y&&(de-=this.y),Z=ee[this.distanceMethod](this.nodes[le][de]),Z{return this.get(O,D)===E?E:(R=!1,!1)}),R}get cardinality(){return this.elements.size}get size(){return this.rows*this.columns}get(R,D){return this.elements.get(R*this.columns+D)}set(R,D,O){return this.threshold&&Math.abs(O){return R.forEachNonZero((ee,te,ie)=>{return Z===ee&&E.set(G,te,E.get(G,te)+$*ie),ie}),$}),E}kroneckerProduct(R){const D=this.rows,O=this.columns,E=R.rows,G=R.columns,Z=new I(D*E,O*G,{initialCapacity:this.cardinality*R.cardinality});return this.forEachNonZero(($,ee,te)=>{return R.forEachNonZero((ie,ne,oe)=>{return Z.set(E*$+ie,G*ee+ne,te*oe),oe}),te}),Z}forEachNonZero(R){return this.elements.forEachPair((D,O)=>{const E=0|D/this.columns,G=D%this.columns;let Z=R(E,G,O);return!1!==Z&&(this.threshold&&Math.abs(Z){return D[G]=Z,O[G]=$,E[G]=ee,G++,ee}),{rows:D,columns:O,values:E}}setThreshold(R){return 0!==R&&R!==this.threshold&&(this.threshold=R,this.forEachNonZero((D,O,E)=>E)),this}}I.prototype.klass='Matrix',I.identity=I.eye,I.prototype.tensorProduct=I.prototype.kroneckerProduct,module.exports=I;var inplaceOperator=` +`,A=I,L=[['+','add'],['-','sub','subtract'],['*','mul','multiply'],['/','div','divide'],['%','mod','modulus'],['&','and'],['|','or'],['^','xor'],['<<','leftShift'],['>>','signPropagatingRightShift'],['>>>','rightShift','zeroFillRightShift']],U;for(var i of L){var _=eval(x(f,{name:i[1],op:i[0]})),q=eval(x(y,{name:i[1]+'S',op:i[0]})),F=eval(x(b,{name:i[1]+'M',op:i[0]})),O=eval(x(S,{name:i[1]}));for(U=1;Uu(k[h])&&(h=d);if(h!==i){for(g=0;gi?e[r][i]:r===i?1:0;return s},get upperTriangularMatrix(){for(var e=this.LU,t=e.rows,n=e.columns,s=new o.Matrix(t,n),r=0;rD[j][j]&&(C[j]=-C[j]),U=j;UV[j+1]&&(V[j]=0-V[j]),U=j+1;U=j&&_!==j;_--)if(p=(_===k?0:u(V[_]))+(_===j+1?0:u(V[_-1])),u(C[_])<=K*p){C[_]=0;break}_===j?N=3:_===k-1?N=1:(N=2,j=_)}switch(j++,N){case 1:{for(q=V[k-2],V[k-2]=0,i=k-2;i>=j;i--)if(p=l(C[i],q),f=C[i]/p,F=q/p,C[i]=p,i!==j&&(q=-F*V[i-1],V[i-1]=f*V[i-1]),z)for(U=0;UJ&&(c=-c),c=b/(J+c)),q=(B+W)*(B-W)+c,Y=B*Q,i=j;i=C[j]&&(C[j]=0>C[j]?-C[j]:0,z))for(U=0;U<=g;U++)P[U][j]=-P[U][j];for(;j=C[j+1]);){if(p=C[j],C[j]=C[j+1],C[j+1]=p,z&&je&&t++;return t},get diagonal(){return this.s},get threshold(){return 2.220446049250313e-16/2*v(this.m,this.n)*this.s[0]},get leftSingularVectors(){return r.Matrix.isMatrix(this.U)||(this.U=new r.Matrix(this.U)),this.U},get rightSingularVectors(){return r.Matrix.isMatrix(this.V)||(this.V=new r.Matrix(this.V)),this.V},get diagonalMatrix(){return r.Matrix.diag(this.s)},solve:function(t){var n=this.threshold,e=this.s.length,o=r.Matrix.zeros(e,e),s;for(s=0;sn?t[a][i]/this.s[i]:0;var l=this.U,c=l.length,m=l[0].length,d=new r.Matrix(e,c),g,p;for(a=0;ao&&(o=i,s=a)}return s}function r(e,i,t,n){var e=e-i;return s(t*l(e*e/n))}function a(e,t){for(var n=e.columns,o=0,s=Array(100),r=0;ra[d][d]&&(p=-p),u=d;uD[j][j]&&(C[j]=-C[j]),U=j;UV[j+1]&&(V[j]=0-V[j]),U=j+1;U=j&&_!==j;_--)if(p=(_===k?0:u(V[_]))+(_===j+1?0:u(V[_-1])),u(C[_])<=K*p){C[_]=0;break}_===j?N=3:_===k-1?N=1:(N=2,j=_)}switch(j++,N){case 1:{for(q=V[k-2],V[k-2]=0,i=k-2;i>=j;i--)if(p=o.i(d.a)(C[i],q),f=C[i]/p,F=q/p,C[i]=p,i!==j&&(q=-F*V[i-1],V[i-1]=f*V[i-1]),z)for(U=0;UJ&&(c=-c),c=b/(J+c)),q=(B+W)*(B-W)+c,Y=B*Q,i=j;i=C[j]&&(C[j]=0>C[j]?-C[j]:0,z))for(U=0;U<=g;U++)P[U][j]=-P[U][j];for(;j=C[j+1]);){if(p=C[j],C[j]=C[j+1],C[j+1]=p,z&&je&&t++;return t},get diagonal(){return this.s},get threshold(){return 2.220446049250313e-16/2*v(this.m,this.n)*this.s[0]},get leftSingularVectors(){return l.a.isMatrix(this.U)||(this.U=new l.a(this.U)),this.U},get rightSingularVectors(){return l.a.isMatrix(this.V)||(this.V=new l.a(this.V)),this.V},get diagonalMatrix(){return l.a.diag(this.s)},solve:function(t){var n=this.threshold,e=this.s.length,o=l.a.zeros(e,e),s;for(s=0;sn?t[r][i]/this.s[i]:0;var a=this.U,c=a.length,m=a[0].length,d=new l.a(e,c),g,p;for(r=0;ra[d][d]&&(p=-p),u=d;uD[j][j]&&(C[j]=-C[j]),U=j;UV[j+1]&&(V[j]=0-V[j]),U=j+1;U=j&&_!==j;_--)if(p=(_===k?0:u(V[_]))+(_===j+1?0:u(V[_-1])),u(C[_])<=K*p){C[_]=0;break}_===j?N=3:_===k-1?N=1:(N=2,j=_)}switch(j++,N){case 1:{for(q=V[k-2],V[k-2]=0,i=k-2;i>=j;i--)if(p=o.i(d.a)(C[i],q),f=C[i]/p,F=q/p,C[i]=p,i!==j&&(q=-F*V[i-1],V[i-1]=f*V[i-1]),z)for(U=0;UJ&&(c=-c),c=b/(J+c)),q=(B+W)*(B-W)+c,Y=B*Q,i=j;i=C[j]&&(C[j]=0>C[j]?-C[j]:0,z))for(U=0;U<=g;U++)P[U][j]=-P[U][j];for(;j=C[j+1]);){if(p=C[j],C[j]=C[j+1],C[j+1]=p,z&&je&&t++;return t},get diagonal(){return this.s},get threshold(){return 2.220446049250313e-16/2*v(this.m,this.n)*this.s[0]},get leftSingularVectors(){return l.a.isMatrix(this.U)||(this.U=new l.a(this.U)),this.U},get rightSingularVectors(){return l.a.isMatrix(this.V)||(this.V=new l.a(this.V)),this.V},get diagonalMatrix(){return l.a.diag(this.s)},solve:function(t){var n=this.threshold,e=this.s.length,o=l.a.zeros(e,e),s;for(s=0;sn?t[r][i]/this.s[i]:0;var a=this.U,c=a.length,m=a[0].length,d=new l.a(e,c),g,p;for(r=0;ra[d][d]&&(p=-p),u=d;uD[j][j]&&(C[j]=-C[j]),U=j;UV[j+1]&&(V[j]=0-V[j]),U=j+1;U=j&&_!==j;_--)if(p=(_===k?0:u(V[_]))+(_===j+1?0:u(V[_-1])),u(C[_])<=K*p){C[_]=0;break}_===j?N=3:_===k-1?N=1:(N=2,j=_)}switch(j++,N){case 1:{for(q=V[k-2],V[k-2]=0,i=k-2;i>=j;i--)if(p=o.i(d.a)(C[i],q),f=C[i]/p,F=q/p,C[i]=p,i!==j&&(q=-F*V[i-1],V[i-1]=f*V[i-1]),z)for(U=0;UJ&&(c=-c),c=b/(J+c)),q=(B+W)*(B-W)+c,Y=B*Q,i=j;i=C[j]&&(C[j]=0>C[j]?-C[j]:0,z))for(U=0;U<=g;U++)P[U][j]=-P[U][j];for(;j=C[j+1]);){if(p=C[j],C[j]=C[j+1],C[j+1]=p,z&&je&&t++;return t},get diagonal(){return this.s},get threshold(){return 2.220446049250313e-16/2*v(this.m,this.n)*this.s[0]},get leftSingularVectors(){return l.a.isMatrix(this.U)||(this.U=new l.a(this.U)),this.U},get rightSingularVectors(){return l.a.isMatrix(this.V)||(this.V=new l.a(this.V)),this.V},get diagonalMatrix(){return l.a.diag(this.s)},solve:function(t){var n=this.threshold,e=this.s.length,o=l.a.zeros(e,e),s;for(s=0;sn?t[r][i]/this.s[i]:0;var a=this.U,c=a.length,m=a[0].length,d=new l.a(e,c),g,p;for(r=0;rt&&(t=e[o]);return t},t.min=function(e){for(var t=Infinity,n=e.length,o=0;on&&(n=e[s]);return{min:t,max:n}},t.arithmeticMean=function(e){for(var t=0,n=e.length,o=0;on)throw new RangeError('sum of values is negative');return t/n},t.median=function(e,i){i===void 0&&(i=!1),i||(e=e.slice().sort(o));var t=e.length,n=c(t/2);return 0==t%2?0.5*(e[n-1]+e[n]):e[n]},t.variance=function(e,n){n===void 0&&(n=!0);for(var o=t.mean(e),s=0,r=e.length,a=0,i;aa&&(a=n[o],l=o);return i[l]},t.covariance=function(e,n,o){'undefined'==typeof o&&(o=!0);var s=t.mean(e),r=t.mean(n);if(e.length!==n.length)throw'Vectors do not have the same dimensions';for(var a=0,c=e.length,l=0;lt&&(t=e[o]);return t},t.min=function(e){for(var t=e[0],n=e.length,o=1;on&&(n=e[s]);return{min:t,max:n}},t.arithmeticMean=function(e){for(var t=0,n=e.length,o=0;on)throw new RangeError('sum of values is negative');return t/n},t.median=function(e,i){i===void 0&&(i=!1),i||(e=[].concat(e).sort(o));var t=e.length,n=c(t/2);return 0==t%2?0.5*(e[n-1]+e[n]):e[n]},t.variance=function(e,n){n===void 0&&(n=!0);for(var o=t.mean(e),s=0,r=e.length,a=0,i;aa&&(a=n[o],l=o);return i[l]},t.covariance=function(e,n,o){'undefined'==typeof o&&(o=!0);var s=t.mean(e),r=t.mean(n);if(e.length!==n.length)throw'Vectors do not have the same dimensions';for(var a=0,c=e.length,l=0;l>>0).toString(2),t+='00000000000000000000000000000000'.substr(i.length)+i;return t}var o=t(103);e.exports={count:function(e){for(var t=0,n=0;n>8]+o[255&e[n]>>16]+o[255&e[n]>>24];return t},and:function(e,t){for(var n=Array(e.length),o=0;o>5]&1<<31-i%32)},setBit:function(e,i,t){var n=i>>5,o=1<<31-i%32;return e[n]=t?o|e[n]:~o&e[n],e},toBinaryString:n,parseBinaryString:function(e){for(var t=e.length/32,n=Array(t),o=0;o>>0).toString(16),t+='00000000'.substr(i.length)+i;return t},parseHexString:function(e){for(var t=e.length/8,n=Array(t),o=0;oi;i+=4)o+=' '+t.substr(32*s+i,4);sArray(i).fill(0))}function s(e){var t=new Set;for(let n=0;n=i||i>e.length||!m(i))throw new Error('K should be a positive integer bigger than the number of points');var l;if(!Array.isArray(n.initialization))switch(n.initialization){case'random':l=a.random(e,i);break;case'mostDistant':l=a.mostDistant(e,i,r.calculateDistanceMatrix(e,n.distanceFunction));break;default:throw new Error('Unknown initialization method: "'+n.initialization+'"');}else if(n.initialization.length!==i)throw new Error('The initial centers should have the same length as K');else l=n.initialization;0===n.maxIterations&&(n.maxIterations=t);var c=Array(e.length);if(n.withIterations)return s(l,e,c,i,n);for(var d=!1,g=0,p;!d&&g=r.damping)throw new TypeError('The damping option should be a positive number');if(r=Object.assign({},s,r),!r.initialValues){r.initialValues=Array(t.length);for(var a=0;ae.x.length||e.y.constructor!==Array||2>e.y.length)throw new TypeError('The data parameter elements should be an array with more than 2 points');const i=e.x.length;if(i!==e.y.length)throw new RangeError('The data parameter elements should have the same size');for(var l=r.initialValues,c=n(e,l,t),m=c<=r.errorTolerance,u=0;us[0].rows)return null;var r=s[0],t=s[1],a=s[2],l=r.rows,c=[l/S(t.dot(t))],n=Object.create(n.LMOptions||[3,100,0.001,0.001,0.001,0.01,0.01,11,9,1]),g=u(r[0][0]-r[1][0]),p=new h([[-g/1e4],[-0.001],[-g/1e4]]),j=new h([[i.x],[1],[i.width]]),k=new h([[i.x-g],[0.75],[i.width/4]]),x=new h([[i.x+g],[1.25],[4*i.width]]),w=d.optimize(o,j,r,t,c,p,k,x,[],n);return w=w.p,[w[0],[w[1][0]*a],w[2]]}function c(e,i,n){n=n||{};var o=m(e,n.percentage||0);if(null===o||3>o[0].rows)return null;var r=o[0],t=o[1],a=o[2],l=r.rows,c=[l/S(t.dot(t))],n=Object.create(n.LMOptions||[3,100,0.001,0.001,0.001,0.01,0.01,11,9,1]),g=u(r[0][0]-r[1][0]),p=new h([[-g/1e4],[-0.001],[-g/1e4]]),p=new h([[-u(r[0][0]-r[1][0])/1e3],[-0.001],[-i.width/1e3]]),j=new h([[i.x],[1],[i.width]]),k=new h([[i.x-g],[0.75],[i.width/4]]),x=new h([[i.x+g],[1.25],[4*i.width]]),w=d.optimize(s,j,r,t,c,p,k,x,[],n);return w=w.p,[w[0],[w[1][0]*a],w[2]]}function m(e,n){var o=e.length,s=null,t=null,r=0,a,l,c;if(2==o){var i=e[0].length;if(s=Array(i),t=Array(i),a=e[0],l=e[1],'number'==typeof a[0])for(c=0;cr&&(r=l[c]);else if('object'==typeof a[0])for(c=0;cr&&(r=l[c][0])}else{var i=o;for(s=Array(i),t=Array(i),c=0;cr&&(r=t[c])}for(c=0;cr[0].rows)return null;var a=r[0],t=r[1],l=r[2],c=a.rows,p=[c/g.sqrt(t.dot(t))],s=Object.create(s||[3,100,0.001,0.001,0.001,0.01,0.01,11,9,1]),j=o.length,k=new h(3*j,1),x=new h(3*j,1),w=new h(3*j,1),f=new h(3*j,1),y=u(a[0][0]-a[1][0]),b;for(b=0;br[0].rows)return null;var a=r[0],t=r[1],l=r[2],c=a.rows,p=new h(c,1),j=c/g.sqrt(t.dot(t)),k;for(k=0;ks[0].rows)return null;for(var r=s[0],t=s[1],a=s[2],l=0,u=r.length,d=[],g=0,i,p,h,a,j;gs[0].rows)return null;for(var r=s[0],t=s[1],l=s[2],c=0,u=r.length,d=[],g=0,i,p,h,l,j;ge[0].length,o){e=this._adjust(e,t);const i=e.transposeView().mmul(e).div(e.rows-1);this._computeFromCovarianceMatrix(i)}else{e=this._adjust(e,t);var r=new s(e,{computeLeftSingularVectors:!1,computeRightSingularVectors:!0,autoTranspose:!0});this.U=r.rightSingularVectors;const i=r.diagonal,n=Array(i.length);for(var a=0;ai/e)}getCumulativeVariance(){for(var e=this.getExplainedVariance(),t=1;tS(e))}getLoadings(){return this.U.transpose()}toJSON(){return{name:'PCA',center:this.center,scale:this.scale,means:this.means,stdevs:this.stdevs,U:this.U,S:this.S}}_adjust(e,t){if(this.center=!!t.center,this.scale=!!t.scale,e=new n(e),this.center){const i=a(e),t=this.scale?l(e,i,!0):null;if(this.means=i,e.subRowVector(i),this.scale){for(var o=0;or||r!==a)throw new Error('When "all" option is false, the prediction matrix must be square and have at least 3 columns');for(var u=0;ue.pred-i.pred):m.sort((e,i)=>i.pred-e.pred);const d=this.cutoffs=[c?e:t],g=this.fp=[0],p=this.tp=[0];for(var h=0,j=0,k=m[0].pred,x=0,w=0,u=0;u=i)for(var n=e-i+1;n<=e;n++)t*=n;return t}function l(e,i,t,r,n){for(var s=0,l=0;l<=r;l++)s+=(2*l+1)*(a(2*t,l)/a(2*t+l+1,l+1))*o(e,t,l,0)*o(i,t,l,n);return s}function s(e,i,n){for(var o=Array(e),s=c(e/2),r=-s;r<=s;r++){o[r+s]=Array(e);for(var t=-s;t<=s;t++)o[r+s][t+s]=l(t,r,s,i,n)}return o}var u=t(21),d=t(245),g={windowSize:9,derivative:0,polynomial:3};e.exports=function(e,t,o){if(o=u({},g,o),0==o.windowSize%2||5>o.windowSize||!m(o.windowSize))throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');if(o.windowSize>e.length)throw new RangeError('Window size is higher than the data length '+o.windowSize+'>'+e.length);if(0>o.derivative||!m(o.derivative))throw new RangeError('Derivative should be a positive integer');if(1>o.polynomial||!m(o.polynomial))throw new RangeError('Polynomial should be a positive integer');6<=o.polynomial&&console.warn('You should not use polynomial grade higher than 5 if you are not sure that your data arises from such a model. Possible polynomial oscillation problems');var a=o.windowSize,p=c(a/2),h=e.length,j=Array(h),k=s(a,o.polynomial,o.derivative),x=0,w=!0;'[object Array]'===Object.prototype.toString.call(t)?w=!1:x=r(t,o.derivative);for(var f=0;fu.windowSize||!m(u.windowSize))throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');if(0>u.derivative||!m(u.derivative))throw new RangeError('Derivative should be a positive integer');if(1>u.polynomial||!m(u.polynomial))throw new RangeError('Polynomial should be a positive integer');var g=c(u.windowSize/2),p,h;'pre'===u.pad&&(e=o(e,{size:g,value:u.padValue}));var x=Array(e.length-2*g);if(5===u.windowSize&&2===u.polynomial&&(1===u.derivative||2===u.derivative))1===u.derivative?(p=[-2,-1,0,1,2],h=10):(p=[2,-1,-2,-1,2],h=7);else{for(var w=n.ones(u.windowSize,u.polynomial+1),f=-(u.windowSize-1)/2,y=0;ys?j+=this.x:s>=this.x&&(j-=this.x),r=p;r<=h;r++){var k=r;0>r?k+=this.y:r>=this.y&&(k-=this.y),a=n[this.distanceMethod](this.nodes[j][k]),a{return this.get(i,t)===n?n:(e=!1,!1)}),e}get cardinality(){return this.elements.size}get size(){return this.rows*this.columns}get(e,i){return this.elements.get(e*this.columns+i)}set(e,i,t){return this.threshold&&u(t){return e.forEachNonZero((e,s,r)=>{return i===e&&n.set(t,s,n.get(t,s)+o*r),r}),o}),n}kroneckerProduct(e){const i=this.rows,t=this.columns,n=e.rows,o=e.columns,s=new r(i*n,t*o,{initialCapacity:this.cardinality*e.cardinality});return this.forEachNonZero((t,i,r)=>{return e.forEachNonZero((e,a,l)=>{return s.set(n*t+e,o*i+a,r*l),l}),r}),s}forEachNonZero(e){return this.elements.forEachPair((t,n)=>{const o=0|t/this.columns,i=t%this.columns;let s=e(o,i,n);return!1!==s&&(this.threshold&&u(s){return t[s]=e,n[s]=i,o[s]=r,s++,r}),{rows:t,columns:n,values:o}}setThreshold(e){return 0!==e&&e!==this.threshold&&(this.threshold=e,this.forEachNonZero((e,i,t)=>t)),this}}r.prototype.klass='Matrix',r.identity=r.eye,r.prototype.tensorProduct=r.prototype.kroneckerProduct,e.exports=r;var a=` (function %name%(value) { if (typeof value === 'number') return this.%name%S(value); return this.%name%M(value); }) -`,inplaceOperatorScalar=` +`,l=` (function %name%S(value) { this.forEachNonZero((i, j, v) => v %op% value); return this; }) -`,inplaceOperatorMatrix=` +`,c=` (function %name%M(matrix) { matrix.forEachNonZero((i, j, v) => { this.set(i, j, this.get(i, j) %op% v); @@ -99,22 +455,22 @@ }); return this; }) -`,staticOperator=` +`,m=` (function %name%(matrix, value) { var newMatrix = new SparseMatrix(matrix); return newMatrix.%name%(value); }) -`,inplaceMethod=` +`,d=` (function %name%() { this.forEachNonZero((i, j, v) => %method%(v)); return this; }) -`,staticMethod=` +`,g=` (function %name%(matrix) { var newMatrix = new SparseMatrix(matrix); return newMatrix.%name%(); }) -`,operators=[['+','add'],['-','sub','subtract'],['*','mul','multiply'],['/','div','divide'],['%','mod','modulus'],['&','and'],['|','or'],['^','xor'],['<<','leftShift'],['>>','signPropagatingRightShift'],['>>>','rightShift','zeroFillRightShift']];for(var operator of operators)for(var i=1;i$.length)throw new Error('Cannot train with less than 2 observations');if(this._trained=!1,this._loaded=!1,this.N=ee.length,this.D=$[0].length,this.options.whitening){this.X=Array(this.N);for(var te=0;tethis.options.tol&&0Math.abs(fe-ye))continue;if(je=2*oe[te][ie]-oe[te][te]-oe[ie][ie],0<=je)continue;var we=ae[ie]-ee[ie]*(ge-pe)/je;if(we>ye?we=ye:weMath.abs(xe-we))continue;ae[ie]=we,ae[te]+=ee[te]*ee[ie]*(xe-we),de=this.b-ge-ee[te]*(ae[te]-he)*oe[te][te]-ee[ie]*(ae[ie]-xe)*oe[te][ie],ce=this.b-pe-ee[te]*(ae[te]-he)*oe[te][ie]-ee[ie]*(ae[ie]-xe)*oe[ie][ie],this.b=(de+ce)/2,ae[te]this.options.alphaTol&&(Me.push(this.X[te]),ze.push(ee[te]),Se.push(this.alphas[te]),this._supportVectorIdx.push(te));this.X=Me,this.Y=ze,this.N=Me.length,this.alphas=Se,this._trained=!0},O.prototype.predictOne=function($){var ee=this.marginOne($);return 0>>=0,le>>>=0;var de=65535&ae,ce=ae-de;return(ce*le>>>0)+de*le>>>0}function G(ae){0===ae.state[0]&&0===ae.state[1]&&0===ae.state[2]&&0===ae.state[3]&&(ae.state[0]=88,ae.state[1]=83,ae.state[2]=65,ae.state[3]=68)}function Z(ae){var le=ae.state[0];le^=le<>>oe,le^=ae.state[3]<=arguments.length||void 0===arguments[0]?Date.now():arguments[0];O(this,ae),this.state=new Uint32Array(4),this.init(le)}return $(ae,[{key:'init',value:function(de){this.state[0]=de,this.state[1]=0,this.state[2]=0,this.state[3]=0;for(var ce=1;ce>>30>>>0)>>>0;G(this);for(var ce=0;ce>>0}},{key:'getFloat',value:function(){return(this.getUint32()>>>8)*(1/16777216)}},{key:'random',get:function(){return this._random||(this._random=this.getFloat.bind(this)),this._random}}]),ae}();R['default']=ie;var ne=15,oe=18,se=11;I.exports=R['default']},function(I){(function(){'use strict';function O(Z){for(var $=[],ee=0;eehe?1:0},ae=function(pe,he,xe,fe,ye){var je;if(null==xe&&(xe=0),null==ye&&(ye=$),0>xe)throw new Error('lo must be non-negative');for(null==fe&&(fe=pe.length);xeye(he,pe[je])?fe=je:xe=je+1;return[].splice.apply(pe,[xe,xe-xe].concat(he)),he},ne=function(pe,he,xe){return null==xe&&(xe=$),pe.push(he),me(pe,0,pe.length-1,xe)},ie=function(pe,he){var xe,fe;return null==he&&(he=$),xe=pe.pop(),pe.length?(fe=pe[0],pe[0]=xe,ge(pe,0,he)):fe=xe,fe},se=function(pe,he,xe){var fe;return null==xe&&(xe=$),fe=pe[0],pe[0]=he,ge(pe,0,xe),fe},oe=function(pe,he,xe){var fe;return null==xe&&(xe=$),pe.length&&0>xe(pe[0],he)&&(fe=[pe[0],he],he=fe[0],pe[0]=fe[1],ge(pe,0,xe)),he},te=function(pe,he){var xe,fe,je,we,be,ve;for(null==he&&(he=$),we=function(){ve=[];for(var Me=0,ze=ee(pe.length/2);0<=ze?Meze;0<=ze?Me++:Me--)ve.push(Me);return ve}.apply(this).reverse(),be=[],(fe=0,je=we.length);fexe(fe,je)&&(ae(ke,fe,0,null,xe),ke.pop(),je=ke[ke.length-1]);return ke}for(te(pe,xe),Se=[],(ye=be=0,ze=le(he,pe.length));0<=ze?beze;ye=0<=ze?++be:--be)Se.push(ie(pe,xe));return Se},me=function(pe,he,xe,fe){var ye,je,ke;for(null==fe&&(fe=$),ye=pe[xe];xe>he;){if(ke=xe-1>>1,je=pe[ke],0>fe(ye,je)){pe[xe]=je,xe=ke;continue}break}return pe[xe]=ye},ge=function(pe,he,xe){var fe,ye,je,ke,we;for(null==xe&&(xe=$),ye=pe.length,we=he,je=pe[he],fe=2*he+1;fexe(pe[fe],pe[ke]))&&(fe=ke),pe[he]=pe[fe],he=fe,fe=2*he+1;return pe[he]=je,me(pe,we,he,xe)},Z=function(){function pe(he){this.cmp=null==he?$:he,this.nodes=[]}return pe.push=ne,pe.pop=ie,pe.replace=se,pe.pushpop=oe,pe.heapify=te,pe.updateItem=ue,pe.nlargest=de,pe.nsmallest=ce,pe.prototype.push=function(he){return ne(this.nodes,he,this.cmp)},pe.prototype.pop=function(){return ie(this.nodes,this.cmp)},pe.prototype.peek=function(){return this.nodes[0]},pe.prototype.contains=function(he){return-1!==this.nodes.indexOf(he)},pe.prototype.replace=function(he){return se(this.nodes,he,this.cmp)},pe.prototype.pushpop=function(he){return oe(this.nodes,he,this.cmp)},pe.prototype.heapify=function(){return te(this.nodes,this.cmp)},pe.prototype.updateItem=function(he){return ue(this.nodes,he,this.cmp)},pe.prototype.clear=function(){return this.nodes=[]},pe.prototype.empty=function(){return 0===this.nodes.length},pe.prototype.size=function(){return this.nodes.length},pe.prototype.clone=function(){var he;return he=new pe,he.nodes=this.nodes.slice(0),he},pe.prototype.toArray=function(){return this.nodes.slice(0)},pe.prototype.insert=pe.prototype.push,pe.prototype.top=pe.prototype.peek,pe.prototype.front=pe.prototype.peek,pe.prototype.has=pe.prototype.contains,pe.prototype.copy=pe.prototype.clone,pe}(),function(pe,he){return E=[],O=he,G='function'==typeof O?O.apply(R,E):O,!(void 0!==G&&(I.exports=G))}(this,function(){return Z})}).call(this)},function(I,R,D){'use strict';function Z(ne){for(var oe=Array(ne[0].length),se=0;se=he)throw new Error('x must be an increasing serie');for(;0=ke?0:je/ke,be++,be===ne)break main;ue=me,me+=se,je=0,ke=0}ge>ue&&(je+=pe,ke++),(ge==-Number.MAX_VALUE||1$[1]&&($=$.slice().reverse(),ee=ee.slice().reverse());var ie=$.length;if(ie!==ee.length)throw new RangeError('the x and y vector doesn\'t have the same size.');te===void 0&&(te={});var ne=te.from===void 0?$[0]:te.from;if(isNaN(ne)||!isFinite(ne))throw new RangeError('\'From\' value must be a number');var oe=te.to===void 0?$[$.length-1]:te.to;if(isNaN(oe)||!isFinite(oe))throw new RangeError('\'To\' value must be a number');var se=ne>oe;if(se){var ae=ne;ne=oe,oe=ae}var le=te.numberOfPoints===void 0?100:te.numberOfPoints;if(isNaN(le)||!isFinite(le))throw new RangeError('\'Number of points\' value must be a number');if(1>le)throw new RangeError('the number of point must be higher than 1');var de='slot'===te.variant?'slot':'smooth',ce='slot'==de?G($,ee,ne,oe,le):E($,ee,ne,oe,le);return se?ce.reverse():ce},R.integral=Z},function(I,R,D){'use strict';R.SNV=function(G){for(var Z=E.mean(G),$=E.standardDeviation(G),ee=G.slice(),te=0;teO;O++){for(var E=O,G=0;E;)E&=E-1,G++;D[O]=G}I.exports=D},function(I){'use strict';const O={mode:'index'};I.exports=function*(E,G,Z){function $(){var de,ce,ue;for(ce=1;0>=ne[ce];)ce++;if(0===ne[ce-1]){for(de=ce-1;1!==de;de--)ne[de]=-1;ne[ce]=0,oe=ae=0,ne[1]=1,se=ce-1}else{1te&&(te=~te),$[te]},R.largestPrime=Z},function(I,R,D){'use strict';function O(le,de,ce){for(var ue=1e101,me=0;meue.d&&(ue.d=xe-fe,ue.p=ye)}return ue}function te(le,de,ce){for(var ue=0,me=0,ge=0;gepe&&(pe=ge,he=je)}if(pe=0,2===ye[he].index.length)ye[he].children=[ye[he].index[0],ye[he].index[1]],ye[he].distance=de.dist(le[ye[he].index[0].index],le[ye[he].index[1].index]);else if(3===ye[he].index.length){ye[he].children=[ye[he].index[0],ye[he].index[1],ye[he].index[2]];var be=[de.dist(le[ye[he].index[0].index],le[ye[he].index[1].index]),de.dist(le[ye[he].index[1].index],le[ye[he].index[2].index])];ye[he].distance=(be[0]+be[1])/2}else{for(var ve=new se,Me=new se,ze=[Array(ye[he].index.length),[]],Se=0;Sepe&&(pe=xe,fe=qe)}for(ze[1]=[fe],ze[0].splice(fe,1),xe=ee(ze,le,de.dist);0ie.dist&&(ie.dist=ee[te[0]][ne],ie.index=ne);if(te[1]=ie.index,2<$)for(var oe=2,se;oe<$;++oe){se={dist:-1,index:-1};for(var ae=0,le;aese.dist&&(se=Object.assign({},le))}te[oe]=se.index}}return te.map(ce=>Z[ce])}},function(I,R){'use strict';/** +`,p=[['+','add'],['-','sub','subtract'],['*','mul','multiply'],['/','div','divide'],['%','mod','modulus'],['&','and'],['|','or'],['^','xor'],['<<','leftShift'],['>>','signPropagatingRightShift'],['>>>','rightShift','zeroFillRightShift']];for(var h of p)for(var j=1;je.length)throw new Error('Cannot train with less than 2 observations');if(this._trained=!1,this._loaded=!1,this.N=t.length,this.D=e[0].length,this.options.whitening){this.X=Array(this.N);for(var n=0;nthis.options.tol&&0u(b-S))continue;if(z=2*l[n][i]-l[n][n]-l[i][i],0<=z)continue;var V=m[i]-t[i]*(k-x)/z;if(V>S?V=S:Vu(y-V))continue;m[i]=V,m[n]+=t[n]*t[i]*(y-V),a=this.b-k-t[n]*(m[n]-f)*l[n][n]-t[i]*(m[i]-y)*l[n][i],p=this.b-x-t[n]*(m[n]-f)*l[n][i]-t[i]*(m[i]-y)*l[i][i],this.b=(a+p)/2,m[n]this.options.alphaTol&&(w.push(this.X[n]),D.push(t[n]),C.push(this.alphas[n]),this._supportVectorIdx.push(n));this.X=w,this.Y=D,this.N=w.length,this.alphas=C,this._trained=!0},n.prototype.predictOne=function(e){var i=this.marginOne(e);return 0>>=0,i>>>=0;var t=65535&e,n=e-t;return(n*i>>>0)+t*i>>>0}function o(e){0===e.state[0]&&0===e.state[1]&&0===e.state[2]&&0===e.state[3]&&(e.state[0]=88,e.state[1]=83,e.state[2]=65,e.state[3]=68)}function s(e){var i=e.state[0];i^=i<>>m,i^=e.state[3]<=arguments.length||void 0===arguments[0]?Date.now():arguments[0];t(this,e),this.state=new Uint32Array(4),this.init(i)}return r(e,[{key:'init',value:function(e){this.state[0]=e,this.state[1]=0,this.state[2]=0,this.state[3]=0;for(var t=1;t>>30>>>0)>>>0;o(this);for(var t=0;t>>0}},{key:'getFloat',value:function(){return(this.getUint32()>>>8)*(1/16777216)}},{key:'random',get:function(){return this._random||(this._random=this.getFloat.bind(this)),this._random}}]),e}();i['default']=l;var c=15,m=18,u=11;e.exports=i['default']},function(e){(function(){'use strict';function i(e){for(var t=[],n=0;ni?1:0},p=function(e,i,t,n,o){var s;if(null==t&&(t=0),null==o&&(o=r),0>t)throw new Error('lo must be non-negative');for(null==n&&(n=e.length);to(i,e[s])?n=s:t=s+1;return[].splice.apply(e,[t,t-t].concat(i)),i},u=function(e,i,t){return null==t&&(t=r),e.push(i),x(e,0,e.length-1,t)},m=function(e,i){var t,n;return null==i&&(i=r),t=e.pop(),e.length?(n=e[0],e[0]=t,f(e,0,i)):n=t,n},g=function(e,i,t){var n;return null==t&&(t=r),n=e[0],e[0]=i,f(e,0,t),n},d=function(e,i,t){var n;return null==t&&(t=r),e.length&&0>t(e[0],i)&&(n=[e[0],i],i=n[0],e[0]=n[1],f(e,0,t)),i},a=function(e,t){var n,i,o,s,a,c;for(null==t&&(t=r),s=function(){c=[];for(var i=0,t=l(e.length/2);0<=t?it;0<=t?i++:i--)c.push(i);return c}.apply(this).reverse(),a=[],(i=0,o=s.length);in(o,i)&&(p(l,o,0,null,n),l.pop(),i=l[l.length-1]);return l}for(a(e,n),k=[],(s=u=0,j=h(t,e.length));0<=j?uj;s=0<=j?++u:--u)k.push(m(e,n));return k},x=function(e,i,t,n){var o,s,a;for(null==n&&(n=r),o=e[t];t>i;){if(a=t-1>>1,s=e[a],0>n(o,s)){e[t]=s,t=a;continue}break}return e[t]=o},f=function(e,i,t){var n,o,s,a,l;for(null==t&&(t=r),o=e.length,l=i,s=e[i],n=2*i+1;nt(e[n],e[a]))&&(n=a),e[i]=e[n],i=n,n=2*i+1;return e[i]=s,x(e,l,i,t)},s=function(){function e(e){this.cmp=null==e?r:e,this.nodes=[]}return e.push=u,e.pop=m,e.replace=g,e.pushpop=d,e.heapify=a,e.updateItem=w,e.nlargest=j,e.nsmallest=k,e.prototype.push=function(e){return u(this.nodes,e,this.cmp)},e.prototype.pop=function(){return m(this.nodes,this.cmp)},e.prototype.peek=function(){return this.nodes[0]},e.prototype.contains=function(e){return-1!==this.nodes.indexOf(e)},e.prototype.replace=function(e){return g(this.nodes,e,this.cmp)},e.prototype.pushpop=function(e){return d(this.nodes,e,this.cmp)},e.prototype.heapify=function(){return a(this.nodes,this.cmp)},e.prototype.updateItem=function(e){return w(this.nodes,e,this.cmp)},e.prototype.clear=function(){return this.nodes=[]},e.prototype.empty=function(){return 0===this.nodes.length},e.prototype.size=function(){return this.nodes.length},e.prototype.clone=function(){var i;return i=new e,i.nodes=this.nodes.slice(0),i},e.prototype.toArray=function(){return this.nodes.slice(0)},e.prototype.insert=e.prototype.push,e.prototype.top=e.prototype.peek,e.prototype.front=e.prototype.peek,e.prototype.has=e.prototype.contains,e.prototype.copy=e.prototype.clone,e}(),function(s,r){return n=[],t=r,o='function'==typeof t?t.apply(i,n):t,!(void 0!==o&&(e.exports=o))}(this,function(){return s})}).call(this)},function(e,i,t){'use strict';function n(e){for(var t=Array(e[0].length),n=0;n=k)throw new Error('x must be an increasing serie');for(;0=b?0:y/b,i++,i===r)break main;d=g,g+=l,y=0,b=0}p>d&&(y+=h,b++),(p==-t||1e[1]&&(e=e.slice().reverse(),i=i.slice().reverse());var n=e.length;if(n!==i.length)throw new RangeError('the x and y vector doesn\'t have the same size.');t===void 0&&(t={});var r=t.from===void 0?e[0]:t.from;if(isNaN(r)||!isFinite(r))throw new RangeError('\'From\' value must be a number');var a=t.to===void 0?e[e.length-1]:t.to;if(isNaN(a)||!isFinite(a))throw new RangeError('\'To\' value must be a number');var l=r>a;if(l){var c=r;r=a,a=c}var m=t.numberOfPoints===void 0?100:t.numberOfPoints;if(isNaN(m)||!isFinite(m))throw new RangeError('\'Number of points\' value must be a number');if(1>m)throw new RangeError('the number of point must be higher than 1');var u='slot'===t.variant?'slot':'smooth',d='slot'==u?s(e,i,r,a,m):o(e,i,r,a,m);return l?d.reverse():d},n.integral=r},function(e,i,t){'use strict';i.SNV=function(e){for(var t=n.mean(e),o=n.standardDeviation(e),s=e.slice(),r=0;rn;n++){for(var i=n,o=0;i;)i&=i-1,o++;t[n]=o}e.exports=t},function(e){'use strict';const t={mode:'index'};e.exports=function*(e,n,o){function s(){var e,i,t;for(i=1;0>=c[i];)i++;if(0===c[i-1]){for(e=i-1;1!==e;e--)c[e]=-1;c[i]=0,u=g=0,c[1]=1,d=i-1}else{1i&&(i=~i),r[i]},i.largestPrime=s},function(e,i,t){'use strict';function n(e,t,n){for(var o=1e101,s=0;ss.d&&(s.d=i-m,s.p=c)}return s}function c(e,t,n){for(var o=0,s=0,r=0;rm&&(m=y,b=z)}if(m=0,2===w[b].index.length)w[b].children=[w[b].index[0],w[b].index[1]],w[b].distance=h.dist(t[w[b].index[0].index],t[w[b].index[1].index]);else if(3===w[b].index.length){w[b].children=[w[b].index[0],w[b].index[1],w[b].index[2]];var R=[h.dist(t[w[b].index[0].index],t[w[b].index[1].index]),h.dist(t[w[b].index[1].index],t[w[b].index[2].index])];w[b].distance=(R[0]+R[1])/2}else{for(var d=new g,V=new g,I=[Array(w[b].index.length),[]],D=0;Dm&&(m=M,S=C)}for(I[1]=[S],I[0].splice(S,1),M=l(I,t,h.dist);0k){R=0;do{for(++R,d=e[k],m=(e[k+1]-d)/(2*n[k]),p=t.i(x.a)(m,1),0>m&&(p=-p),e[k]=n[k]/(m+p),e[k+1]=n[k]*(m+p),w=e[k+1],g=d-e[k],h=k+2;h=k;h--)for(b=c,c=y,z=S,d=y*n[h],g=y*m,p=t.i(x.a)(m,n[h]),n[h+1]=S*p,S=n[h]/p,y=m/p,m=y*e[h]-S*d,e[h+1]=g+S*(y*d+S*e[h]),j=0;jI*f)}e[k]+=V,n[k]=0}for(h=0;h=p;d--)n[d]=t[d][p-1]/m,c+=n[d]*n[d];for(l=S(c),0=p;d--)a+=n[d]*t[d][i];for(a/=c,d=p;d<=r;d++)t[d][i]-=a*n[d]}for(d=0;d<=r;d++){for(a=0,i=r;i>=p;i--)a+=n[i]*t[d][i];for(a/=c,i=p;i<=r;i++)t[d][i]-=a*n[i]}n[p]=m*n[p],t[p][p-1]=m*l}}for(d=0;d=s+1;p--)if(0!==t[p][p-1]){for(d=p+1;d<=r;d++)n[d]=t[d][p-1];for(i=p;i<=r;i++){for(l=0,d=p;d<=r;d++)l+=n[d]*o[d][i];for(l=l/n[p]/t[p][p-1],d=p;d<=r;d++)o[d][i]+=l*n[d]}}}function l(o,a,e,d,g){var h=o-1,n=0,f=o-1,b=2.220446049250313e-16,R=0,V=0,I=0,p=0,D=0,C=0,P=0,A=0,L,i,j,k,l,m,t,w,x,y,U,_,q,F,O;for(L=0;Lf)&&(e[L]=g[L][L],a[L]=0),i=v(L-1,0);i=n;){for(k=h;k>n&&(C=u(g[k-1][k-1])+u(g[k][k]),0===C&&(C=V),!(u(g[k][k-1])=k&&(P=g[l][l],D=w-P,C=x-P,I=(D*C-t)/g[l+1][l]+g[l][l+1],p=g[l+1][l+1]-P-D-C,D=g[l+2][l+1],C=u(I)+u(p)+u(D),I/=C,p/=C,D/=C,l!==k)&&!(u(g[l][l-1])*(u(p)+u(D))l+2&&(g[L][L-3]=0);for(j=l;j<=h-1&&(F=j!==h-1,j!==l&&(I=g[j][j-1],p=g[j+1][j-1],D=F?g[j+2][j-1]:0,w=u(I)+u(p)+u(D),0!==w&&(I/=w,p/=w,D/=w)),0!==w);j++)if(C=S(I*I+p*p+D*D),0>I&&(C=-C),0!==C){for(j===l?k!==l&&(g[j][j-1]=-g[j][j-1]):g[j][j-1]=-C*w,I+=C,w=I/C,x=p/C,P=D/C,p/=I,D/=I,i=j;ia[L])P=t,C=D;else if(k=L,0===a[L]?g[L][h]=0===t?-D/(b*V):-D/t:(w=g[L][L+1],x=g[L+1][L],p=(e[L]-I)*(e[L]-I)+a[L]*a[L],m=(w*C-P*D)/p,g[L][h]=m,g[L+1][h]=u(w)>u(P)?(-D-t*m)/w:(-C-x*m)/P),m=u(g[L][h]),1p)for(k=h-1,u(g[h][h-1])>u(g[h-1][h])?(g[h-1][h-1]=p/g[h][h-1],g[h-1][h]=-(g[h][h]-I)/g[h][h-1]):(O=c(0,-g[h-1][h],g[h-1][h-1]-I,p),g[h-1][h-1]=O[0],g[h-1][h]=O[1]),g[h][h-1]=0,g[h][h]=1,L=h-2;0<=L;L--){for(y=0,U=0,i=k;i<=h;i++)y+=g[L][i]*g[i][h-1],U+=g[L][i]*g[i][h];if(t=g[L][L]-I,0>a[L])P=t,D=y,C=U;else if(k=L,0===a[L]?(O=c(-y,-U,t,p),g[L][h-1]=O[0],g[L][h]=O[1]):(w=g[L][L+1],x=g[L+1][L],_=(e[L]-I)*(e[L]-I)+a[L]*a[L]-p*p,q=2*(e[L]-I)*p,0===_&&0===q&&(_=b*V*(u(t)+u(p)+u(w)+u(x)+u(P))),O=c(w*D-P*y+p*U,w*C-P*U-p*y,_,q),g[L][h-1]=O[0],g[L][h]=O[1],u(w)>u(P)+u(p)?(g[L+1][h-1]=(-y-t*g[L][h-1]+p*g[L][h])/w,g[L+1][h]=(-U-t*g[L][h]-p*g[L][h-1])/w):(O=c(-D-x*g[L][h-1],-C-x*g[L][h],P,p),g[L+1][h-1]=O[0],g[L+1][h]=O[1])),m=v(u(g[L][h-1]),u(g[L][h])),1f)for(i=L;i=n;i--)for(L=n;L<=f;L++){for(P=0,j=n;j<=M(i,f);j++)P+=d[L][j]*g[j][i];d[L][i]=P}}}function c(e,i,t,n){var o,s;return u(t)>u(n)?(o=n/t,s=t+o*n,[(e+o*i)/s,(i-o*e)/s]):(o=t/n,s=n+o*t,[(o*e+i)/s,(o*i-e)/s])}var m=t(3),x=t(25);const g={assumeSymmetric:!1};o.prototype={get realEigenvalues(){return this.d},get imaginaryEigenvalues(){return this.e},get eigenvectorMatrix(){return m.a.isMatrix(this.V)||(this.V=new m.a(this.V)),this.V},get diagonalMatrix(){var t=this.n,n=this.e,e=this.d,o=new m.a(t,t),s,i;for(s=0;sn[s]&&(o[s][s-1]=n[s])}return o}},i.a=o},function(e,i,t){'use strict';function n(e,i){return e=o.a.checkMatrix(e),i=o.a.checkMatrix(i),e.isSquare()?new s.a(e).solve(i):new r.a(e).solve(i)}i.b=function(e){return e=o.a.checkMatrix(e),n(e,o.a.eye(e.rows))},i.a=n;var o=t(3),s=t(24),r=t(59)},function(e,i,t){'use strict';Object.defineProperty(i,'__esModule',{value:!0});var n=t(3);t.d(i,'default',function(){return n.a}),t.d(i,'Matrix',function(){return n.a});var o=t(23);t.d(i,'abstractMatrix',function(){return o.a});var s=t(161);t.d(i,'solve',function(){return s.a}),t.d(i,'inverse',function(){return s.b});var r=t(60);t.d(i,'SingularValueDecomposition',function(){return r.a}),t.d(i,'SVD',function(){return r.a});var a=t(160);t.d(i,'EigenvalueDecomposition',function(){return a.a}),t.d(i,'EVD',function(){return a.a});var l=t(159);t.d(i,'CholeskyDecomposition',function(){return l.a}),t.d(i,'CHO',function(){return l.a});var c=t(24);t.d(i,'LuDecomposition',function(){return c.a}),t.d(i,'LU',function(){return c.a});var m=t(59);t.d(i,'QrDecomposition',function(){return m.a}),t.d(i,'QR',function(){return m.a})},function(){Symbol.species||(Symbol.species=Symbol.for('@@species'))},function(e,i,t){'use strict';var n=t(8);class o extends n.a{constructor(e,i){super(e,e.rows,1),this.column=i}set(e,i,t){return this.matrix.set(e,this.column,t),this}get(e){return this.matrix.get(e,this.column)}}i.a=o},function(e,i,t){'use strict';var n=t(8);class o extends n.a{constructor(e){super(e,e.rows,e.columns)}set(e,i,t){return this.matrix.set(e,this.columns-i-1,t),this}get(e,i){return this.matrix.get(e,this.columns-i-1)}}i.a=o},function(e,i,t){'use strict';var n=t(8);class o extends n.a{constructor(e){super(e,e.rows,e.columns)}set(e,i,t){return this.matrix.set(this.rows-e-1,i,t),this}get(e,i){return this.matrix.get(this.rows-e-1,i)}}i.a=o},function(e,i,t){'use strict';var n=t(8);class o extends n.a{constructor(e,i){super(e,1,e.columns),this.row=i}set(e,i,t){return this.matrix.set(this.row,i,t),this}get(e,i){return this.matrix.get(this.row,i)}}i.a=o},function(e,i,t){'use strict';var n=t(8),o=t(15);class s extends n.a{constructor(e,i,n){var s=t.i(o.i)(e,i,n);super(e,s.row.length,s.column.length),this.rowIndices=s.row,this.columnIndices=s.column}set(e,i,t){return this.matrix.set(this.rowIndices[e],this.columnIndices[i],t),this}get(e,i){return this.matrix.get(this.rowIndices[e],this.columnIndices[i])}}i.a=s},function(e,i,t){'use strict';var n=t(8),o=t(15);class s extends n.a{constructor(e,i,n,s,r){t.i(o.h)(e,i,n,s,r),super(e,n-i+1,r-s+1),this.startRow=i,this.startColumn=s}set(e,i,t){return this.matrix.set(this.startRow+e,this.startColumn+i,t),this}get(e,i){return this.matrix.get(this.startRow+e,this.startColumn+i)}}i.a=s},function(e,i,t){'use strict';var n=t(8);class o extends n.a{constructor(e){super(e,e.columns,e.rows)}set(e,i,t){return this.matrix.set(i,e,t),this}get(e,i){return this.matrix.get(i,e)}}i.a=o},function(e){'use strict';const i={sigma:1,degree:1};e.exports=class{constructor(e){e=Object.assign({},i,e),this.sigma=e.sigma,this.degree=e.degree}compute(e,t){for(var n=0,o=M(e.length,t.length),s=1;s<=o;++s)n+=r(l(-this.sigma*r(r(e[s-1],s)-r(t[s-1],s),2)),this.degree);return n}}},function(e,i,t){'use strict';const n=t(1).squared,o={sigma:1};e.exports=class{constructor(e){e=Object.assign({},o,e),this.sigma=e.sigma}compute(e,i){return 1/(1+n(e,i)/(this.sigma*this.sigma))}}},function(e,i,t){'use strict';const n=t(1),o={sigma:1};e.exports=class{constructor(e){e=Object.assign({},o,e),this.sigma=e.sigma,this.divisor=2*e.sigma*e.sigma}compute(e,i){const t=n(e,i);return l(-t/this.divisor)}}},function(e){'use strict';e.exports=class{compute(e,t){for(var n=M(e.length,t.length),o=0,s=0;sr.dist&&(r.dist=o[s[0]][a],r.index=a);if(s[1]=r.index,2u.dist&&(u=Object.assign({},g))}s[l]=u.index}}return s.map((i)=>e[i])}},function(e,i){'use strict';/** * k-d Tree JavaScript - V 1.01 * * https://github.com/ubilabs/kd-tree-javascript @@ -123,5 +479,5 @@ * @author Martin Kleppe , 2012 * @author Ubilabs http://ubilabs.net, 2012 * @license MIT License -*/function O(Z,$,ee){this.obj=Z,this.left=null,this.right=null,this.parent=ee,this.dimension=$}function E(Z,$,ee){function te(oe,se,ae){var le=se%ee.length,de,ce;return 0===oe.length?null:1===oe.length?new O(oe[0],le,ae):(oe.sort(function(ue,me){return ue[ee[le]]-me[ee[le]]}),de=Math.floor(oe.length/2),ce=new O(oe[de],le,ae),ce.left=te(oe.slice(0,de),se+1,ce),ce.right=te(oe.slice(de+1),se+1,ce),ce)}var ne=this;Array.isArray(Z)?this.root=te(Z,0,null):function(oe){function se(ae){ae.left&&(ae.left.parent=ae,se(ae.left)),ae.right&&(ae.right.parent=ae,se(ae.right))}ne.root=oe,se(ne.root)}(Z,$,ee),this.toJSON=function(oe){oe||(oe=this.root);var se=new O(oe.obj,oe.dimension,null);return oe.left&&(se.left=ne.toJSON(oe.left)),oe.right&&(se.right=ne.toJSON(oe.right)),se},this.insert=function(oe){function se(ce,ue){if(null===ce)return ue;var me=ee[ce.dimension];return oe[me]se&&ue.pop()}var he=ee[me.dimension],xe=$(oe,me.obj),fe={},pe,ye,je,ke;for(ke=0;keie&&(te=se,ie=ae)}return te},O.load=function(Z){if('KNN'!==Z.modelName)throw new RangeError('The given model is invalid!');return new O(!0,Z)},O.prototype.export=function(){return{modelName:'KNN',kdtree:this.kdtree,k:this.k,classes:this.classes}}},function(I,R,D){'use strict';function O(G){if(!(this instanceof O))return new O(G);if(G=E.checkMatrix(G),!G.isSymmetric())throw new Error('Matrix is not symmetric');var Z=G,$=Z.rows,ee=new E($,$),te=!0,ie,ne,oe;for(ne=0;ne<$;ne++){var se=ee[ne],ae=0;for(oe=0;oexe){qe=0;do{for(++qe,ue=de[xe],ye=(de[xe+1]-ue)/(2*le[xe]),je=ne(ye,1),0>ye&&(je=-je),de[xe]=le[xe]/(ye+je),de[xe+1]=le[xe]*(ye+je),ke=de[xe+1],me=ue-de[xe],ge=xe+2;ge=xe;ge--)for(ve=be,be=we,Se=ze,ue=we*le[ge],me=we*ye,je=ne(ye,le[ge]),le[ge+1]=ze*je,ze=le[ge]/je,we=ye/je,ye=we*de[ge]-ze*ue,de[ge+1]=me+ze*(we*ue+ze*de[ge]),he=0;heRe*Ie)}de[xe]+=Ce,le[xe]=0}for(ge=0;ge=ye;xe--)de[xe]=le[xe][ye-1]/je,he+=de[xe]*de[xe];for(pe=Math.sqrt(he),0=ye;xe--)ge+=de[xe]*le[xe][fe];for(ge/=he,xe=ye;xe<=me;xe++)le[xe][fe]-=ge*de[xe]}for(xe=0;xe<=me;xe++){for(ge=0,fe=me;fe>=ye;fe--)ge+=de[fe]*le[xe][fe];for(ge/=he,fe=ye;fe<=me;fe++)le[xe][fe]-=ge*de[fe]}de[ye]=je*de[ye],le[ye][ye-1]=je*pe}}for(xe=0;xe=ue+1;ye--)if(0!==le[ye][ye-1]){for(xe=ye+1;xe<=me;xe++)de[xe]=le[xe][ye-1];for(fe=ye;fe<=me;fe++){for(pe=0,xe=ye;xe<=me;xe++)pe+=de[xe]*ce[xe][fe];for(pe=pe/de[ye]/le[ye][ye-1],xe=ye;xe<=me;xe++)ce[xe][fe]+=pe*de[xe]}}}function $(ae,le,de,ce,ue){var me=ae-1,ge=0,pe=ae-1,he=Math.pow(2,-52),xe=0,fe=0,ye=0,je=0,ke=0,we=0,be=0,ve=0,Me,ze,Se,qe,Ce,Ie,Re,De,Pe,Ve,Ae,_e,Oe,Le,Ne;for(Me=0;Mepe)&&(de[Me]=ue[Me][Me],le[Me]=0),ze=Math.max(Me-1,0);ze=ge;){for(qe=me;qe>ge&&(we=Math.abs(ue[qe-1][qe-1])+Math.abs(ue[qe][qe]),0==we&&(we=fe),!(Math.abs(ue[qe][qe-1])=qe&&(be=ue[Ce][Ce],ke=De-be,we=Pe-be,ye=(ke*we-Re)/ue[Ce+1][Ce]+ue[Ce][Ce+1],je=ue[Ce+1][Ce+1]-be-ke-we,ke=ue[Ce+2][Ce+1],we=Math.abs(ye)+Math.abs(je)+Math.abs(ke),ye/=we,je/=we,ke/=we,Ce!=qe)&&!(Math.abs(ue[Ce][Ce-1])*(Math.abs(je)+Math.abs(ke))Ce+2&&(ue[Me][Me-3]=0);for(Se=Ce;Se<=me-1&&(Le=Se!==me-1,Se!=Ce&&(ye=ue[Se][Se-1],je=ue[Se+1][Se-1],ke=Le?ue[Se+2][Se-1]:0,De=Math.abs(ye)+Math.abs(je)+Math.abs(ke),0!==De&&(ye/=De,je/=De,ke/=De)),0!==De);Se++)if(we=Math.sqrt(ye*ye+je*je+ke*ke),0>ye&&(we=-we),0!==we){for(Se==Ce?qe!==Ce&&(ue[Se][Se-1]=-ue[Se][Se-1]):ue[Se][Se-1]=-we*De,ye+=we,De=ye/we,Pe=je/we,be=ke/we,je/=ye,ke/=ye,ze=Se;zele[Me])be=Re,we=ke;else if(qe=Me,0===le[Me]?ue[Me][me]=0===Re?-ke/(he*fe):-ke/Re:(De=ue[Me][Me+1],Pe=ue[Me+1][Me],je=(de[Me]-ye)*(de[Me]-ye)+le[Me]*le[Me],Ie=(De*we-be*ke)/je,ue[Me][me]=Ie,ue[Me+1][me]=Math.abs(De)>Math.abs(be)?(-ke-Re*Ie)/De:(-we-Pe*Ie)/be),Ie=Math.abs(ue[Me][me]),1je)for(qe=me-1,Math.abs(ue[me][me-1])>Math.abs(ue[me-1][me])?(ue[me-1][me-1]=je/ue[me][me-1],ue[me-1][me]=-(ue[me][me]-ye)/ue[me][me-1]):(Ne=ee(0,-ue[me-1][me],ue[me-1][me-1]-ye,je),ue[me-1][me-1]=Ne[0],ue[me-1][me]=Ne[1]),ue[me][me-1]=0,ue[me][me]=1,Me=me-2;0<=Me;Me--){for(Ve=0,Ae=0,ze=qe;ze<=me;ze++)Ve+=ue[Me][ze]*ue[ze][me-1],Ae+=ue[Me][ze]*ue[ze][me];if(Re=ue[Me][Me]-ye,0>le[Me])be=Re,ke=Ve,we=Ae;else if(qe=Me,0===le[Me]?(Ne=ee(-Ve,-Ae,Re,je),ue[Me][me-1]=Ne[0],ue[Me][me]=Ne[1]):(De=ue[Me][Me+1],Pe=ue[Me+1][Me],_e=(de[Me]-ye)*(de[Me]-ye)+le[Me]*le[Me]-je*je,Oe=2*(de[Me]-ye)*je,0===_e&&0===Oe&&(_e=he*fe*(Math.abs(Re)+Math.abs(je)+Math.abs(De)+Math.abs(Pe)+Math.abs(be))),Ne=ee(De*ke-be*Ve+je*Ae,De*we-be*Ae-je*Ve,_e,Oe),ue[Me][me-1]=Ne[0],ue[Me][me]=Ne[1],Math.abs(De)>Math.abs(be)+Math.abs(je)?(ue[Me+1][me-1]=(-Ve-Re*ue[Me][me-1]+je*ue[Me][me])/De,ue[Me+1][me]=(-Ae-Re*ue[Me][me]-je*ue[Me][me-1])/De):(Ne=ee(-ke-Pe*ue[Me][me-1],-we-Pe*ue[Me][me],be,je),ue[Me+1][me-1]=Ne[0],ue[Me+1][me]=Ne[1])),Ie=Math.max(Math.abs(ue[Me][me-1]),Math.abs(ue[Me][me])),1pe)for(ze=Me;ze=ge;ze--)for(Me=ge;Me<=pe;Me++){for(be=0,Se=ge;Se<=Math.min(ze,pe);Se++)be+=ce[Me][Se]*ue[Se][ze];ce[Me][ze]=be}}}function ee(ae,le,de,ce){var ue,me;return Math.abs(de)>Math.abs(ce)?(ue=ce/de,me=de+ue*ce,[(ae+ue*le)/me,(le-ue*ae)/me]):(ue=de/ce,me=ce+ue*de,[(ue*ae+le)/me,(ue*le-ae)/me])}const te=D(3).Matrix,ie=D(11),ne=ie.hypotenuse,oe=ie.getFilled2DArray,se={assumeSymmetric:!1};O.prototype={get realEigenvalues(){return this.d},get imaginaryEigenvalues(){return this.e},get eigenvectorMatrix(){return te.isMatrix(this.V)||(this.V=new te(this.V)),this.V},get diagonalMatrix(){var ae=this.n,le=this.e,de=this.d,ce=new te(ae,ae),ue,me;for(ue=0;uele[ue]&&(ce[ue][ue-1]=le[ue])}return ce}},I.exports=O},function(I,R,D){'use strict';function O(Z){if(!(this instanceof O))return new O(Z);Z=E.checkMatrix(Z);var $=Z.clone(),ee=Z.rows,te=Z.columns,ie=Array(te),ne,oe,se,ae;for(se=0;se$[se][se]&&(le=-le),ne=se;nece[we][we]&&(me[we]=-me[we]),je=we;jehe[we+1]&&(he[we]=0-he[we]),je=we+1;je=we&&Me!==we;Me--)if(ve=(Me===be?0:Math.abs(he[Me]))+(Me===we+1?0:Math.abs(he[Me-1])),Math.abs(me[Me])<=Xe*ve){me[Me]=0;break}Me===we?Ie=3:Me===be-1?Ie=1:(Ie=2,we=Me)}switch(we++,Ie){case 1:{for(ze=he[be-2],he[be-2]=0,ke=be-2;ke>=we;ke--)if(ve=Z(me[ke],ze),Se=me[ke]/ve,qe=ze/ve,me[ke]=ve,ke!==we&&(ze=-qe*he[ke-1],he[ke-1]=Se*he[ke-1]),ae)for(je=0;jeOe&&(Ne=-Ne),Ne=Le/(Oe+Ne)),ze=(Ae+De)*(Ae-De)+Ne,Fe=Ae*_e,ke=we;ke=me[we]&&(me[we]=0>me[we]?-me[we]:0,ae))for(je=0;je<=Te;je++)pe[je][we]=-pe[je][we];for(;we=me[we+1]);){if(ve=me[we],me[we]=me[we+1],me[we+1]=ve,ae&&wete&&ie++;return ie},get diagonal(){return this.s},get threshold(){return Math.pow(2,-52)/2*Math.max(this.m,this.n)*this.s[0]},get leftSingularVectors(){return E.isMatrix(this.U)||(this.U=new E(this.U)),this.U},get rightSingularVectors(){return E.isMatrix(this.V)||(this.V=new E(this.V)),this.V},get diagonalMatrix(){return E.diag(this.s)},solve:function(ee){var ie=this.threshold,ne=this.s.length,oe=E.zeros(ne,ne),se;for(se=0;sete?ee[se][ae]/this.s[ae]:0;var le=this.U,de=le.length,ce=le[0].length,ue=new E(ie,de),me,ge;for(se=0;sese&&(se=le,oe=ae);else if('function'==typeof te)for(var de=Number.MAX_VALUE,ce=0,ue;ce{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.length,G=Array(E);for(var Z=0;Z{const E=O.cutoffs.slice();return E[0]=E[1],E}},function(I,R,D){'use strict';function O(Z,$,ee){var te=new E(Z),ie=new E($);te=G.featureNormalize(te).result,ie=G.featureNormalize(ie).result;var ne=te.rows,oe=te.columns,se=te.clone().mul(te).sum(),ae=te.transpose().mmul(ie);ae.div(G.norm(ae));for(var le=Array(ee),de=Array(ee),ce=Array(ee),ue=0;ueie&&(ie=oe,te=ne);return te}var G=D(0),Z=D(12);class ${constructor(ee,te){if(!0===ee){const ie=te;this.meanX=ie.meanX,this.stdDevX=ie.stdDevX,this.meanY=ie.meanY,this.stdDevY=ie.stdDevY,this.PBQ=G.checkMatrix(ie.PBQ),this.R2X=ie.R2X}else{if(ee.length!==te.length)throw new RangeError('The number of X rows must be equal to the number of Y rows');const ie=Z.featureNormalize(ee);this.X=ie.result,this.meanX=ie.means,this.stdDevX=ie.std;const ne=Z.featureNormalize(te);this.Y=ne.result,this.meanY=ne.means,this.stdDevY=ne.std}}train(ee){ee===void 0&&(ee={});var te=ee.latentVectors;te===void 0&&(te=Math.min(this.X.length-1,this.X[0].length));var ie=ee.tolerance;ie===void 0&&(ie=1e-5);for(var ne=this.X,oe=this.Y,se=ne.rows,ae=ne.columns,le=oe.rows,de=oe.columns,ce=ne.clone().mul(ne).sum(),ue=oe.clone().mul(oe).sum(),me=te,ge=G.zeros(se,me),pe=G.zeros(ae,me),he=G.zeros(le,me),xe=G.zeros(de,me),fe=G.zeros(me,me),ye=pe.clone(),je=0;Z.norm(oe)>ie&&jeie;){qe=ke.mmul(ze),qe.div(Z.norm(qe)),Se=Me,Me=ne.mmul(qe);var Ce=we.mmul(Me);Ce.div(Z.norm(Ce)),ze=oe.mmul(Ce)}Se=Me;var Ie=ke.mmul(Se),Re=Se.transpose().mmul(Se)[0][0],De=Ie.div(Re),Pe=Z.norm(De);De.div(Pe),Se.mul(Pe),qe.mul(Pe),Ie=ze.transpose().mmul(Se),Re=Se.transpose().mmul(Se)[0][0];var Ve=Ie.div(Re)[0][0];ne.sub(Se.mmul(De.transpose())),oe.sub(Se.clone().mul(Ve).mmul(Ce.transpose())),ge.setColumn(je,Se),pe.setColumn(je,De),he.setColumn(je,ze),xe.setColumn(je,Ce),ye.setColumn(je,qe),fe[je][je]=Ve,je++}je--,ge=ge.subMatrix(0,ge.rows-1,0,je),pe=pe.subMatrix(0,pe.rows-1,0,je),he=he.subMatrix(0,he.rows-1,0,je),xe=xe.subMatrix(0,xe.rows-1,0,je),ye=ye.subMatrix(0,ye.rows-1,0,je),fe=fe.subMatrix(0,je,0,je),this.ssqYcal=ue,this.E=ne,this.F=oe,this.T=ge,this.P=pe,this.U=he,this.Q=xe,this.W=ye,this.B=fe,this.PBQ=pe.mmul(fe).mmul(xe.transpose()),this.R2X=Se.transpose().mmul(Se).mmul(De.transpose().mmul(De)).div(ce)[0][0]}predict(ee){var te=G.checkMatrix(ee);te=te.subRowVector(this.meanX).divRowVector(this.stdDevX);var ie=te.mmul(this.PBQ);return ie=ie.mulRowVector(this.stdDevY).addRowVector(this.meanY),ie}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}}static load(ee){if('PLS'!==ee.name)throw new RangeError('Invalid model: '+ee.name);return new $(!0,ee)}}I.exports=$},function(I,R,D){'use strict';const O=D(6).maybeToPrecision,E=D(13),G=D(4);class Z extends G{constructor($,ee,te){super();if(!0===$)this.A=ee.A,this.C=ee.C,ee.quality&&(this.quality=ee.quality);else{var ne=$.length;if(ne!==ee.length)throw new RangeError('input and output array have a different length');for(var oe=Array(ne),se=0;seMath.abs(te-1)?'':te+' * ')+'x',this.intercept){var ie=Math.abs(this.intercept),ne=ie===this.intercept?'+':'-';ee+=' '+ne+' '+E(ie,$)}}else ee+=E(this.intercept,$);return ee}toLaTeX($){return this.toString($)}static load($){if('TheilSenRegression'!==$.name)throw new TypeError('not a Theil-Sen model');return new Z(!0,$)}}I.exports=Z},function(I,R,D){'use strict';R.array=D(41),R.matrix=D(158)},function(I,R,D){'use strict';function E(xe,fe){'undefined'==typeof fe&&(fe=0);var ye=xe.length,je=xe[0].length,ke,we,be,ve;if(-1===fe){for(ke=[0],we=ye*je,be=0;beqe&&(qe=be[we],Ce=we);je[ke]=Me[Ce]}return je},skewness:function(xe,fe){'undefined'==typeof fe&&(fe=!0);for(var ye=E(xe),je=xe.length,ke=ye.length,we=Array(ke),be=0;beG&&(G=Z[$][ee]);return G},R.min=function(Z){for(var G=Infinity,$=0;$ee&&(ee=Z[te][ie]);return{min:$,max:ee}},R.entropy=function(Z,$){'undefined'==typeof $&&($=0);for(var ee=0,te=Z.length,ie=Z[0].length,ne=0;nece&&(ce=oe[ne],ue=ne);te[ie]=ae[ue]}return te},R.skewness=function(Z,$){'undefined'==typeof $&&($=!0);for(var ee=R.mean(Z),te=Z.length,ie=ee.length,ne=Array(ie),oe=0;oete&&(se+=ee[ae]);if(!(sete&&(le+=$[de]*ee[de]);return le/=se,1e-5>le-te||1e-5>ie-le?void 0:le-tePe)return xe(De)?Re.stylize(RegExp.prototype.toString.call(De),'regexp'):Re.stylize('[Object]','special');Re.seen.push(De);var Xe;return Xe=Fe?oe(Re,De,Pe,Oe,_e):_e.map(function(We){return se(Re,De,Pe,Oe,We,Fe)}),Re.seen.pop(),ae(Xe,Ne,Te)}function ie(Re,De){if(he(De))return Re.stylize('undefined','undefined');if(ge(De)){var Pe='\''+JSON.stringify(De).replace(/^"|"$/g,'').replace(/'/g,'\\\'').replace(/\\"/g,'"')+'\'';return Re.stylize(Pe,'string')}return me(De)?Re.stylize(''+De,'number'):de(De)?Re.stylize(''+De,'boolean'):ce(De)?Re.stylize('null','null'):void 0}function ne(Re){return'['+Error.prototype.toString.call(Re)+']'}function oe(Re,De,Pe,Ve,Ae){for(var _e=[],Oe=0,Le=De.length;OeRe.seen.indexOf(Ne.value)?(Le=ce(Pe)?te(Re,Ne.value,null):te(Re,Ne.value,Pe-1),-1Re?'0'+Re.toString(10):Re.toString(10)}function Me(){var Re=new Date,De=[ve(Re.getHours()),ve(Re.getMinutes()),ve(Re.getSeconds())].join(':');return[Re.getDate(),Ie[Re.getMonth()],De].join(' ')}function ze(Re,De){return Object.prototype.hasOwnProperty.call(Re,De)}var Se=/%[sdj%]/g;R.format=function(Re){if(!ge(Re)){for(var De=[],Pe=0;Pe=Ae)return Le;switch(Le){case'%s':return Ve[Pe++]+'';case'%d':return+Ve[Pe++];case'%j':try{return JSON.stringify(Ve[Pe++])}catch(Ne){return'[Circular]'}default:return Le;}}),Oe=Ve[Pe];Pet&&m.pop()}var a=r[o.dimension],c=n(e,o.obj),d={},g,p,h,j;for(j=0;js&&(o=i,s=l)}return o},n.load=function(e){if('KNN'!==e.modelName)throw new RangeError('The given model is invalid!');return new n(!0,e)},n.prototype.export=function(){return{modelName:'KNN',kdtree:this.kdtree,k:this.k,classes:this.classes}}},function(e){'use strict';e.exports=function(e,t,n){var o=0;const s=n(...t);for(var r=0;rk){z=0;do{for(++z,a=e[k],m=(e[k+1]-a)/(2*n[k]),p=j(m,1),0>m&&(p=-p),e[k]=n[k]/(m+p),e[k+1]=n[k]*(m+p),x=e[k+1],d=a-e[k],g=k+2;g=k;g--)for(y=c,c=w,S=M,a=w*n[g],d=w*m,p=j(m,n[g]),n[g+1]=M*p,M=n[g]/p,w=m/p,m=w*e[g]-M*a,e[g+1]=d+M*(w*a+M*e[g]),h=0;hV*f)}e[k]+=R,n[k]=0}for(g=0;g=p;d--)n[d]=t[d][p-1]/m,c+=n[d]*n[d];for(l=S(c),0=p;d--)a+=n[d]*t[d][i];for(a/=c,d=p;d<=r;d++)t[d][i]-=a*n[d]}for(d=0;d<=r;d++){for(a=0,i=r;i>=p;i--)a+=n[i]*t[d][i];for(a/=c,i=p;i<=r;i++)t[d][i]-=a*n[i]}n[p]=m*n[p],t[p][p-1]=m*l}}for(d=0;d=s+1;p--)if(0!==t[p][p-1]){for(d=p+1;d<=r;d++)n[d]=t[d][p-1];for(i=p;i<=r;i++){for(l=0,d=p;d<=r;d++)l+=n[d]*o[d][i];for(l=l/n[p]/t[p][p-1],d=p;d<=r;d++)o[d][i]+=l*n[d]}}}function l(o,a,e,d,g){var h=o-1,n=0,f=o-1,b=2.220446049250313e-16,R=0,V=0,I=0,p=0,D=0,C=0,P=0,A=0,L,i,j,k,l,m,t,w,x,y,U,_,q,F,O;for(L=0;Lf)&&(e[L]=g[L][L],a[L]=0),i=v(L-1,0);i=n;){for(k=h;k>n&&(C=u(g[k-1][k-1])+u(g[k][k]),0===C&&(C=V),!(u(g[k][k-1])=k&&(P=g[l][l],D=w-P,C=x-P,I=(D*C-t)/g[l+1][l]+g[l][l+1],p=g[l+1][l+1]-P-D-C,D=g[l+2][l+1],C=u(I)+u(p)+u(D),I/=C,p/=C,D/=C,l!==k)&&!(u(g[l][l-1])*(u(p)+u(D))l+2&&(g[L][L-3]=0);for(j=l;j<=h-1&&(F=j!==h-1,j!==l&&(I=g[j][j-1],p=g[j+1][j-1],D=F?g[j+2][j-1]:0,w=u(I)+u(p)+u(D),0!==w&&(I/=w,p/=w,D/=w)),0!==w);j++)if(C=S(I*I+p*p+D*D),0>I&&(C=-C),0!==C){for(j===l?k!==l&&(g[j][j-1]=-g[j][j-1]):g[j][j-1]=-C*w,I+=C,w=I/C,x=p/C,P=D/C,p/=I,D/=I,i=j;ia[L])P=t,C=D;else if(k=L,0===a[L]?g[L][h]=0===t?-D/(b*V):-D/t:(w=g[L][L+1],x=g[L+1][L],p=(e[L]-I)*(e[L]-I)+a[L]*a[L],m=(w*C-P*D)/p,g[L][h]=m,g[L+1][h]=u(w)>u(P)?(-D-t*m)/w:(-C-x*m)/P),m=u(g[L][h]),1p)for(k=h-1,u(g[h][h-1])>u(g[h-1][h])?(g[h-1][h-1]=p/g[h][h-1],g[h-1][h]=-(g[h][h]-I)/g[h][h-1]):(O=c(0,-g[h-1][h],g[h-1][h-1]-I,p),g[h-1][h-1]=O[0],g[h-1][h]=O[1]),g[h][h-1]=0,g[h][h]=1,L=h-2;0<=L;L--){for(y=0,U=0,i=k;i<=h;i++)y+=g[L][i]*g[i][h-1],U+=g[L][i]*g[i][h];if(t=g[L][L]-I,0>a[L])P=t,D=y,C=U;else if(k=L,0===a[L]?(O=c(-y,-U,t,p),g[L][h-1]=O[0],g[L][h]=O[1]):(w=g[L][L+1],x=g[L+1][L],_=(e[L]-I)*(e[L]-I)+a[L]*a[L]-p*p,q=2*(e[L]-I)*p,0===_&&0===q&&(_=b*V*(u(t)+u(p)+u(w)+u(x)+u(P))),O=c(w*D-P*y+p*U,w*C-P*U-p*y,_,q),g[L][h-1]=O[0],g[L][h]=O[1],u(w)>u(P)+u(p)?(g[L+1][h-1]=(-y-t*g[L][h-1]+p*g[L][h])/w,g[L+1][h]=(-U-t*g[L][h]-p*g[L][h-1])/w):(O=c(-D-x*g[L][h-1],-C-x*g[L][h],P,p),g[L+1][h-1]=O[0],g[L+1][h]=O[1])),m=v(u(g[L][h-1]),u(g[L][h])),1f)for(i=L;i=n;i--)for(L=n;L<=f;L++){for(P=0,j=n;j<=M(i,f);j++)P+=d[L][j]*g[j][i];d[L][i]=P}}}function c(e,i,t,n){var o,s;return u(t)>u(n)?(o=n/t,s=t+o*n,[(e+o*i)/s,(i-o*e)/s]):(o=t/n,s=n+o*t,[(o*e+i)/s,(o*i-e)/s])}const m=t(4).Matrix,n=t(26),j=n.hypotenuse,g=n.getFilled2DArray,p={assumeSymmetric:!1};o.prototype={get realEigenvalues(){return this.d},get imaginaryEigenvalues(){return this.e},get eigenvectorMatrix(){return m.isMatrix(this.V)||(this.V=new m(this.V)),this.V},get diagonalMatrix(){var t=this.n,n=this.e,e=this.d,o=new m(t,t),s,i;for(s=0;sn[s]&&(o[s][s-1]=n[s])}return o}},e.exports=o},function(e,i,t){'use strict';function o(e){if(!(this instanceof o))return new o(e);e=r.checkMatrix(e);var t=e.clone(),a=e.rows,l=e.columns,c=Array(l),m,i,u,d;for(u=0;ut[u][u]&&(g=-g),m=u;mu&&(u=g,m=d);else if('function'==typeof a)for(var p=t,h=0,i;h{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const t=e.cutoffs.length,n=Array(t);for(var o=0;o{const i=e.cutoffs.slice();return i[0]=i[1],i}},function(e,i,t){'use strict';function n(e,n,r){var a=new o(e),l=new o(n);a=s.featureNormalize(a).result,l=s.featureNormalize(l).result;var c=a.rows,m=a.columns,u=a.clone().mul(a).sum(),d=a.transpose().mmul(l);d.div(s.norm(d));for(var g=Array(r),h=Array(r),j=Array(r),k=0;ko&&(o=i,t=s);return t}var s=t(0),r=t(27);class a{constructor(e,i){if(!0===e){const e=i;this.meanX=e.meanX,this.stdDevX=e.stdDevX,this.meanY=e.meanY,this.stdDevY=e.stdDevY,this.PBQ=s.checkMatrix(e.PBQ),this.R2X=e.R2X}else{if(e.length!==i.length)throw new RangeError('The number of X rows must be equal to the number of Y rows');const t=r.featureNormalize(e);this.X=t.result,this.meanX=t.means,this.stdDevX=t.std;const n=r.featureNormalize(i);this.Y=n.result,this.meanY=n.means,this.stdDevY=n.std}}train(e){e===void 0&&(e={});var i=e.latentVectors;i===void 0&&(i=M(this.X.length-1,this.X[0].length));var a=e.tolerance;a===void 0&&(a=1e-5);for(var l=this.X,c=this.Y,m=l.rows,d=l.columns,g=c.rows,h=c.columns,j=l.clone().mul(l).sum(),x=c.clone().mul(c).sum(),f=i,n=s.zeros(m,f),y=s.zeros(d,f),v=s.zeros(g,f),S=s.zeros(h,f),z=s.zeros(f,f),R=y.clone(),V=0;r.norm(c)>a&&Va;){var t=k.mmul(A);t.div(r.norm(t)),u=P,P=l.mmul(t);var w=I.mmul(P);w.div(r.norm(w)),A=c.mmul(w)}u=P;var L=k.mmul(u),U=u.transpose().mmul(u)[0][0],_=L.div(U),p=r.norm(_);_.div(p),u.mul(p),t.mul(p),L=A.transpose().mmul(u),U=u.transpose().mmul(u)[0][0];var q=L.div(U)[0][0];l.sub(u.mmul(_.transpose())),c.sub(u.clone().mul(q).mmul(w.transpose())),n.setColumn(V,u),y.setColumn(V,_),v.setColumn(V,A),S.setColumn(V,w),R.setColumn(V,t),z[V][V]=q,V++}V--,n=n.subMatrix(0,n.rows-1,0,V),y=y.subMatrix(0,y.rows-1,0,V),v=v.subMatrix(0,v.rows-1,0,V),S=S.subMatrix(0,S.rows-1,0,V),R=R.subMatrix(0,R.rows-1,0,V),z=z.subMatrix(0,V,0,V),this.ssqYcal=x,this.E=l,this.F=c,this.T=n,this.P=y,this.U=v,this.Q=S,this.W=R,this.B=z,this.PBQ=y.mmul(z).mmul(S.transpose()),this.R2X=u.transpose().mmul(u).mmul(_.transpose().mmul(_)).div(j)[0][0]}predict(e){var i=s.checkMatrix(e);i=i.subRowVector(this.meanX).divRowVector(this.stdDevX);var t=i.mmul(this.PBQ);return t=t.mulRowVector(this.stdDevY).addRowVector(this.meanY),t}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}}static load(e){if('PLS'!==e.name)throw new RangeError('Invalid model: '+e.name);return new a(!0,e)}}e.exports=a},function(e,i){'use strict';i.a=function(e,i){if(!Array.isArray(e)||!Array.isArray(i))throw new TypeError('x and y must be arrays');if(e.length!==i.length)throw new RangeError('x and y arrays must have the same length')}},function(e,i){'use strict';i.a=function(e,i){return 0>e?(e=0-e,'number'==typeof i?'- '+e.toPrecision(i):'- '+e.toString()):'number'==typeof i?e.toPrecision(i):e.toString()}},function(e,i,t){'use strict';function n(e,i,t){const o=i.length,n=Array(o);for(let r=0;rk){R=0;do{for(++R,d=e[k],m=(e[k+1]-d)/(2*n[k]),p=t.i(x.a)(m,1),0>m&&(p=-p),e[k]=n[k]/(m+p),e[k+1]=n[k]*(m+p),w=e[k+1],g=d-e[k],h=k+2;h=k;h--)for(b=c,c=y,z=S,d=y*n[h],g=y*m,p=t.i(x.a)(m,n[h]),n[h+1]=S*p,S=n[h]/p,y=m/p,m=y*e[h]-S*d,e[h+1]=g+S*(y*d+S*e[h]),j=0;jI*f)}e[k]+=V,n[k]=0}for(h=0;h=p;d--)n[d]=t[d][p-1]/m,c+=n[d]*n[d];for(l=S(c),0=p;d--)a+=n[d]*t[d][i];for(a/=c,d=p;d<=r;d++)t[d][i]-=a*n[d]}for(d=0;d<=r;d++){for(a=0,i=r;i>=p;i--)a+=n[i]*t[d][i];for(a/=c,i=p;i<=r;i++)t[d][i]-=a*n[i]}n[p]=m*n[p],t[p][p-1]=m*l}}for(d=0;d=s+1;p--)if(0!==t[p][p-1]){for(d=p+1;d<=r;d++)n[d]=t[d][p-1];for(i=p;i<=r;i++){for(l=0,d=p;d<=r;d++)l+=n[d]*o[d][i];for(l=l/n[p]/t[p][p-1],d=p;d<=r;d++)o[d][i]+=l*n[d]}}}function l(o,a,e,d,g){var h=o-1,n=0,f=o-1,b=2.220446049250313e-16,R=0,V=0,I=0,p=0,D=0,C=0,P=0,A=0,L,i,j,k,l,m,t,w,x,y,U,_,q,F,O;for(L=0;Lf)&&(e[L]=g[L][L],a[L]=0),i=v(L-1,0);i=n;){for(k=h;k>n&&(C=u(g[k-1][k-1])+u(g[k][k]),0===C&&(C=V),!(u(g[k][k-1])=k&&(P=g[l][l],D=w-P,C=x-P,I=(D*C-t)/g[l+1][l]+g[l][l+1],p=g[l+1][l+1]-P-D-C,D=g[l+2][l+1],C=u(I)+u(p)+u(D),I/=C,p/=C,D/=C,l!==k)&&!(u(g[l][l-1])*(u(p)+u(D))l+2&&(g[L][L-3]=0);for(j=l;j<=h-1&&(F=j!==h-1,j!==l&&(I=g[j][j-1],p=g[j+1][j-1],D=F?g[j+2][j-1]:0,w=u(I)+u(p)+u(D),0!==w&&(I/=w,p/=w,D/=w)),0!==w);j++)if(C=S(I*I+p*p+D*D),0>I&&(C=-C),0!==C){for(j===l?k!==l&&(g[j][j-1]=-g[j][j-1]):g[j][j-1]=-C*w,I+=C,w=I/C,x=p/C,P=D/C,p/=I,D/=I,i=j;ia[L])P=t,C=D;else if(k=L,0===a[L]?g[L][h]=0===t?-D/(b*V):-D/t:(w=g[L][L+1],x=g[L+1][L],p=(e[L]-I)*(e[L]-I)+a[L]*a[L],m=(w*C-P*D)/p,g[L][h]=m,g[L+1][h]=u(w)>u(P)?(-D-t*m)/w:(-C-x*m)/P),m=u(g[L][h]),1p)for(k=h-1,u(g[h][h-1])>u(g[h-1][h])?(g[h-1][h-1]=p/g[h][h-1],g[h-1][h]=-(g[h][h]-I)/g[h][h-1]):(O=c(0,-g[h-1][h],g[h-1][h-1]-I,p),g[h-1][h-1]=O[0],g[h-1][h]=O[1]),g[h][h-1]=0,g[h][h]=1,L=h-2;0<=L;L--){for(y=0,U=0,i=k;i<=h;i++)y+=g[L][i]*g[i][h-1],U+=g[L][i]*g[i][h];if(t=g[L][L]-I,0>a[L])P=t,D=y,C=U;else if(k=L,0===a[L]?(O=c(-y,-U,t,p),g[L][h-1]=O[0],g[L][h]=O[1]):(w=g[L][L+1],x=g[L+1][L],_=(e[L]-I)*(e[L]-I)+a[L]*a[L]-p*p,q=2*(e[L]-I)*p,0===_&&0===q&&(_=b*V*(u(t)+u(p)+u(w)+u(x)+u(P))),O=c(w*D-P*y+p*U,w*C-P*U-p*y,_,q),g[L][h-1]=O[0],g[L][h]=O[1],u(w)>u(P)+u(p)?(g[L+1][h-1]=(-y-t*g[L][h-1]+p*g[L][h])/w,g[L+1][h]=(-U-t*g[L][h]-p*g[L][h-1])/w):(O=c(-D-x*g[L][h-1],-C-x*g[L][h],P,p),g[L+1][h-1]=O[0],g[L+1][h]=O[1])),m=v(u(g[L][h-1]),u(g[L][h])),1f)for(i=L;i=n;i--)for(L=n;L<=f;L++){for(P=0,j=n;j<=M(i,f);j++)P+=d[L][j]*g[j][i];d[L][i]=P}}}function c(e,i,t,n){var o,s;return u(t)>u(n)?(o=n/t,s=t+o*n,[(e+o*i)/s,(i-o*e)/s]):(o=t/n,s=n+o*t,[(o*e+i)/s,(o*i-e)/s])}var m=t(5),x=t(30);const g={assumeSymmetric:!1};o.prototype={get realEigenvalues(){return this.d},get imaginaryEigenvalues(){return this.e},get eigenvectorMatrix(){return m.a.isMatrix(this.V)||(this.V=new m.a(this.V)),this.V},get diagonalMatrix(){var t=this.n,n=this.e,e=this.d,o=new m.a(t,t),s,i;for(s=0;sn[s]&&(o[s][s-1]=n[s])}return o}}},function(e,i,t){'use strict';i.a=function(e,i){return e=n.a.checkMatrix(e),i=n.a.checkMatrix(i),e.isSquare()?new o.a(e).solve(i):new s.a(e).solve(i)};var n=t(5),o=t(29),s=t(66)},function(e,i,t){'use strict';var n=t(5);t.d(i,'a',function(){return n.a});var o=t(28),s=t(205);t.d(i,'b',function(){return s.a});var r=t(67),a=t(204),l=t(203),c=t(29),m=t(66)},function(){Symbol.species||(Symbol.species=Symbol.for('@@species'))},function(e,i,t){'use strict';var n=t(10);class o extends n.a{constructor(e,i){super(e,e.rows,1),this.column=i}set(e,i,t){return this.matrix.set(e,this.column,t),this}get(e){return this.matrix.get(e,this.column)}}i.a=o},function(e,i,t){'use strict';var n=t(10);class o extends n.a{constructor(e){super(e,e.rows,e.columns)}set(e,i,t){return this.matrix.set(e,this.columns-i-1,t),this}get(e,i){return this.matrix.get(e,this.columns-i-1)}}i.a=o},function(e,i,t){'use strict';var n=t(10);class o extends n.a{constructor(e){super(e,e.rows,e.columns)}set(e,i,t){return this.matrix.set(this.rows-e-1,i,t),this}get(e,i){return this.matrix.get(this.rows-e-1,i)}}i.a=o},function(e,i,t){'use strict';var n=t(10);class o extends n.a{constructor(e,i){super(e,1,e.columns),this.row=i}set(e,i,t){return this.matrix.set(this.row,i,t),this}get(e,i){return this.matrix.get(this.row,i)}}i.a=o},function(e,i,t){'use strict';var n=t(10),o=t(17);class s extends n.a{constructor(e,i,n){var s=t.i(o.i)(e,i,n);super(e,s.row.length,s.column.length),this.rowIndices=s.row,this.columnIndices=s.column}set(e,i,t){return this.matrix.set(this.rowIndices[e],this.columnIndices[i],t),this}get(e,i){return this.matrix.get(this.rowIndices[e],this.columnIndices[i])}}i.a=s},function(e,i,t){'use strict';var n=t(10),o=t(17);class s extends n.a{constructor(e,i,n,s,r){t.i(o.h)(e,i,n,s,r),super(e,n-i+1,r-s+1),this.startRow=i,this.startColumn=s}set(e,i,t){return this.matrix.set(this.startRow+e,this.startColumn+i,t),this}get(e,i){return this.matrix.get(this.startRow+e,this.startColumn+i)}}i.a=s},function(e,i,t){'use strict';var n=t(10);class o extends n.a{constructor(e){super(e,e.columns,e.rows)}set(e,i,t){return this.matrix.set(i,e,t),this}get(e,i){return this.matrix.get(i,e)}}i.a=o},function(e,i,t){'use strict';function n(e,t,o){const r=t.length,n=Array(r),c=Array(r);for(let a=0;ak){R=0;do{for(++R,d=e[k],m=(e[k+1]-d)/(2*n[k]),p=t.i(x.a)(m,1),0>m&&(p=-p),e[k]=n[k]/(m+p),e[k+1]=n[k]*(m+p),w=e[k+1],g=d-e[k],h=k+2;h=k;h--)for(b=c,c=y,z=S,d=y*n[h],g=y*m,p=t.i(x.a)(m,n[h]),n[h+1]=S*p,S=n[h]/p,y=m/p,m=y*e[h]-S*d,e[h+1]=g+S*(y*d+S*e[h]),j=0;jI*f)}e[k]+=V,n[k]=0}for(h=0;h=p;d--)n[d]=t[d][p-1]/m,c+=n[d]*n[d];for(l=S(c),0=p;d--)a+=n[d]*t[d][i];for(a/=c,d=p;d<=r;d++)t[d][i]-=a*n[d]}for(d=0;d<=r;d++){for(a=0,i=r;i>=p;i--)a+=n[i]*t[d][i];for(a/=c,i=p;i<=r;i++)t[d][i]-=a*n[i]}n[p]=m*n[p],t[p][p-1]=m*l}}for(d=0;d=s+1;p--)if(0!==t[p][p-1]){for(d=p+1;d<=r;d++)n[d]=t[d][p-1];for(i=p;i<=r;i++){for(l=0,d=p;d<=r;d++)l+=n[d]*o[d][i];for(l=l/n[p]/t[p][p-1],d=p;d<=r;d++)o[d][i]+=l*n[d]}}}function l(o,a,e,d,g){var h=o-1,n=0,f=o-1,b=2.220446049250313e-16,R=0,V=0,I=0,p=0,D=0,C=0,P=0,A=0,L,i,j,k,l,m,t,w,x,y,U,_,q,F,O;for(L=0;Lf)&&(e[L]=g[L][L],a[L]=0),i=v(L-1,0);i=n;){for(k=h;k>n&&(C=u(g[k-1][k-1])+u(g[k][k]),0===C&&(C=V),!(u(g[k][k-1])=k&&(P=g[l][l],D=w-P,C=x-P,I=(D*C-t)/g[l+1][l]+g[l][l+1],p=g[l+1][l+1]-P-D-C,D=g[l+2][l+1],C=u(I)+u(p)+u(D),I/=C,p/=C,D/=C,l!==k)&&!(u(g[l][l-1])*(u(p)+u(D))l+2&&(g[L][L-3]=0);for(j=l;j<=h-1&&(F=j!==h-1,j!==l&&(I=g[j][j-1],p=g[j+1][j-1],D=F?g[j+2][j-1]:0,w=u(I)+u(p)+u(D),0!==w&&(I/=w,p/=w,D/=w)),0!==w);j++)if(C=S(I*I+p*p+D*D),0>I&&(C=-C),0!==C){for(j===l?k!==l&&(g[j][j-1]=-g[j][j-1]):g[j][j-1]=-C*w,I+=C,w=I/C,x=p/C,P=D/C,p/=I,D/=I,i=j;ia[L])P=t,C=D;else if(k=L,0===a[L]?g[L][h]=0===t?-D/(b*V):-D/t:(w=g[L][L+1],x=g[L+1][L],p=(e[L]-I)*(e[L]-I)+a[L]*a[L],m=(w*C-P*D)/p,g[L][h]=m,g[L+1][h]=u(w)>u(P)?(-D-t*m)/w:(-C-x*m)/P),m=u(g[L][h]),1p)for(k=h-1,u(g[h][h-1])>u(g[h-1][h])?(g[h-1][h-1]=p/g[h][h-1],g[h-1][h]=-(g[h][h]-I)/g[h][h-1]):(O=c(0,-g[h-1][h],g[h-1][h-1]-I,p),g[h-1][h-1]=O[0],g[h-1][h]=O[1]),g[h][h-1]=0,g[h][h]=1,L=h-2;0<=L;L--){for(y=0,U=0,i=k;i<=h;i++)y+=g[L][i]*g[i][h-1],U+=g[L][i]*g[i][h];if(t=g[L][L]-I,0>a[L])P=t,D=y,C=U;else if(k=L,0===a[L]?(O=c(-y,-U,t,p),g[L][h-1]=O[0],g[L][h]=O[1]):(w=g[L][L+1],x=g[L+1][L],_=(e[L]-I)*(e[L]-I)+a[L]*a[L]-p*p,q=2*(e[L]-I)*p,0===_&&0===q&&(_=b*V*(u(t)+u(p)+u(w)+u(x)+u(P))),O=c(w*D-P*y+p*U,w*C-P*U-p*y,_,q),g[L][h-1]=O[0],g[L][h]=O[1],u(w)>u(P)+u(p)?(g[L+1][h-1]=(-y-t*g[L][h-1]+p*g[L][h])/w,g[L+1][h]=(-U-t*g[L][h]-p*g[L][h-1])/w):(O=c(-D-x*g[L][h-1],-C-x*g[L][h],P,p),g[L+1][h-1]=O[0],g[L+1][h]=O[1])),m=v(u(g[L][h-1]),u(g[L][h])),1f)for(i=L;i=n;i--)for(L=n;L<=f;L++){for(P=0,j=n;j<=M(i,f);j++)P+=d[L][j]*g[j][i];d[L][i]=P}}}function c(e,i,t,n){var o,s;return u(t)>u(n)?(o=n/t,s=t+o*n,[(e+o*i)/s,(i-o*e)/s]):(o=t/n,s=n+o*t,[(o*e+i)/s,(o*i-e)/s])}var m=t(6),x=t(33);const g={assumeSymmetric:!1};o.prototype={get realEigenvalues(){return this.d},get imaginaryEigenvalues(){return this.e},get eigenvectorMatrix(){return m.a.isMatrix(this.V)||(this.V=new m.a(this.V)),this.V},get diagonalMatrix(){var t=this.n,n=this.e,e=this.d,o=new m.a(t,t),s,i;for(s=0;sn[s]&&(o[s][s-1]=n[s])}return o}}},function(e,i,t){'use strict';i.a=function(e,i){return e=n.a.checkMatrix(e),i=n.a.checkMatrix(i),e.isSquare()?new o.a(e).solve(i):new s.a(e).solve(i)};var n=t(6),o=t(32),s=t(69)},function(e,i,t){'use strict';var n=t(6),o=t(31),s=t(218);t.d(i,'a',function(){return s.a});var r=t(70),a=t(217),l=t(216),c=t(32),m=t(69)},function(){Symbol.species||(Symbol.species=Symbol.for('@@species'))},function(e,i,t){'use strict';var n=t(11);class o extends n.a{constructor(e,i){super(e,e.rows,1),this.column=i}set(e,i,t){return this.matrix.set(e,this.column,t),this}get(e){return this.matrix.get(e,this.column)}}i.a=o},function(e,i,t){'use strict';var n=t(11);class o extends n.a{constructor(e){super(e,e.rows,e.columns)}set(e,i,t){return this.matrix.set(e,this.columns-i-1,t),this}get(e,i){return this.matrix.get(e,this.columns-i-1)}}i.a=o},function(e,i,t){'use strict';var n=t(11);class o extends n.a{constructor(e){super(e,e.rows,e.columns)}set(e,i,t){return this.matrix.set(this.rows-e-1,i,t),this}get(e,i){return this.matrix.get(this.rows-e-1,i)}}i.a=o},function(e,i,t){'use strict';var n=t(11);class o extends n.a{constructor(e,i){super(e,1,e.columns),this.row=i}set(e,i,t){return this.matrix.set(this.row,i,t),this}get(e,i){return this.matrix.get(this.row,i)}}i.a=o},function(e,i,t){'use strict';var n=t(11),o=t(18);class s extends n.a{constructor(e,i,n){var s=t.i(o.i)(e,i,n);super(e,s.row.length,s.column.length),this.rowIndices=s.row,this.columnIndices=s.column}set(e,i,t){return this.matrix.set(this.rowIndices[e],this.columnIndices[i],t),this}get(e,i){return this.matrix.get(this.rowIndices[e],this.columnIndices[i])}}i.a=s},function(e,i,t){'use strict';var n=t(11),o=t(18);class s extends n.a{constructor(e,i,n,s,r){t.i(o.h)(e,i,n,s,r),super(e,n-i+1,r-s+1),this.startRow=i,this.startColumn=s}set(e,i,t){return this.matrix.set(this.startRow+e,this.startColumn+i,t),this}get(e,i){return this.matrix.get(this.startRow+e,this.startColumn+i)}}i.a=s},function(e,i,t){'use strict';var n=t(11);class o extends n.a{constructor(e){super(e,e.columns,e.rows)}set(e,i,t){return this.matrix.set(i,e,t),this}get(e,i){return this.matrix.get(i,e)}}i.a=o},function(e,i,t){'use strict';function n(e,t,n,r){let c=Array(r);for(let i=0;ie.residual-i.residual);var i=e.length,t=c(i/2);return 0==i%2?e[t-1]:e[t]}Object.defineProperty(i,'__esModule',{value:!0});var m=t(14),u=t(219);class d extends m.a{constructor(e,i,o){super(),!0===e?(this.degree=i.degree,this.powers=i.powers,this.coefficients=i.coefficients):(t.i(m.b)(e,i),n(this,e,i,o))}toJSON(){return{name:'robustPolynomialRegression',degree:this.degree,powers:this.powers,coefficients:this.coefficients}}_predict(e){return a(e,this.powers,this.coefficients)}toString(e){return this._toFormula(e,!1)}toLaTeX(e){return this._toFormula(e,!0)}_toFormula(e,i){let n='^',o='',s=' * ';i&&(n='^{',o='}',s='');let r='',a='';for(let l=0;lu(n-1)?'':n+' * ')+'x',this.intercept){var s=u(this.intercept),r=s===this.intercept?'+':'-';i+=' '+r+' '+t.i(o.c)(s,e)}}else i+=t.i(o.c)(this.intercept,e);return i}toLaTeX(e){return this.toString(e)}static load(e){if('TheilSenRegression'!==e.name)throw new TypeError('not a Theil-Sen model');return new l(!0,e)}}i['default']=l},function(e,i,t){'use strict';function n(e){if(!(this instanceof n))return new n(e);if(e=o.a.checkMatrix(e),!e.isSymmetric())throw new Error('Matrix is not symmetric');var t=e,r=t.rows,a=new o.a(r,r),l=!0,c,i,m;for(i=0;ik){R=0;do{for(++R,d=e[k],m=(e[k+1]-d)/(2*n[k]),p=t.i(x.a)(m,1),0>m&&(p=-p),e[k]=n[k]/(m+p),e[k+1]=n[k]*(m+p),w=e[k+1],g=d-e[k],h=k+2;h=k;h--)for(b=c,c=y,z=S,d=y*n[h],g=y*m,p=t.i(x.a)(m,n[h]),n[h+1]=S*p,S=n[h]/p,y=m/p,m=y*e[h]-S*d,e[h+1]=g+S*(y*d+S*e[h]),j=0;jI*f)}e[k]+=V,n[k]=0}for(h=0;h=p;d--)n[d]=t[d][p-1]/m,c+=n[d]*n[d];for(l=S(c),0=p;d--)a+=n[d]*t[d][i];for(a/=c,d=p;d<=r;d++)t[d][i]-=a*n[d]}for(d=0;d<=r;d++){for(a=0,i=r;i>=p;i--)a+=n[i]*t[d][i];for(a/=c,i=p;i<=r;i++)t[d][i]-=a*n[i]}n[p]=m*n[p],t[p][p-1]=m*l}}for(d=0;d=s+1;p--)if(0!==t[p][p-1]){for(d=p+1;d<=r;d++)n[d]=t[d][p-1];for(i=p;i<=r;i++){for(l=0,d=p;d<=r;d++)l+=n[d]*o[d][i];for(l=l/n[p]/t[p][p-1],d=p;d<=r;d++)o[d][i]+=l*n[d]}}}function l(o,a,e,d,g){var h=o-1,n=0,f=o-1,b=2.220446049250313e-16,R=0,V=0,I=0,p=0,D=0,C=0,P=0,A=0,L,i,j,k,l,m,t,w,x,y,U,_,q,F,O;for(L=0;Lf)&&(e[L]=g[L][L],a[L]=0),i=v(L-1,0);i=n;){for(k=h;k>n&&(C=u(g[k-1][k-1])+u(g[k][k]),0===C&&(C=V),!(u(g[k][k-1])=k&&(P=g[l][l],D=w-P,C=x-P,I=(D*C-t)/g[l+1][l]+g[l][l+1],p=g[l+1][l+1]-P-D-C,D=g[l+2][l+1],C=u(I)+u(p)+u(D),I/=C,p/=C,D/=C,l!==k)&&!(u(g[l][l-1])*(u(p)+u(D))l+2&&(g[L][L-3]=0);for(j=l;j<=h-1&&(F=j!==h-1,j!==l&&(I=g[j][j-1],p=g[j+1][j-1],D=F?g[j+2][j-1]:0,w=u(I)+u(p)+u(D),0!==w&&(I/=w,p/=w,D/=w)),0!==w);j++)if(C=S(I*I+p*p+D*D),0>I&&(C=-C),0!==C){for(j===l?k!==l&&(g[j][j-1]=-g[j][j-1]):g[j][j-1]=-C*w,I+=C,w=I/C,x=p/C,P=D/C,p/=I,D/=I,i=j;ia[L])P=t,C=D;else if(k=L,0===a[L]?g[L][h]=0===t?-D/(b*V):-D/t:(w=g[L][L+1],x=g[L+1][L],p=(e[L]-I)*(e[L]-I)+a[L]*a[L],m=(w*C-P*D)/p,g[L][h]=m,g[L+1][h]=u(w)>u(P)?(-D-t*m)/w:(-C-x*m)/P),m=u(g[L][h]),1p)for(k=h-1,u(g[h][h-1])>u(g[h-1][h])?(g[h-1][h-1]=p/g[h][h-1],g[h-1][h]=-(g[h][h]-I)/g[h][h-1]):(O=c(0,-g[h-1][h],g[h-1][h-1]-I,p),g[h-1][h-1]=O[0],g[h-1][h]=O[1]),g[h][h-1]=0,g[h][h]=1,L=h-2;0<=L;L--){for(y=0,U=0,i=k;i<=h;i++)y+=g[L][i]*g[i][h-1],U+=g[L][i]*g[i][h];if(t=g[L][L]-I,0>a[L])P=t,D=y,C=U;else if(k=L,0===a[L]?(O=c(-y,-U,t,p),g[L][h-1]=O[0],g[L][h]=O[1]):(w=g[L][L+1],x=g[L+1][L],_=(e[L]-I)*(e[L]-I)+a[L]*a[L]-p*p,q=2*(e[L]-I)*p,0===_&&0===q&&(_=b*V*(u(t)+u(p)+u(w)+u(x)+u(P))),O=c(w*D-P*y+p*U,w*C-P*U-p*y,_,q),g[L][h-1]=O[0],g[L][h]=O[1],u(w)>u(P)+u(p)?(g[L+1][h-1]=(-y-t*g[L][h-1]+p*g[L][h])/w,g[L+1][h]=(-U-t*g[L][h]-p*g[L][h-1])/w):(O=c(-D-x*g[L][h-1],-C-x*g[L][h],P,p),g[L+1][h-1]=O[0],g[L+1][h]=O[1])),m=v(u(g[L][h-1]),u(g[L][h])),1f)for(i=L;i=n;i--)for(L=n;L<=f;L++){for(P=0,j=n;j<=M(i,f);j++)P+=d[L][j]*g[j][i];d[L][i]=P}}}function c(e,i,t,n){var o,s;return u(t)>u(n)?(o=n/t,s=t+o*n,[(e+o*i)/s,(i-o*e)/s]):(o=t/n,s=n+o*t,[(o*e+i)/s,(o*i-e)/s])}var m=t(7),x=t(37);const g={assumeSymmetric:!1};o.prototype={get realEigenvalues(){return this.d},get imaginaryEigenvalues(){return this.e},get eigenvectorMatrix(){return m.a.isMatrix(this.V)||(this.V=new m.a(this.V)),this.V},get diagonalMatrix(){var t=this.n,n=this.e,e=this.d,o=new m.a(t,t),s,i;for(s=0;sn[s]&&(o[s][s-1]=n[s])}return o}},i.a=o},function(e,i,t){'use strict';function n(e,i){return e=o.a.checkMatrix(e),i=o.a.checkMatrix(i),e.isSquare()?new s.a(e).solve(i):new r.a(e).solve(i)}i.b=function(e){return e=o.a.checkMatrix(e),n(e,o.a.eye(e.rows))},i.a=n;var o=t(7),s=t(36),r=t(71)},function(){Symbol.species||(Symbol.species=Symbol.for('@@species'))},function(e,i,t){'use strict';var n=t(12);class o extends n.a{constructor(e,i){super(e,e.rows,1),this.column=i}set(e,i,t){return this.matrix.set(e,this.column,t),this}get(e){return this.matrix.get(e,this.column)}}i.a=o},function(e,i,t){'use strict';var n=t(12);class o extends n.a{constructor(e){super(e,e.rows,e.columns)}set(e,i,t){return this.matrix.set(e,this.columns-i-1,t),this}get(e,i){return this.matrix.get(e,this.columns-i-1)}}i.a=o},function(e,i,t){'use strict';var n=t(12);class o extends n.a{constructor(e){super(e,e.rows,e.columns)}set(e,i,t){return this.matrix.set(this.rows-e-1,i,t),this}get(e,i){return this.matrix.get(this.rows-e-1,i)}}i.a=o},function(e,i,t){'use strict';var n=t(12);class o extends n.a{constructor(e,i){super(e,1,e.columns),this.row=i}set(e,i,t){return this.matrix.set(this.row,i,t),this}get(e,i){return this.matrix.get(this.row,i)}}i.a=o},function(e,i,t){'use strict';var n=t(12),o=t(19);class s extends n.a{constructor(e,i,n){var s=t.i(o.i)(e,i,n);super(e,s.row.length,s.column.length),this.rowIndices=s.row,this.columnIndices=s.column}set(e,i,t){return this.matrix.set(this.rowIndices[e],this.columnIndices[i],t),this}get(e,i){return this.matrix.get(this.rowIndices[e],this.columnIndices[i])}}i.a=s},function(e,i,t){'use strict';var n=t(12),o=t(19);class s extends n.a{constructor(e,i,n,s,r){t.i(o.h)(e,i,n,s,r),super(e,n-i+1,r-s+1),this.startRow=i,this.startColumn=s}set(e,i,t){return this.matrix.set(this.startRow+e,this.startColumn+i,t),this}get(e,i){return this.matrix.get(this.startRow+e,this.startColumn+i)}}i.a=s},function(e,i,t){'use strict';var n=t(12);class o extends n.a{constructor(e){super(e,e.columns,e.rows)}set(e,i,t){return this.matrix.set(i,e,t),this}get(e,i){return this.matrix.get(i,e)}}i.a=o},function(e,i,t){'use strict';const n=t(73),o=n.Matrix,s=n.solve,r=t(20),a=t(38),l={lambda:0.1,kernelType:'gaussian',kernelOptions:{},computeCoefficient:!1};class c extends a{constructor(e,i,t){if(super(),!0===e)this.alpha=i.alpha,this.inputs=i.inputs,this.kernelType=i.kernelType,this.kernelOptions=i.kernelOptions,this.kernel=new r(i.kernelType,i.kernelOptions),i.quality&&(this.quality=i.quality);else{t=Object.assign({},l,t);const a=new r(t.kernelType,t.kernelOptions),c=a.compute(e),m=e.length;c.add(o.eye(m,m).mul(t.lambda)),this.alpha=s(c,i),this.inputs=e,this.kernelType=t.kernelType,this.kernelOptions=t.kernelOptions,this.kernel=a,t.computeQuality&&(this.quality=this.modelQuality(e,i))}}_predict(e){return this.kernel.compute([e],this.inputs).mmul(this.alpha)[0]}toJSON(){var e={name:'kernelRidgeRegression',alpha:this.alpha,inputs:this.inputs,kernelType:this.kernelType,kernelOptions:this.kernelOptions};return this.quality&&(e.quality=this.quality),e}static load(e){if('kernelRidgeRegression'!==e.name)throw new TypeError('not a KRR model');return new c(!0,e)}}e.exports=c},function(e,i,t){'use strict';function n(e,t){for(var n=e.clone(),o=0;oe?(e=-1*e,i?'- '+e.toPrecision(i):'- '+e.toString()):i?e.toPrecision(i):e.toString()}},function(e,i,t){'use strict';i.array=t(74),i.matrix=t(246)},function(e,i,t){'use strict';function o(e,t){'undefined'==typeof t&&(t=0);var n=e.length,o=e[0].length,s,r,a,i;if(-1===t){for(s=[0],r=n*o,a=0;au&&(u=r[i],d=i);o[s]=l[d]}return o},skewness:function(e,t){'undefined'==typeof t&&(t=!0);for(var s=o(e),c=e.length,n=s.length,l=Array(n),m=0;mt&&(t=e[n][i]);return t},t.min=function(e){for(var t=Infinity,n=0;nn&&(n=e[o][i]);return{min:t,max:n}},t.entropy=function(e,t){'undefined'==typeof t&&(t=0);for(var n=0,o=e.length,r=e[0].length,a=0;au&&(u=r[i],d=i);o[s]=l[d]}return o},t.skewness=function(e,o){'undefined'==typeof o&&(o=!0);for(var s=t.mean(e),c=e.length,n=s.length,l=Array(n),m=0;mo&&(l+=n[c]);if(!(lo&&(i+=e[m]*n[m]);return i/=l,1e-5>i-o||1e-5>s-i?void 0:i-oo)return f(t)?e.stylize(RegExp.prototype.toString.call(t),'regexp'):e.stylize('[Object]','special');e.seen.push(t);var n;return n=y?u(e,t,o,j,h):h.map(function(i){return d(e,t,o,j,i,y)}),e.seen.pop(),g(n,x,S)}function c(e,i){if(x(i))return e.stylize('undefined','undefined');if(w(i)){var t='\''+JSON.stringify(i).replace(/^"|"$/g,'').replace(/'/g,'\\\'').replace(/\\"/g,'"')+'\'';return e.stylize(t,'string')}return k(i)?e.stylize(''+i,'number'):h(i)?e.stylize(''+i,'boolean'):j(i)?e.stylize('null','null'):void 0}function m(e){return'['+Error.prototype.toString.call(e)+']'}function u(e,t,n,o,s){for(var r=[],a=0,i=t.length;ae.seen.indexOf(c.value)?(a=j(t)?l(e,c.value,null):l(e,c.value,t-1),-1e?'0'+e.toString(10):e.toString(10)}function R(){var e=new Date,i=[z(e.getHours()),z(e.getMinutes()),z(e.getSeconds())].join(':');return[e.getDate(),P[e.getMonth()],i].join(' ')}function V(e,i){return Object.prototype.hasOwnProperty.call(e,i)}var I=/%[sdj%]/g;i.format=function(e){if(!w(e)){for(var t=[],n=0;n=s)return e;switch(e){case'%s':return i[n++]+'';case'%d':return+i[n++];case'%j':try{return JSON.stringify(i[n++])}catch(e){return'[Circular]'}default:return e;}}),a=i[n];n 0) { // Create an empty matrix\n super(nRows);\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (i = 0; i < nRows; i++) {\n this[i] = new Array(nColumns);\n }\n } else {\n throw new TypeError('nColumns must be a positive integer');\n }\n } else if (Array.isArray(nRows)) { // Copy the values from the 2D array\n const matrix = nRows;\n nRows = matrix.length;\n nColumns = matrix[0].length;\n if (typeof nColumns !== 'number' || nColumns === 0) {\n throw new TypeError('Data must be a 2D array with at least one element');\n }\n super(nRows);\n for (i = 0; i < nRows; i++) {\n if (matrix[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this[i] = [].concat(matrix[i]);\n }\n } else {\n throw new TypeError('First argument must be a positive number or an array');\n }\n this.rows = nRows;\n this.columns = nColumns;\n return this;\n }\n\n set(rowIndex, columnIndex, value) {\n this[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this[rowIndex][columnIndex];\n }\n\n /**\n * Creates an exact and independent copy of the matrix\n * @return {Matrix}\n */\n clone() {\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\n for (var row = 0; row < this.rows; row++) {\n for (var column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n /**\n * Removes a row from the given index\n * @param {number} index - Row index\n * @return {Matrix} this\n */\n removeRow(index) {\n util.checkRowIndex(this, index);\n if (this.rows === 1) {\n throw new RangeError('A matrix cannot have less than one row');\n }\n this.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n /**\n * Adds a row at the given index\n * @param {number} [index = this.rows] - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n util.checkRowIndex(this, index, true);\n array = util.checkRowVector(this, array, true);\n this.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\n\n /**\n * Removes a column from the given index\n * @param {number} index - Column index\n * @return {Matrix} this\n */\n removeColumn(index) {\n util.checkColumnIndex(this, index);\n if (this.columns === 1) {\n throw new RangeError('A matrix cannot have less than one column');\n }\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 1);\n }\n this.columns -= 1;\n return this;\n }\n\n /**\n * Adds a column at the given index\n * @param {number} [index = this.columns] - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addColumn(index, array) {\n if (typeof array === 'undefined') {\n array = index;\n index = this.columns;\n }\n util.checkColumnIndex(this, index, true);\n array = util.checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 0, array[i]);\n }\n this.columns += 1;\n return this;\n }\n}\n\nexports.Matrix = Matrix;\nMatrix.abstractMatrix = abstractMatrix;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/matrix.js\n// module id = 3\n// module chunks = 0","'use strict';\n\nclass BaseRegression {\n predict(x) {\n var y2;\n if (Array.isArray(x)) {\n y2 = new Array(x.length);\n for (var i = 0; i < x.length; i++) {\n y2[i] = this._predict(x[i]);\n }\n } else if (Number.isFinite(x)) {\n y2 = this._predict(x);\n } else {\n throw new TypeError('x must be a number or array');\n }\n return y2;\n }\n\n _predict() {\n throw new Error('_compute not 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 modelQuality(x, y) {\n let n = x.length;\n var y2 = new Array(n);\n for (let i = 0; i < n; i++) {\n y2[i] = this._predict(x[i]);\n }\n var xSum = 0;\n var ySum = 0;\n var chi2 = 0;\n var rmsd = 0;\n var xSquared = 0;\n var ySquared = 0;\n var xY = 0;\n\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 var r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));\n\n return {\n r: r,\n r2: r * r,\n chi2: chi2,\n rmsd: rmsd * rmsd / n\n };\n }\n\n}\n\nmodule.exports = BaseRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/base-regression.js\n// module id = 4\n// module chunks = 0","'use strict';\n\nvar abstractMatrix = require('../abstractMatrix');\nvar Matrix = require('../matrix');\n\nclass BaseView extends abstractMatrix() {\n constructor(matrix, rows, columns) {\n super();\n this.matrix = matrix;\n this.rows = rows;\n this.columns = columns;\n }\n\n static get [Symbol.species]() {\n return Matrix.Matrix;\n }\n}\n\nmodule.exports = BaseView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/base.js\n// module id = 5\n// module chunks = 0","'use strict';\n\nexports.maybeToPrecision = function maybeToPrecision(value, digits) {\n if (value < 0) {\n value = -1 * value;\n if (digits) {\n return '- ' + value.toPrecision(digits);\n } else {\n return '- ' + value.toString();\n }\n } else {\n if (digits) {\n return value.toPrecision(digits);\n } else {\n return value.toString();\n }\n }\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/util.js\n// module id = 6\n// module chunks = 0","'use strict';\n\nvar Matrix = require('./matrix');\n\n/**\n * @private\n * Check that a row index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexports.checkRowIndex = function checkRowIndex(matrix, index, outer) {\n var max = outer ? matrix.rows : matrix.rows - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Row index out of range');\n }\n};\n\n/**\n * @private\n * Check that a column index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexports.checkColumnIndex = function checkColumnIndex(matrix, index, outer) {\n var max = outer ? matrix.columns : matrix.columns - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Column index out of range');\n }\n};\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexports.checkRowVector = function checkRowVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.columns) {\n throw new RangeError('vector size must be the same as the number of columns');\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 */\nexports.checkColumnVector = 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\nexports.checkIndices = function checkIndices(matrix, rowIndices, columnIndices) {\n var rowOut = rowIndices.some(r => {\n return r < 0 || r >= matrix.rows;\n\n });\n\n var columnOut = columnIndices.some(c => {\n return c < 0 || c >= matrix.columns;\n });\n\n if (rowOut || columnOut) {\n throw new RangeError('Indices are out of range');\n }\n\n if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') {\n throw new TypeError('Unexpected type for row/column indices');\n }\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\n if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices);\n\n return {\n row: rowIndices,\n column: columnIndices\n };\n};\n\nexports.checkRange = function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\n if (arguments.length !== 5) throw new TypeError('Invalid argument type');\n var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) {\n return typeof arg !== 'number';\n });\n if (notAllNumbers) throw new TypeError('Invalid argument type');\n 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) {\n throw new RangeError('Submatrix indices are out of range');\n }\n};\n\nexports.getRange = function getRange(from, to) {\n var arr = new Array(to - from + 1);\n for (var i = 0; i < arr.length; i++) {\n arr[i] = from + i;\n }\n return arr;\n};\n\nexports.sumByRow = function sumByRow(matrix) {\n var sum = Matrix.Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\n }\n }\n return sum;\n};\n\nexports.sumByColumn = function sumByColumn(matrix) {\n var sum = Matrix.Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\n }\n }\n return sum;\n};\n\nexports.sumAll = function sumAll(matrix) {\n var v = 0;\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/util.js\n// module id = 7\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix');\n\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst ANOVAKernel = require('./kernels/anova-kernel');\nconst CauchyKernel = require('./kernels/cauchy-kernel');\nconst ExponentialKernel = require('./kernels/exponential-kernel');\nconst HistogramKernel = require('./kernels/histogram-intersection-kernel');\nconst LaplacianKernel = require('./kernels/laplacian-kernel');\nconst MultiquadraticKernel = require('./kernels/multiquadratic-kernel');\nconst RationalKernel = require('./kernels/rational-quadratic-kernel');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\nconst kernelType = {\n gaussian: GaussianKernel,\n rbf: GaussianKernel,\n polynomial: PolynomialKernel,\n poly: PolynomialKernel,\n anova: ANOVAKernel,\n cauchy: CauchyKernel,\n exponential: ExponentialKernel,\n histogram: HistogramKernel,\n min: HistogramKernel,\n laplacian: LaplacianKernel,\n multiquadratic: MultiquadraticKernel,\n rational: RationalKernel,\n sigmoid: SigmoidKernel,\n mlp: SigmoidKernel\n};\n\nclass Kernel {\n constructor(type, options) {\n this.kernelType = type;\n if (type === 'linear') return;\n\n if (typeof type === 'string') {\n type = type.toLowerCase();\n\n var KernelConstructor = kernelType[type];\n if (KernelConstructor) {\n this.kernelFunction = new KernelConstructor(options);\n } else {\n throw new Error('unsupported kernel type: ' + type);\n }\n } else if (typeof type === 'object' && typeof type.compute === 'function') {\n this.kernelFunction = type;\n } else {\n throw new TypeError('first argument must be a valid kernel type or instance');\n }\n }\n\n compute(inputs, landmarks) {\n if (landmarks === undefined) {\n landmarks = inputs;\n }\n\n if (this.kernelType === 'linear') {\n var matrix = new Matrix(inputs);\n return matrix.mmul(new Matrix(landmarks).transpose());\n }\n\n const kernelMatrix = new Matrix(inputs.length, landmarks.length);\n var i, j;\n if (inputs === landmarks) { // fast path, matrix is symmetric\n for (i = 0; i < inputs.length; i++) {\n for (j = i; j < inputs.length; j++) {\n kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]);\n }\n }\n } else {\n for (i = 0; i < inputs.length; i++) {\n for (j = 0; j < landmarks.length; j++) {\n kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]);\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernel.js\n// module id = 8\n// module chunks = 0","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) {/**/}\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone,\n\t\ttarget = arguments[0],\n\t\ti = 1,\n\t\tlength = arguments.length,\n\t\tdeep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t} else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = target[name];\n\t\t\t\tcopy = options[name];\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\ttarget[name] = extend(deep, clone, copy);\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\ttarget[name] = copy;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/extend/index.js\n// module id = 9\n// module chunks = 0","'use strict';\n\nconst Heap = require('heap');\n\nfunction Cluster () {\n this.children = [];\n this.distance = -1;\n this.index = [];\n}\n\n/**\n * Creates an array of values where maximum distance smaller than the threshold\n * @param {number} threshold\n * @return {Array }\n */\nCluster.prototype.cut = function (threshold) {\n if (threshold < 0) throw new RangeError('Threshold too small');\n var root = new Cluster();\n root.children = this.children;\n root.distance = this.distance;\n root.index = this.index;\n var list = [root];\n var ans = [];\n while (list.length > 0) {\n var aux = list.shift();\n if (threshold >= aux.distance)\n ans.push(aux);\n else\n list = list.concat(aux.children);\n }\n return ans;\n};\n\n/**\n * Merge the leaves in the minimum way to have 'minGroups' number of clusters\n * @param {number} minGroups\n * @return {Cluster}\n */\nCluster.prototype.group = function (minGroups) {\n if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer');\n\n const heap = new Heap(function (a, b) {\n return b.distance - a.distance;\n });\n\n heap.push(this);\n\n while (heap.size() < minGroups) {\n var first = heap.pop();\n if (first.children.length === 0) {\n break;\n }\n first.children.forEach(child => heap.push(child));\n }\n\n var root = new Cluster();\n root.children = heap.toArray();\n root.distance = this.distance;\n\n return root;\n};\n\nmodule.exports = Cluster;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/Cluster.js\n// module id = 10\n// module chunks = 0","'use strict';\n\nexports.hypotenuse = function hypotenuse(a, b) {\n var r;\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\n// For use in the decomposition algorithms. With big matrices, access time is\n// too long on elements from array subclass\n// todo check when it is fixed in v8\n// http://jsperf.com/access-and-write-array-subclass\nexports.getEmpty2DArray = function (rows, columns) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n }\n return array;\n};\n\nexports.getFilled2DArray = function (rows, columns, value) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n for (var j = 0; j < columns; j++) {\n array[i][j] = value;\n }\n }\n return array;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/util.js\n// module id = 11\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix');\nconst Stat = require('ml-stat');\n\n/**\n * Function that given vector, returns his norm\n * @param {Vector} X\n * @returns {number} Norm of the vector\n */\nfunction norm(X) {\n return Math.sqrt(X.clone().apply(pow2array).sum());\n}\n\n/**\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 i - index i.\n * @param j - index j.\n * @return The Matrix object modified at the index i, j.\n * */\nfunction pow2array(i, j) {\n this[i][j] = this[i][j] * this[i][j];\n return this;\n}\n\n/**\n * Function that normalize the dataset and return the means and\n * standard deviation of each feature.\n * @param dataset\n * @returns {{result: Matrix, means: (*|number), std: Matrix}} dataset normalized, means\n * and standard deviations\n */\nfunction featureNormalize(dataset) {\n var means = Stat.matrix.mean(dataset);\n var std = Stat.matrix.standardDeviation(dataset, means, true);\n var result = Matrix.checkMatrix(dataset).subRowVector(means);\n return {result: result.divRowVector(std), means: means, std: std};\n}\n\nmodule.exports = {\n norm: norm,\n pow2array: pow2array,\n featureNormalize: featureNormalize\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pls/src/utils.js\n// module id = 12\n// module chunks = 0","'use strict';\n\nvar maybeToPrecision = require('./util').maybeToPrecision;\nconst BaseRegression = require('./base-regression');\n\n\nclass SimpleLinearRegression extends BaseRegression {\n\n constructor(x, y, options) {\n options = options || {};\n super();\n if (x === true) {\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.quality = y.quality || {};\n if (y.quality.r) {\n this.quality.r = y.quality.r;\n this.quality.r2 = y.quality.r2;\n }\n if (y.quality.chi2) {\n this.quality.chi2 = y.quality.chi2;\n }\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n\n var xSum = 0;\n var ySum = 0;\n\n var xSquared = 0;\n var xY = 0;\n\n for (var 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 var numerator = (n * xY - xSum * ySum);\n\n\n this.slope = numerator / (n * xSquared - xSum * xSum);\n this.intercept = (1 / n) * ySum - this.slope * (1 / n) * xSum;\n this.coefficients = [this.intercept, this.slope];\n if (options.computeQuality) {\n this.quality = this.modelQuality(x, y);\n }\n }\n\n }\n\n toJSON() {\n var out = {\n name: 'simpleLinearRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n if (this.quality) {\n out.quality = this.quality;\n }\n\n return out;\n }\n\n _predict(input) {\n return this.slope * input + this.intercept;\n }\n\n computeX(input) {\n return (input - this.intercept) / this.slope;\n }\n\n toString(precision) {\n var result = 'f(x) = ';\n if (this.slope) {\n var xFactor = maybeToPrecision(this.slope, precision);\n result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n var absIntercept = Math.abs(this.intercept);\n var operator = absIntercept === this.intercept ? '+' : '-';\n result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision);\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'simpleLinearRegression') {\n throw new TypeError('not a SLR model');\n }\n return new SimpleLinearRegression(true, json);\n }\n}\n\nmodule.exports = SimpleLinearRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/simple-linear-regression.js\n// module id = 13\n// module chunks = 0","'use strict';\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n/**\n * Computes the sum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.sum = function sum(values) {\n var sum = 0;\n for (var i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum;\n};\n\n/**\n * Computes the maximum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.max = function max(values) {\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] > max) max = values[i];\n }\n return max;\n};\n\n/**\n * Computes the minimum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.min = function min(values) {\n var min = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n }\n return min;\n};\n\n/**\n * Computes the min and max of the given values\n * @param {Array} values\n * @returns {{min: number, max: number}}\n */\nexports.minMax = function minMax(values) {\n var min = values[0];\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n if (values[i] > max) max = values[i];\n }\n return {\n min: min,\n max: max\n };\n};\n\n/**\n * Computes the arithmetic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.arithmeticMean = function arithmeticMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n sum += values[i];\n }\n return sum / l;\n};\n\n/**\n * {@link arithmeticMean}\n */\nexports.mean = exports.arithmeticMean;\n\n/**\n * Computes the geometric mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.geometricMean = function geometricMean(values) {\n var mul = 1;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n mul *= values[i];\n }\n return Math.pow(mul, 1 / l);\n};\n\n/**\n * Computes the mean of the log of the given values\n * If the return value is exponentiated, it gives the same result as the\n * geometric mean.\n * @param {Array} values\n * @returns {number}\n */\nexports.logMean = function logMean(values) {\n var lnsum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n lnsum += Math.log(values[i]);\n }\n return lnsum / l;\n};\n\n/**\n * Computes the weighted grand mean for a list of means and sample sizes\n * @param {Array} means - Mean values for each set of samples\n * @param {Array} samples - Number of original values for each set of samples\n * @returns {number}\n */\nexports.grandMean = function grandMean(means, samples) {\n var sum = 0;\n var n = 0;\n var l = means.length;\n for (var i = 0; i < l; i++) {\n sum += samples[i] * means[i];\n n += samples[i];\n }\n return sum / n;\n};\n\n/**\n * Computes the truncated mean of the given values using a given percentage\n * @param {Array} values\n * @param {number} percent - The percentage of values to keep (range: [0,1])\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var k = Math.floor(l * percent);\n var sum = 0;\n for (var i = k; i < (l - k); i++) {\n sum += values[i];\n }\n return sum / (l - 2 * k);\n};\n\n/**\n * Computes the harmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.harmonicMean = function harmonicMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] === 0) {\n throw new RangeError('value at index ' + i + 'is zero');\n }\n sum += 1 / values[i];\n }\n return l / sum;\n};\n\n/**\n * Computes the contraharmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.contraHarmonicMean = function contraHarmonicMean(values) {\n var r1 = 0;\n var r2 = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n r1 += values[i] * values[i];\n r2 += values[i];\n }\n if (r2 < 0) {\n throw new RangeError('sum of values is negative');\n }\n return r1 / r2;\n};\n\n/**\n * Computes the median of the given values\n * @param {Array} values\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.median = function median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n};\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.variance = function variance(values, unbiased) {\n if (unbiased === undefined) unbiased = true;\n var theMean = exports.mean(values);\n var theVariance = 0;\n var l = values.length;\n\n for (var i = 0; i < l; i++) {\n var x = values[i] - theMean;\n theVariance += x * x;\n }\n\n if (unbiased) {\n return theVariance / (l - 1);\n } else {\n return theVariance / l;\n }\n};\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.standardDeviation = function standardDeviation(values, unbiased) {\n return Math.sqrt(exports.variance(values, unbiased));\n};\n\nexports.standardError = function standardError(values) {\n return exports.standardDeviation(values) / Math.sqrt(values.length);\n};\n\n/**\n * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-\n * Calculate the standard deviation via the Median of the absolute deviation\n * The formula for the standard deviation only holds for Gaussian random variables.\n * @returns {{mean: number, stdev: number}}\n */\nexports.robustMeanAndStdev = function robustMeanAndStdev(y) {\n var mean = 0, stdev = 0;\n var length = y.length, i = 0;\n for (i = 0; i < length; i++) {\n mean += y[i];\n }\n mean /= length;\n var averageDeviations = new Array(length);\n for (i = 0; i < length; i++)\n averageDeviations[i] = Math.abs(y[i] - mean);\n averageDeviations.sort(compareNumbers);\n if (length % 2 === 1) {\n stdev = averageDeviations[(length - 1) / 2] / 0.6745;\n } else {\n stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745;\n }\n\n return {\n mean: mean,\n stdev: stdev\n };\n};\n\nexports.quartiles = function quartiles(values, alreadySorted) {\n if (typeof (alreadySorted) === 'undefined') alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n\n var quart = values.length / 4;\n var q1 = values[Math.ceil(quart) - 1];\n var q2 = exports.median(values, true);\n var q3 = values[Math.ceil(quart * 3) - 1];\n\n return {q1: q1, q2: q2, q3: q3};\n};\n\nexports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {\n return Math.sqrt(exports.pooledVariance(samples, unbiased));\n};\n\nexports.pooledVariance = function pooledVariance(samples, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var sum = 0;\n var length = 0, l = samples.length;\n for (var i = 0; i < l; i++) {\n var values = samples[i];\n var vari = exports.variance(values);\n\n sum += (values.length - 1) * vari;\n\n if (unbiased)\n length += values.length - 1;\n else\n length += values.length;\n }\n return sum / length;\n};\n\nexports.mode = function mode(values) {\n var l = values.length,\n itemCount = new Array(l),\n i;\n for (i = 0; i < l; i++) {\n itemCount[i] = 0;\n }\n var itemArray = new Array(l);\n var count = 0;\n\n for (i = 0; i < l; i++) {\n var index = itemArray.indexOf(values[i]);\n if (index >= 0)\n itemCount[index]++;\n else {\n itemArray[count] = values[i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (i = 0; i < count; i++) {\n if (itemCount[i] > maxValue) {\n maxValue = itemCount[i];\n maxIndex = i;\n }\n }\n\n return itemArray[maxIndex];\n};\n\nexports.covariance = function covariance(vector1, vector2, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var mean1 = exports.mean(vector1);\n var mean2 = exports.mean(vector2);\n\n if (vector1.length !== vector2.length)\n throw 'Vectors do not have the same dimensions';\n\n var cov = 0, l = vector1.length;\n for (var i = 0; i < l; i++) {\n var x = vector1[i] - mean1;\n var y = vector2[i] - mean2;\n cov += x * y;\n }\n\n if (unbiased)\n return cov / (l - 1);\n else\n return cov / l;\n};\n\nexports.skewness = function skewness(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n\n var s2 = 0, s3 = 0, l = values.length;\n for (var i = 0; i < l; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n var m2 = s2 / l;\n var m3 = s3 / l;\n\n var g = m3 / (Math.pow(m2, 3 / 2.0));\n if (unbiased) {\n var a = Math.sqrt(l * (l - 1));\n var b = l - 2;\n return (a / b) * g;\n } else {\n return g;\n }\n};\n\nexports.kurtosis = function kurtosis(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n var n = values.length, s2 = 0, s4 = 0;\n\n for (var i = 0; i < n; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n\n return a * b - 3 * c;\n } else {\n return m4 / (m2 * m2) - 3;\n }\n};\n\nexports.entropy = function entropy(values, eps) {\n if (typeof (eps) === 'undefined') eps = 0;\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * Math.log(values[i] + eps);\n return -sum;\n};\n\nexports.weightedMean = function weightedMean(values, weights) {\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * weights[i];\n return sum;\n};\n\nexports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {\n return Math.sqrt(exports.weightedVariance(values, weights));\n};\n\nexports.weightedVariance = function weightedVariance(values, weights) {\n var theMean = exports.weightedMean(values, weights);\n var vari = 0, l = values.length;\n var a = 0, b = 0;\n\n for (var i = 0; i < l; i++) {\n var z = values[i] - theMean;\n var w = weights[i];\n\n vari += w * (z * z);\n b += w;\n a += w * w;\n }\n\n return vari * (b / (b * b - a));\n};\n\nexports.center = function center(values, inPlace) {\n if (typeof (inPlace) === 'undefined') inPlace = false;\n\n var result = values;\n if (!inPlace)\n result = [].concat(values);\n\n var theMean = exports.mean(result), l = result.length;\n for (var i = 0; i < l; i++)\n result[i] -= theMean;\n};\n\nexports.standardize = function standardize(values, standardDev, inPlace) {\n if (typeof (standardDev) === 'undefined') standardDev = exports.standardDeviation(values);\n if (typeof (inPlace) === 'undefined') inPlace = false;\n var l = values.length;\n var result = inPlace ? values : new Array(l);\n for (var i = 0; i < l; i++)\n result[i] = values[i] / standardDev;\n return result;\n};\n\nexports.cumulativeSum = function cumulativeSum(array) {\n var l = array.length;\n var result = new Array(l);\n result[0] = array[0];\n for (var i = 1; i < l; i++)\n result[i] = result[i - 1] + array[i];\n return result;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-stat/array.js\n// module id = 14\n// module chunks = 0","module.exports = function(haystack, needle, comparator, low, high) {\n var mid, cmp;\n\n if(low === undefined)\n low = 0;\n\n else {\n low = low|0;\n if(low < 0 || low >= haystack.length)\n throw new RangeError(\"invalid lower bound\");\n }\n\n if(high === undefined)\n high = haystack.length - 1;\n\n else {\n high = high|0;\n if(high < low || high >= haystack.length)\n throw new RangeError(\"invalid upper bound\");\n }\n\n while(low <= high) {\n /* Note that \"(low + high) >>> 1\" may overflow, and results in a typecast\n * to double (which gives the wrong results). */\n mid = low + (high - low >> 1);\n cmp = +comparator(haystack[mid], needle, mid, haystack);\n\n /* Too low. */\n if(cmp < 0.0)\n low = mid + 1;\n\n /* Too high. */\n else if(cmp > 0.0)\n high = mid - 1;\n\n /* Key found. */\n else\n return mid;\n }\n\n /* Key not found. */\n return ~low;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/binary-search/index.js\n// module id = 15\n// module chunks = 0","module.exports = exports = require('./ArrayUtils');\n\n\nexports.getEquallySpacedData = require('./getEquallySpaced').getEquallySpacedData;\nexports.SNV = require('./snv').SNV;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-array-utils/src/index.js\n// module id = 16\n// module chunks = 0","'use strict';\n\nmodule.exports = require('./LM');\nmodule.exports.Matrix = require('ml-matrix');\nmodule.exports.Matrix.algebra = require('./algebra');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-curve-fitting/src/index.js\n// module id = 17\n// module chunks = 0","'use strict';\n\nexports.distance = require('./distances');\nexports.similarity = require('./similarities');\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/index.js\n// module id = 18\n// module chunks = 0","'use strict';\n\nconst newArray = require('new-array');\n\nconst primeFinder = require('./primeFinder');\nconst nextPrime = primeFinder.nextPrime;\nconst largestPrime = primeFinder.largestPrime;\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nclass HashTable {\n constructor(options = {}) {\n if (options instanceof HashTable) {\n this.table = options.table.slice();\n this.values = options.values.slice();\n this.state = options.state.slice();\n this.minLoadFactor = options.minLoadFactor;\n this.maxLoadFactor = options.maxLoadFactor;\n this.distinct = options.distinct;\n this.freeEntries = options.freeEntries;\n this.lowWaterMark = options.lowWaterMark;\n this.highWaterMark = options.maxLoadFactor;\n return;\n }\n\n const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`);\n }\n\n const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor;\n const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor;\n if (minLoadFactor < 0 || minLoadFactor >= 1) {\n throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`);\n }\n if (maxLoadFactor <= 0 || maxLoadFactor >= 1) {\n throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`);\n }\n if (minLoadFactor >= maxLoadFactor) {\n throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`);\n }\n\n let capacity = initialCapacity;\n // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to\n // avoid the need to rehash before this capacity is reached.\n // actualCapacity * maxLoadFactor >= capacity\n capacity = (capacity / maxLoadFactor) | 0;\n capacity = nextPrime(capacity);\n if (capacity === 0) capacity = 1;\n\n this.table = newArray(capacity, 0);\n this.values = newArray(capacity, 0);\n this.state = newArray(capacity, 0);\n\n this.minLoadFactor = minLoadFactor;\n if (capacity === largestPrime) {\n this.maxLoadFactor = 1;\n } else {\n this.maxLoadFactor = maxLoadFactor;\n }\n\n this.distinct = 0;\n this.freeEntries = capacity;\n\n this.lowWaterMark = 0;\n this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor);\n }\n\n clone() {\n return new HashTable(this);\n }\n\n get size() {\n return this.distinct;\n }\n\n get(key) {\n const i = this.indexOfKey(key);\n if (i < 0) return 0;\n return this.values[i];\n }\n\n set(key, value) {\n let i = this.indexOfInsertion(key);\n if (i < 0) {\n i = -i - 1;\n this.values[i] = value;\n return false;\n }\n\n if (this.distinct > this.highWaterMark) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n return this.set(key, value);\n }\n\n this.table[i] = key;\n this.values[i] = value;\n if (this.state[i] === FREE) this.freeEntries--;\n this.state[i] = FULL;\n this.distinct++;\n\n if (this.freeEntries < 1) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n\n return true;\n }\n \n remove(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = REMOVED;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n delete(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = FREE;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n maybeShrinkCapacity() {\n if (this.distinct < this.lowWaterMark) {\n const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n }\n\n containsKey(key) {\n return this.indexOfKey(key) >= 0;\n }\n\n indexOfKey(key) {\n const table = this.table;\n const state = this.state;\n const length = this.table.length;\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === FREE) return -1;\n return i;\n }\n\n containsValue(value) {\n return this.indexOfValue(value) >= 0;\n }\n\n indexOfValue(value) {\n const values = this.values;\n const state = this.state;\n\n for (var i = 0; i < state.length; i++) {\n if (state[i] === FULL && values[i] === value) {\n return i;\n }\n }\n\n return -1;\n }\n\n indexOfInsertion(key) {\n const table = this.table;\n const state = this.state;\n const length = table.length;\n\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] === FULL && table[i] !== key) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === REMOVED) {\n const j = i;\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n if (state[i] === FREE) i = j;\n }\n\n if (state[i] === FULL) {\n return -i - 1;\n }\n\n return i;\n }\n\n ensureCapacity(minCapacity) {\n if (this.table.length < minCapacity) {\n const newCapacity = nextPrime(minCapacity);\n this.rehash(newCapacity);\n }\n }\n\n rehash(newCapacity) {\n const oldCapacity = this.table.length;\n\n if (newCapacity <= this.distinct) throw new Error('Unexpected');\n\n const oldTable = this.table;\n const oldValues = this.values;\n const oldState = this.state;\n\n const newTable = newArray(newCapacity, 0);\n const newValues = newArray(newCapacity, 0);\n const newState = newArray(newCapacity, 0);\n\n this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor);\n this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor);\n\n this.table = newTable;\n this.values = newValues;\n this.state = newState;\n this.freeEntries = newCapacity - this.distinct;\n\n for (var i = 0; i < oldCapacity; i++) {\n if (oldState[i] === FULL) {\n var element = oldTable[i];\n var index = this.indexOfInsertion(element);\n newTable[index] = element;\n newValues[index] = oldValues[i];\n newState[index] = FULL;\n }\n }\n }\n\n forEachKey(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i])) return false;\n }\n }\n return true;\n }\n\n forEachValue(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.values[i])) return false;\n }\n }\n return true;\n }\n\n forEachPair(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i], this.values[i])) return false;\n }\n }\n return true;\n }\n}\n\nmodule.exports = HashTable;\n\nfunction chooseLowWaterMark(capacity, minLoad) {\n return (capacity * minLoad) | 0;\n}\n\nfunction chooseHighWaterMark(capacity, maxLoad) {\n return Math.min(capacity - 2, (capacity * maxLoad) | 0);\n}\n\nfunction chooseGrowCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (3 * minLoad + maxLoad)) | 0));\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (minLoad + 3 * maxLoad)) | 0));\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hash-table/src/HashTable.js\n// module id = 19\n// module chunks = 0","'use strict';\n\nvar extend = require('extend');\n\nvar defaultOptions = {\n size: 1,\n value: 0\n};\n\n/**\n * Case when the entry is an array\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction arrayCase(data, options) {\n var len = data.length;\n if (typeof options.size === 'number')\n options.size = [options.size, options.size];\n\n var cond = len + options.size[0] + options.size[1];\n\n var output;\n if (options.output) {\n if (options.output.length !== cond)\n throw new RangeError('Wrong output size');\n output = options.output;\n }\n else\n output = new Array(cond);\n\n var i;\n\n // circular option\n if (options.value === 'circular') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[((len - (options.size[0] % len)) + i) % len];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[(i - options.size[0]) % len];\n }\n }\n\n // replicate option\n else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[0];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[len - 1];\n }\n }\n\n // symmetric option\n else if (options.value === 'symmetric') {\n if ((options.size[0] > len) || (options.size[1] > len))\n throw new RangeError('expanded value should not be bigger than the data length');\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[options.size[0] - 1 - i];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[2*len + options.size[0] - i - 1];\n }\n }\n\n // default option\n else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = options.value;\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = options.value;\n }\n }\n\n return output;\n}\n\n/**\n * Case when the entry is a matrix\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction matrixCase(data, options) {\n var row = data.length;\n var col = data[0].length;\n if (options.size[0] === undefined)\n options.size = [options.size, options.size, options.size, options.size];\n throw new Error('matrix not supported yet, sorry');\n}\n\n/**\n * Pads and array\n * @param {Array } data\n * @param {object} options\n */\nfunction padArray (data, options) {\n options = extend({}, defaultOptions, options);\n\n if (Array.isArray(data)) {\n if (Array.isArray(data[0]))\n return matrixCase(data, options);\n else\n return arrayCase(data, options);\n }\n else\n throw new TypeError('data should be an array');\n}\n\nmodule.exports = padArray;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pad-array/src/index.js\n// module id = 20\n// module chunks = 0","'use strict';\nvar numberIsNan = require('number-is-nan');\n\nfunction assertNum(x) {\n\tif (typeof x !== 'number' || numberIsNan(x)) {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.asc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn a - b;\n};\n\nexports.desc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn b - a;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/num-sort/index.js\n// module id = 21\n// module chunks = 0","/**\n * Created by acastillo on 8/24/15.\n */\n/**\n * Non in-place function definitions, compatible with mathjs code *\n */\n\n'use strict';\n\nvar Matrix = require('ml-matrix');\n\nfunction matrix(A,B){\n return new Matrix(A,B);\n}\n\nfunction ones(rows, cols){\n return Matrix.ones(rows,cols);\n}\n\nfunction eye(rows, cols){\n return Matrix.eye(rows, cols);\n}\n\nfunction zeros(rows, cols){\n return Matrix.zeros(rows, cols);\n}\n\nfunction random(rows, cols){\n return Matrix.rand(rows,cols);\n}\n\nfunction transpose(A){\n if(typeof A == 'number')\n return A;\n var result = A.clone();\n return result.transpose();\n}\n\nfunction add(A, B){\n if(typeof A == 'number'&&typeof B === 'number')\n return A+B;\n if(typeof A == 'number')\n return this.add(B,A);\n\n var result = A.clone();\n return result.add(B);\n\n}\n\nfunction subtract(A, B){\n if(typeof A == 'number'&&typeof B === 'number')\n return A-B;\n if(typeof A == 'number')\n return this.subtract(B,A);\n var result = A.clone();\n return result.sub(B);\n}\n\nfunction multiply(A, B){\n if(typeof A == 'number'&&typeof B === 'number')\n return A*B;\n if(typeof A == 'number')\n return this.multiply(B,A);\n\n var result = A.clone();\n\n if(typeof B === 'number')\n result.mul(B);\n else\n result = result.mmul(B);\n\n if(result.rows==1&&result.columns==1)\n return result[0][0];\n else\n return result;\n\n}\n\nfunction dotMultiply(A, B){\n var result = A.clone();\n return result.mul(B);\n}\n\nfunction dotDivide(A, B){\n var result = A.clone();\n return result.div(B);\n}\n\nfunction diag(A){\n var diag = null;\n var rows = A.rows, cols = A.columns, j, r;\n //It is an array\n if(typeof cols === \"undefined\" && (typeof A)=='object'){\n if(A[0]&&A[0].length){\n rows = A.length;\n cols = A[0].length;\n r = Math.min(rows,cols);\n diag = Matrix.zeros(cols, cols);\n for (j = 0; j < cols; j++) {\n diag[j][j]=A[j][j];\n }\n }\n else{\n cols = A.length;\n diag = Matrix.zeros(cols, cols);\n for (j = 0; j < cols; j++) {\n diag[j][j]=A[j];\n }\n }\n\n }\n if(rows == 1){\n diag = Matrix.zeros(cols, cols);\n for (j = 0; j < cols; j++) {\n diag[j][j]=A[0][j];\n }\n }\n else{\n if(rows>0 && cols > 0){\n r = Math.min(rows,cols);\n diag = new Array(r);\n for (j = 0; j < r; j++) {\n diag[j] = A[j][j];\n }\n }\n }\n return diag;\n}\n\nfunction min(A, B){\n if(typeof A==='number' && typeof B ==='number')\n return Math.min(A,B);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n if (A[i][j] < B[i][j]) {\n result[i][j] = A[i][j];\n }\n else{\n result[i][j] = B[i][j];\n }\n }\n }\n return result;\n}\n\nfunction max(A, B){\n if(typeof A==='number' && typeof B ==='number')\n return Math.max(A,B);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n if (A[i][j] > B[i][j]) {\n result[i][j] = A[i][j];\n }\n else{\n result[i][j] = B[i][j];\n }\n }\n }\n return result;\n}\n\nfunction sqrt(A){\n if(typeof A==='number' )\n return Math.sqrt(A);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n result[i][j] = Math.sqrt(A[i][j]);\n\n }\n }\n return result;\n}\n\nfunction abs(A){\n if(typeof A==='number' )\n return Math.abs(A);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n result[i][j] = Math.abs(A[i][j]);\n\n }\n }\n return result;\n}\n\nfunction exp(A){\n if(typeof A==='number' )\n return Math.sqrt(A);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n result[i][j] = Math.exp(A[i][j]);\n }\n }\n return result;\n}\n\nfunction dotPow(A, b){\n if(typeof A==='number' )\n return Math.pow(A,b);\n //console.log(A);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n result[i][j] = Math.pow(A[i][j],b);\n }\n }\n return result;\n}\n\nfunction solve(A, B){\n return A.solve(B);\n}\n\nfunction inv(A){\n if(typeof A ===\"number\")\n return 1/A;\n return A.inverse();\n}\n\nmodule.exports = {\n transpose:transpose,\n add:add,\n subtract:subtract,\n multiply:multiply,\n dotMultiply:dotMultiply,\n dotDivide:dotDivide,\n diag:diag,\n min:min,\n max:max,\n solve:solve,\n inv:inv,\n sqrt:sqrt,\n exp:exp,\n dotPow:dotPow,\n abs:abs,\n matrix:matrix,\n ones:ones,\n zeros:zeros,\n random:random,\n eye:eye\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-curve-fitting/src/algebra.js\n// module id = 22\n// module chunks = 0","module.exports = function dice(a, b) {\n var ii = a.length,\n p = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p + q1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/dice.js\n// module id = 23\n// module chunks = 0","module.exports = function intersection(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.min(a[i], b[i]);\n }\n return 1 - ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/intersection.js\n// module id = 24\n// module chunks = 0","module.exports = function jaccard(a, b) {\n var ii = a.length,\n p1 = 0,\n p2 = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p1 += a[i] * b[i];\n p2 += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p2 + q1 - p1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/jaccard.js\n// module id = 25\n// module chunks = 0","module.exports = function kulczynski(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.min(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kulczynski.js\n// module id = 26\n// module chunks = 0","module.exports = function motyka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 1 - (up / down);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/motyka.js\n// module id = 27\n// module chunks = 0","module.exports = function squaredChord(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/squaredChord.js\n// module id = 28\n// module chunks = 0","module.exports = function cosine(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (Math.sqrt(p2) * Math.sqrt(q2));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/cosine.js\n// module id = 29\n// module chunks = 0","'use strict';\n\nmodule.exports = function czekanowskiSimilarity(a, b) {\n var up = 0;\n var down = 0;\n for (var i = 0; i < a.length; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 2 * up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/czekanowski.js\n// module id = 30\n// module chunks = 0","module.exports = function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0,\n union = 0;\n for (var j = 0; j < a.length; j++) {\n inter += a[j] && b[j];\n union += a[j] || b[j];\n }\n if (union === 0)\n return 1;\n return inter / union;\n }\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return 1 - (p + q - 2 * m) / (p + q - m);\n }\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/tanimoto.js\n// module id = 31\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\n\nvar Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass Layer {\n /**\n * Create a new layer with the given options\n * @param {object} options\n * @param {number} [options.inputSize] - Number of conections that enter the neurons.\n * @param {number} [options.outputSize] - Number of conections that leave the neurons.\n * @param {number} [options.regularization] - Regularization parameter.\n * @param {number} [options.epsilon] - Learning rate parameter.\n * @param {string} [options.activation] - Activation function parameter from the FeedForwardNeuralNetwork class.\n * @param {number} [options.activationParam] - Activation parameter if needed.\n */\n constructor(options) {\n this.inputSize = options.inputSize;\n this.outputSize = options.outputSize;\n this.regularization = options.regularization;\n this.epsilon = options.epsilon;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n\n var selectedFunction = ACTIVATION_FUNCTIONS[options.activation];\n var params = selectedFunction.activation.length;\n\n var actFunction = params > 1 ? val => selectedFunction.activation(val, options.activationParam) : selectedFunction.activation;\n var derFunction = params > 1 ? val => selectedFunction.derivate(val, options.activationParam) : selectedFunction.derivate;\n\n this.activationFunction = function (i, j) {\n this[i][j] = actFunction(this[i][j]);\n };\n this.derivate = function (i, j) {\n this[i][j] = derFunction(this[i][j]);\n };\n\n if (options.model) {\n // load model\n this.W = Matrix.checkMatrix(options.W);\n this.b = Matrix.checkMatrix(options.b);\n\n } else {\n // default constructor\n\n this.W = Matrix.rand(this.inputSize, this.outputSize);\n this.b = Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this[i][j] /= Math.sqrt(options.inputSize);\n });\n }\n }\n\n /**\n * 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 * apply backpropagation algorithm at the current layer\n * @param {Matrix} delta - delta values estimated at the following layer.\n * @param {Matrix} a - 'a' values from the following layer.\n * @return {Matrix} the new delta values for the next layer.\n */\n backpropagation(delta, a) {\n this.dW = a.transposeView().mmul(delta);\n this.db = Utils.sumCol(delta);\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate));\n }\n\n /**\n * 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 * 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 * Creates a new Layer with the given model.\n * @param {object} model\n * @return {Layer}\n */\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n return new Layer(model);\n }\n\n}\n\nmodule.exports = Layer;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-fnn/src/Layer.js\n// module id = 32\n// module chunks = 0","'use strict';\n\nfunction logistic(val) {\n return 1 / (1 + Math.exp(-val));\n}\n\nfunction expELU(val, param) {\n return val < 0 ? param * (Math.exp(val) - 1) : val;\n}\n\nfunction softExponential(val, param) {\n if (param < 0) {\n return -Math.log(1 - param * (val + param)) / param;\n }\n if (param > 0) {\n return ((Math.exp(param * val) - 1) / param) + param;\n }\n return val;\n}\n\nfunction softExponentialPrime(val, param) {\n if (param < 0) {\n return 1 / (1 - param * (param + val));\n } else {\n return Math.exp(param * val);\n }\n}\n\nconst ACTIVATION_FUNCTIONS = {\n 'tanh': {\n activation: Math.tanh,\n derivate: val => 1 - (val * val)\n },\n 'identity': {\n activation: val => val,\n derivate: () => 1\n },\n 'logistic': {\n activation: logistic,\n derivate: val => logistic(val) * (1 - logistic(val))\n },\n 'arctan': {\n activation: Math.atan,\n derivate: val => 1 / (val * val + 1)\n },\n 'softsign': {\n activation: val => val / (1 + Math.abs(val)),\n derivate: val => 1 / ((1 + Math.abs(val)) * (1 + Math.abs(val)))\n },\n 'relu': {\n activation: val => val < 0 ? 0 : val,\n derivate: val => val < 0 ? 0 : 1\n },\n 'softplus': {\n activation: val => Math.log(1 + Math.exp(val)),\n derivate: val => 1 / (1 + Math.exp(-val))\n },\n 'bent': {\n activation: val => ((Math.sqrt(val * val + 1) - 1) / 2) + val,\n derivate: val => (val / (2 * Math.sqrt(val * val + 1))) + 1\n },\n 'sinusoid': {\n activation: Math.sin,\n derivate: Math.cos\n },\n 'sinc': {\n activation: val => val === 0 ? 1 : Math.sin(val) / val,\n derivate: val => val === 0 ? 0 : (Math.cos(val) / val) - (Math.sin(val) / (val * val))\n },\n 'gaussian': {\n activation: val => Math.exp(-(val * val)),\n derivate: val => -2 * val * Math.exp(-(val * val))\n },\n 'parametric-relu': {\n activation: (val, param) => val < 0 ? param * val : val,\n derivate: (val, param) => val < 0 ? param : 1\n },\n 'exponential-elu': {\n activation: expELU,\n derivate: (val, param) => val < 0 ? expELU(val, param) + param : 1\n },\n 'soft-exponential': {\n activation: softExponential,\n derivate: softExponentialPrime\n }\n};\n\nmodule.exports = ACTIVATION_FUNCTIONS;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-fnn/src/activationFunctions.js\n// module id = 33\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\n\n/**\n * Retrieves the sum at each row of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[i][0] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * Retrieves the sum at each column of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumCol(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[0][j] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * 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 = {}, outputs = {}, l = array.length, index = 0;\n for (var i = 0; i < l; i += 1) {\n if (inputs[array[i]] === undefined) {\n inputs[array[i]] = index;\n outputs[index] = array[i];\n index++;\n }\n }\n\n return {\n inputs: inputs,\n outputs: outputs\n };\n}\n\nmodule.exports = {\n dictOutputs: dictOutputs,\n sumCol: sumCol,\n sumRow: sumRow\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-fnn/src/utils.js\n// module id = 34\n// module chunks = 0","'use strict';\n\nvar Cluster = require('./Cluster');\nvar util = require('util');\n\nfunction ClusterLeaf (index) {\n Cluster.call(this);\n this.index = index;\n this.distance = 0;\n this.children = [];\n}\n\nutil.inherits(ClusterLeaf, Cluster);\n\nmodule.exports = ClusterLeaf;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/ClusterLeaf.js\n// module id = 35\n// module chunks = 0","'use strict';\n\nconst nearestVector = require('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 */\nfunction 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 * @returns {Array} the cluster identifier for each data dot\n */\nfunction updateClusterID(data, centers, clusterID, distance) {\n for (var i = 0; i < data.length; i++) {\n clusterID[i] = nearestVector(centers, data[i], {distanceFunction: distance});\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 >} 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 * @returns {Array} he K centers in format [x,y,z,...]\n */\nfunction updateCenters(data, clusterID, K) {\n const nDim = data[0].length;\n\n // creates empty centers with 0 size\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 centers[id][d] /= centersLen[id];\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 */\nfunction converged(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\nexports.updateClusterID = updateClusterID;\nexports.updateCenters = updateCenters;\nexports.calculateDistanceMatrix = calculateDistanceMatrix;\nexports.converged = converged;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kmeans/src/utils.js\n// module id = 36\n// module chunks = 0","'use strict';\n\nmodule.exports = abstractMatrix;\n\nvar LuDecomposition = require('./dc/lu');\nvar arrayUtils = require('ml-array-utils');\nvar util = require('./util');\nvar MatrixTransposeView = require('./views/transpose');\nvar MatrixRowView = require('./views/row');\nvar MatrixSubView = require('./views/sub');\nvar MatrixSelectionView = require('./views/selection');\nvar MatrixColumnView = require('./views/column');\nvar MatrixFlipRowView = require('./views/flipRow');\nvar MatrixFlipColumnView = require('./views/flipColumn');\n\nfunction abstractMatrix(superCtor) {\n if (superCtor === undefined) superCtor = Object;\n\n /**\n * Real matrix\n * @class Matrix\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\n * 2D array containing the data or Matrix instance to clone\n * @param {number} [nColumns] - Number of columns of the new matrix\n */\n class Matrix extends superCtor {\n static get [Symbol.species]() {\n return this;\n }\n\n /**\n * Constructs a Matrix with the chosen dimensions from a 1D array\n * @param {number} newRows - Number of rows\n * @param {number} newColumns - Number of columns\n * @param {Array} newData - A 1D array containing data for the matrix\n * @return {Matrix} - The new matrix\n */\n static from1DArray(newRows, newColumns, newData) {\n var length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('Data length does not match given dimensions');\n }\n var newMatrix = new this(newRows, newColumns);\n for (var row = 0; row < newRows; row++) {\n for (var column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n /**\n * Creates a row vector, a matrix with only one row.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static rowVector(newData) {\n var vector = new this(1, newData.length);\n for (var i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates a column vector, a matrix with only one column.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static columnVector(newData) {\n var vector = new this(newData.length, 1);\n for (var i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static empty(rows, columns) {\n return new this(rows, columns);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to zero.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static zeros(rows, columns) {\n return this.empty(rows, columns).fill(0);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to one.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static ones(rows, columns) {\n return this.empty(rows, columns).fill(1);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be randomly set.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static rand(rows, columns, rng) {\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n matrix.set(i, j, rng());\n }\n }\n return matrix;\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be random integers.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {number} [maxValue=1000] - Maximum value\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static randInt(rows, columns, maxValue, rng) {\n if (maxValue === undefined) maxValue = 1000;\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = Math.floor(rng() * maxValue);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n /**\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\n * @param {number} rows - Number of rows\n * @param {number} [columns=rows] - Number of columns\n * @param {number} [value=1] - Value to fill the diagonal with\n * @return {Matrix} - The new identity matrix\n */\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n var min = Math.min(rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n /**\n * Creates a diagonal matrix based on the given array.\n * @param {Array} data - Array containing the data for the diagonal\n * @param {number} [rows] - Number of rows (Default: data.length)\n * @param {number} [columns] - Number of columns (Default: rows)\n * @return {Matrix} - The new diagonal matrix\n */\n static diag(data, rows, columns) {\n var l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n var min = Math.min(l, rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n /**\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Check that the provided value is a Matrix and tries to instantiate one if not\n * @param {*} value - The value to check\n * @return {Matrix}\n */\n static checkMatrix(value) {\n return Matrix.isMatrix(value) ? value : new this(value);\n }\n\n /**\n * Returns true if the argument is a Matrix, false otherwise\n * @param {*} value - The value to check\n * @return {boolean}\n */\n static isMatrix(value) {\n return (value != null) && (value.klass === 'Matrix');\n }\n\n /**\n * @prop {number} size - The number of elements in the matrix.\n */\n get size() {\n return this.rows * this.columns;\n }\n\n /**\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\n * @return {Matrix} this\n */\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n var ii = this.rows;\n var jj = this.columns;\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n /**\n * Returns a new 1D array filled row by row with the matrix values\n * @return {Array}\n */\n to1DArray() {\n var array = new Array(this.size);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n array[i * this.columns + j] = this.get(i, j);\n }\n }\n return array;\n }\n\n /**\n * Returns a 2D array containing a copy of the data\n * @return {Array}\n */\n to2DArray() {\n var copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n /**\n * @return {boolean} true if the matrix has one row\n */\n isRowVector() {\n return this.rows === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one column\n */\n isColumnVector() {\n return this.columns === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one row or one column\n */\n isVector() {\n return (this.rows === 1) || (this.columns === 1);\n }\n\n /**\n * @return {boolean} true if the matrix has the same number of rows and columns\n */\n isSquare() {\n return this.rows === this.columns;\n }\n\n /**\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\n */\n isSymmetric() {\n if (this.isSquare()) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j <= i; j++) {\n if (this.get(i, j) !== this.get(j, i)) {\n return false;\n }\n }\n }\n return true;\n }\n return false;\n }\n\n /**\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @param {number} value - The new value for the element\n * @return {Matrix} this\n */\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\n throw new Error('set method is unimplemented');\n }\n\n /**\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @return {number}\n */\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\n throw new Error('get method is unimplemented');\n }\n\n /**\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\n * rows of the matrix, and colRep times the number of columns of the matrix\n * @param {number} rowRep - Number of times the rows should be repeated\n * @param {number} colRep - Number of times the columns should be re\n * @return {Matrix}\n * @example\n * var matrix = new Matrix([[1,2]]);\n * matrix.repeat(2); // [[1,2],[1,2]]\n */\n repeat(rowRep, colRep) {\n rowRep = rowRep || 1;\n colRep = colRep || 1;\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\n for (var i = 0; i < rowRep; i++) {\n for (var j = 0; j < colRep; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n /**\n * Fills the matrix with a given value. All elements will be set to this value.\n * @param {number} value - New value\n * @return {Matrix} this\n */\n fill(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n /**\n * Negates the matrix. All elements will be multiplied by (-1)\n * @return {Matrix} this\n */\n neg() {\n return this.mulS(-1);\n }\n\n /**\n * Returns a new array from the given row index\n * @param {number} index - Row index\n * @return {Array}\n */\n getRow(index) {\n util.checkRowIndex(this, index);\n var row = new Array(this.columns);\n for (var i = 0; i < this.columns; i++) {\n row[i] = this.get(index, i);\n }\n return row;\n }\n\n /**\n * Returns a new row vector from the given row index\n * @param {number} index - Row index\n * @return {Matrix}\n */\n getRowVector(index) {\n return this.constructor.rowVector(this.getRow(index));\n }\n\n /**\n * Sets a row at the given index\n * @param {number} index - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setRow(index, array) {\n util.checkRowIndex(this, index);\n array = util.checkRowVector(this, array);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two rows\n * @param {number} row1 - First row index\n * @param {number} row2 - Second row index\n * @return {Matrix} this\n */\n swapRows(row1, row2) {\n util.checkRowIndex(this, row1);\n util.checkRowIndex(this, row2);\n for (var i = 0; i < this.columns; i++) {\n var temp = this.get(row1, i);\n this.set(row1, i, this.get(row2, i));\n this.set(row2, i, temp);\n }\n return this;\n }\n\n /**\n * Returns a new array from the given column index\n * @param {number} index - Column index\n * @return {Array}\n */\n getColumn(index) {\n util.checkColumnIndex(this, index);\n var column = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n column[i] = this.get(i, index);\n }\n return column;\n }\n\n /**\n * Returns a new column vector from the given column index\n * @param {number} index - Column index\n * @return {Matrix}\n */\n getColumnVector(index) {\n return this.constructor.columnVector(this.getColumn(index));\n }\n\n /**\n * Sets a column at the given index\n * @param {number} index - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setColumn(index, array) {\n util.checkColumnIndex(this, index);\n array = util.checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two columns\n * @param {number} column1 - First column index\n * @param {number} column2 - Second column index\n * @return {Matrix} this\n */\n swapColumns(column1, column2) {\n util.checkColumnIndex(this, column1);\n util.checkColumnIndex(this, column2);\n for (var i = 0; i < this.rows; i++) {\n var temp = this.get(i, column1);\n this.set(i, column1, this.get(i, column2));\n this.set(i, column2, temp);\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each row by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each column by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a row with a scalar\n * @param {number} index - Row index\n * @param {number} value\n * @return {Matrix} this\n */\n mulRow(index, value) {\n util.checkRowIndex(this, index);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n /**\n * Multiplies the values of a column with a scalar\n * @param {number} index - Column index\n * @param {number} value\n * @return {Matrix} this\n */\n mulColumn(index, value) {\n util.checkColumnIndex(this, index);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n /**\n * Returns the maximum value of the matrix\n * @return {number}\n */\n max() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value\n * @return {Array}\n */\n maxIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of the matrix\n * @return {number}\n */\n min() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value\n * @return {Array}\n */\n minIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n maxRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n maxRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n minRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n minRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n maxColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n maxColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n minColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n minColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns an array containing the diagonal values of the matrix\n * @return {Array}\n */\n diag() {\n var min = Math.min(this.rows, this.columns);\n var diag = new Array(min);\n for (var i = 0; i < min; i++) {\n diag[i] = this.get(i, i);\n }\n return diag;\n }\n\n /**\n * Returns the sum by the argument given, if no argument given,\n * it returns the sum of all elements of the matrix.\n * @param {string} by - sum by 'row' or 'column'.\n * @return {Matrix|number}\n */\n sum(by) {\n switch (by) {\n case 'row':\n return util.sumByRow(this);\n case 'column':\n return util.sumByColumn(this);\n default:\n return util.sumAll(this);\n }\n }\n\n /**\n * Returns the mean of all elements of the matrix\n * @return {number}\n */\n mean() {\n return this.sum() / this.size;\n }\n\n /**\n * Returns the product of all elements of the matrix\n * @return {number}\n */\n prod() {\n var prod = 1;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n prod *= this.get(i, j);\n }\n }\n return prod;\n }\n\n /**\n * Computes the cumulative sum of the matrix elements (in place, row by row)\n * @return {Matrix} this\n */\n cumulativeSum() {\n var sum = 0;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n sum += this.get(i, j);\n this.set(i, j, sum);\n }\n }\n return this;\n }\n\n /**\n * Computes the dot (scalar) product between the matrix and another\n * @param {Matrix} vector2 vector\n * @return {number}\n */\n dot(vector2) {\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n var vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n var dot = 0;\n for (var i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n /**\n * Returns the matrix product between this and other\n * @param {Matrix} other\n * @return {Matrix}\n */\n mmul(other) {\n other = this.constructor.checkMatrix(other);\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n var m = this.rows;\n var n = this.columns;\n var p = other.columns;\n\n var result = new this.constructor[Symbol.species](m, p);\n\n var Bcolj = new Array(n);\n for (var j = 0; j < p; j++) {\n for (var k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (var i = 0; i < m; i++) {\n var s = 0;\n for (k = 0; k < n; k++) {\n s += this.get(i, k) * Bcolj[k];\n }\n\n result.set(i, j, s);\n }\n }\n return result;\n }\n\n strassen2x2(other) {\n var result = new this.constructor[Symbol.species](2, 2);\n const a11 = this.get(0, 0);\n const b11 = other.get(0, 0);\n const a12 = this.get(0, 1);\n const b12 = other.get(0, 1);\n const a21 = this.get(1, 0);\n const b21 = other.get(1, 0);\n const a22 = this.get(1, 1);\n const b22 = other.get(1, 1);\n\n // Compute intermediate values.\n const m1 = (a11 + a22) * (b11 + b22);\n const m2 = (a21 + a22) * b11;\n const m3 = a11 * (b12 - b22);\n const m4 = a22 * (b21 - b11);\n const m5 = (a11 + a12) * b22;\n const m6 = (a21 - a11) * (b11 + b12);\n const m7 = (a12 - a22) * (b21 + b22);\n\n // Combine intermediate values into the output.\n const c00 = m1 + m4 - m5 + m7;\n const c01 = m3 + m5;\n const c10 = m2 + m4;\n const c11 = m1 - m2 + m3 + m6;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n return result;\n }\n\n strassen3x3(other) {\n var result = new this.constructor[Symbol.species](3, 3);\n\n const a00 = this.get(0, 0);\n const a01 = this.get(0, 1);\n const a02 = this.get(0, 2);\n const a10 = this.get(1, 0);\n const a11 = this.get(1, 1);\n const a12 = this.get(1, 2);\n const a20 = this.get(2, 0);\n const a21 = this.get(2, 1);\n const a22 = this.get(2, 2);\n\n const b00 = other.get(0, 0);\n const b01 = other.get(0, 1);\n const b02 = other.get(0, 2);\n const b10 = other.get(1, 0);\n const b11 = other.get(1, 1);\n const b12 = other.get(1, 2);\n const b20 = other.get(2, 0);\n const b21 = other.get(2, 1);\n const b22 = other.get(2, 2);\n\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\n const m2 = (a00 - a10) * (-b01 + b11);\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\n const m5 = (a10 + a11) * (-b00 + b01);\n const m6 = a00 * b00;\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\n const m8 = (-a00 + a20) * (b02 - b12);\n const m9 = (a20 + a21) * (-b00 + b02);\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\n const m13 = (a02 - a22) * (b11 - b21);\n const m14 = a02 * b20;\n const m15 = (a21 + a22) * (-b20 + b21);\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\n const m17 = (a02 - a12) * (b12 - b22);\n const m18 = (a11 + a12) * (-b20 + b22);\n const m19 = a01 * b10;\n const m20 = a12 * b21;\n const m21 = a10 * b02;\n const m22 = a20 * b01;\n const m23 = a22 * b22;\n\n const c00 = m6 + m14 + m19;\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\n const c11 = m2 + m4 + m5 + m6 + m20;\n const c12 = m14 + m16 + m17 + m18 + m21;\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\n const c21 = m12 + m13 + m14 + m15 + m22;\n const c22 = m6 + m7 + m8 + m9 + m23;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(0, 2, c02);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n result.set(1, 2, c12);\n result.set(2, 0, c20);\n result.set(2, 1, c21);\n result.set(2, 2, c22);\n return result;\n }\n\n /**\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\n * @param {Matrix} y\n * @return {Matrix}\n */\n mmulStrassen(y) {\n var x = this.clone();\n var r1 = x.rows;\n var c1 = x.columns;\n var r2 = y.rows;\n var c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\n }\n\n // Put a matrix into the top left of a matrix of zeros.\n // `rows` and `cols` are the dimensions of the output matrix.\n function embed(mat, rows, cols) {\n var r = mat.rows;\n var c = mat.columns;\n if ((r === rows) && (c === cols)) {\n return mat;\n } else {\n var resultat = Matrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\n }\n }\n\n\n // Make sure both matrices are the same size.\n // This is exclusively for simplicity:\n // this algorithm can be implemented with matrices of different sizes.\n\n var r = Math.max(r1, r2);\n var c = Math.max(c1, c2);\n x = embed(x, r, c);\n y = embed(y, r, c);\n\n // Our recursive multiplication function.\n function blockMult(a, b, rows, cols) {\n // For small matrices, resort to naive multiplication.\n if (rows <= 512 || cols <= 512) {\n return a.mmul(b); // a is equivalent to this\n }\n\n // Apply dynamic padding.\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\n a = embed(a, rows + 1, cols + 1);\n b = embed(b, rows + 1, cols + 1);\n } else if (rows % 2 === 1) {\n a = embed(a, rows + 1, cols);\n b = embed(b, rows + 1, cols);\n } else if (cols % 2 === 1) {\n a = embed(a, rows, cols + 1);\n b = embed(b, rows, cols + 1);\n }\n\n var halfRows = parseInt(a.rows / 2);\n var halfCols = parseInt(a.columns / 2);\n // Subdivide input matrices.\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\n\n // Combine intermediate values into the output.\n var c11 = Matrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n var c12 = Matrix.add(m3, m5);\n var c21 = Matrix.add(m2, m4);\n var c22 = Matrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n //Crop output to the desired size (undo dynamic padding).\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\n resultat = resultat.setSubMatrix(c11, 0, 0);\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\n }\n return blockMult(x, y, r, c);\n }\n\n /**\n * Returns a row-by-row scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The scaled matrix\n */\n scaleRows(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.rows; i++) {\n var scaled = arrayUtils.scale(this.getRow(i), {min, max});\n newMatrix.setRow(i, scaled);\n }\n return newMatrix;\n }\n\n /**\n * Returns a new column-by-column scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The new scaled matrix\n * @example\n * var matrix = new Matrix([[1,2],[-1,0]]);\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\n */\n scaleColumns(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.columns; i++) {\n var scaled = arrayUtils.scale(this.getColumn(i), {\n min: min,\n max: max\n });\n newMatrix.setColumn(i, scaled);\n }\n return newMatrix;\n }\n\n\n /**\n * Returns the Kronecker product (also known as tensor product) between this and other\n * See https://en.wikipedia.org/wiki/Kronecker_product\n * @param {Matrix} other\n * @return {Matrix}\n */\n kroneckerProduct(other) {\n other = this.constructor.checkMatrix(other);\n\n var m = this.rows;\n var n = this.columns;\n var p = other.rows;\n var q = other.columns;\n\n var result = new this.constructor[Symbol.species](m * p, n * q);\n for (var i = 0; i < m; i++) {\n for (var j = 0; j < n; j++) {\n for (var k = 0; k < p; k++) {\n for (var l = 0; l < q; l++) {\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Transposes the matrix and returns a new one containing the result\n * @return {Matrix}\n */\n transpose() {\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n /**\n * Sorts the rows (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortRows(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Sorts the columns (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortColumns(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Returns a subset of the matrix\n * @param {number} startRow - First row index\n * @param {number} endRow - Last row index\n * @param {number} startColumn - First column index\n * @param {number} endColumn - Last column index\n * @return {Matrix}\n */\n subMatrix(startRow, endRow, startColumn, endColumn) {\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\n for (var i = startRow; i <= endRow; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of row indices\n * @param {Array} indices - Array containing the row indices\n * @param {number} [startColumn = 0] - First column index\n * @param {number} [endColumn = this.columns-1] - Last column index\n * @return {Matrix}\n */\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n if (indices[i] < 0 || indices[i] >= this.rows) {\n throw new RangeError('Row index out of range: ' + indices[i]);\n }\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of column indices\n * @param {Array} indices - Array containing the column indices\n * @param {number} [startRow = 0] - First row index\n * @param {number} [endRow = this.rows-1] - Last row index\n * @return {Matrix}\n */\n subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startRow; j <= endRow; j++) {\n if (indices[i] < 0 || indices[i] >= this.columns) {\n throw new RangeError('Column index out of range: ' + indices[i]);\n }\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\n }\n }\n return newMatrix;\n }\n\n /**\n * Set a part of the matrix to the given sub-matrix\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\n * @param {number} startRow - The index of the first row to set\n * @param {number} startColumn - The index of the first column to set\n * @return {Matrix}\n */\n setSubMatrix(matrix, startRow, startColumn) {\n matrix = this.constructor.checkMatrix(matrix);\n var endRow = startRow + matrix.rows - 1;\n var endColumn = startColumn + matrix.columns - 1;\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n this[startRow + i][startColumn + j] = matrix.get(i, j);\n }\n }\n return this;\n }\n\n /**\n * Return a new matrix based on a selection of rows and columns\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\n * @return {Matrix} The new matrix\n */\n selection(rowIndices, columnIndices) {\n var indices = util.checkIndices(this, rowIndices, columnIndices);\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\n for (var i = 0; i < indices.row.length; i++) {\n var rowIndex = indices.row[i];\n for (var j = 0; j < indices.column.length; j++) {\n var columnIndex = indices.column[j];\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns the trace of the matrix (sum of the diagonal elements)\n * @return {number}\n */\n trace() {\n var min = Math.min(this.rows, this.columns);\n var trace = 0;\n for (var i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n /*\n Matrix views\n */\n\n /**\n * Returns a view of the transposition of the matrix\n * @return {MatrixTransposeView}\n */\n transposeView() {\n return new MatrixTransposeView(this);\n }\n\n /**\n * Returns a view of the row vector with the given index\n * @param {number} row - row index of the vector\n * @return {MatrixRowView}\n */\n rowView(row) {\n util.checkRowIndex(this, row);\n return new MatrixRowView(this, row);\n }\n\n /**\n * Returns a view of the column vector with the given index\n * @param {number} column - column index of the vector\n * @return {MatrixColumnView}\n */\n columnView(column) {\n util.checkColumnIndex(this, column);\n return new MatrixColumnView(this, column);\n }\n\n /**\n * Returns a view of the matrix flipped in the row axis\n * @return {MatrixFlipRowView}\n */\n flipRowView() {\n return new MatrixFlipRowView(this);\n }\n\n /**\n * Returns a view of the matrix flipped in the column axis\n * @return {MatrixFlipColumnView}\n */\n flipColumnView() {\n return new MatrixFlipColumnView(this);\n }\n\n /**\n * Returns a view of a submatrix giving the index boundaries\n * @param {number} startRow - first row index of the submatrix\n * @param {number} endRow - last row index of the submatrix\n * @param {number} startColumn - first column index of the submatrix\n * @param {number} endColumn - last column index of the submatrix\n * @return {MatrixSubView}\n */\n subMatrixView(startRow, endRow, startColumn, endColumn) {\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\n }\n\n /**\n * Returns a view of the cross of the row indices and the column indices\n * @example\n * // resulting vector is [[2], [2]]\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\n * @param {Array} rowIndices\n * @param {Array} columnIndices\n * @return {MatrixSelectionView}\n */\n selectionView(rowIndices, columnIndices) {\n return new MatrixSelectionView(this, rowIndices, columnIndices);\n }\n\n\n /**\n * Calculates and returns the determinant of a matrix as a Number\n * @example\n * new Matrix([[1,2,3], [4,5,6]]).det()\n * @return {number}\n */\n det() {\n if (this.isSquare()) {\n var a, b, c, d;\n if (this.columns === 2) {\n // 2 x 2 matrix\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(1, 0);\n d = this.get(1, 1);\n\n return a * d - (b * c);\n } else if (this.columns === 3) {\n // 3 x 3 matrix\n var subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(0, 2);\n\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(this).determinant;\n }\n\n } else {\n throw Error('Determinant can only be calculated for a square matrix.');\n }\n }\n }\n\n Matrix.prototype.klass = 'Matrix';\n\n /**\n * @private\n * Check that two matrices have the same dimensions\n * @param {Matrix} matrix\n * @param {Matrix} otherMatrix\n */\n function checkDimensions(matrix, otherMatrix) { // eslint-disable-line no-unused-vars\n if (matrix.rows !== otherMatrix.rows ||\n matrix.columns !== otherMatrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n }\n\n function compareNumbers(a, b) {\n return a - b;\n }\n\n /*\n Synonyms\n */\n\n Matrix.random = Matrix.rand;\n Matrix.diagonal = Matrix.diag;\n Matrix.prototype.diagonal = Matrix.prototype.diag;\n Matrix.identity = Matrix.eye;\n Matrix.prototype.negate = Matrix.prototype.neg;\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\n Matrix.prototype.determinant = Matrix.prototype.det;\n\n /*\n Add dynamically instance and static methods for mathematical operations\n */\n\n var inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var inplaceOperatorScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n`;\n\n var inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n checkDimensions(this, matrix);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n`;\n\n var staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n`;\n\n var inplaceMethod = `\n(function %name%() {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%();\n})\n`;\n\n var inplaceMethodWithArgs = `\n(function %name%(%args%) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), %args%));\n }\n }\n return this;\n})\n`;\n\n var staticMethodWithArgs = `\n(function %name%(matrix, %args%) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(%args%);\n})\n`;\n\n\n var inplaceMethodWithOneArgScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), value));\n }\n }\n return this;\n})\n`;\n var inplaceMethodWithOneArgMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n checkDimensions(this, matrix);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var inplaceMethodWithOneArg = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var staticMethodWithOneArg = staticMethodWithArgs;\n\n var operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n ];\n\n var i;\n\n for (var operator of operators) {\n var inplaceOp = eval(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]}));\n var inplaceOpS = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]}));\n var inplaceOpM = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]}));\n var staticOp = eval(fillTemplateFunction(staticOperator, {name: operator[1]}));\n for (i = 1; i < operator.length; i++) {\n Matrix.prototype[operator[i]] = inplaceOp;\n Matrix.prototype[operator[i] + 'S'] = inplaceOpS;\n Matrix.prototype[operator[i] + 'M'] = inplaceOpM;\n Matrix[operator[i]] = staticOp;\n }\n }\n\n var methods = [\n ['~', 'not']\n ];\n\n [\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n ].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n });\n\n for (var method of methods) {\n var inplaceMeth = eval(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]}));\n var staticMeth = eval(fillTemplateFunction(staticMethod, {name: method[1]}));\n for (i = 1; i < method.length; i++) {\n Matrix.prototype[method[i]] = inplaceMeth;\n Matrix[method[i]] = staticMeth;\n }\n }\n\n var methodsWithArgs = [\n ['Math.pow', 1, 'pow']\n ];\n\n for (var methodWithArg of methodsWithArgs) {\n var args = 'arg0';\n for (i = 1; i < methodWithArg[1]; i++) {\n args += `, arg${i}`;\n }\n if (methodWithArg[1] !== 1) {\n var inplaceMethWithArgs = eval(fillTemplateFunction(inplaceMethodWithArgs, {\n name: methodWithArg[2],\n method: methodWithArg[0],\n args: args\n }));\n var staticMethWithArgs = eval(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args}));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\n Matrix[methodWithArg[i]] = staticMethWithArgs;\n }\n } else {\n var tmplVar = {\n name: methodWithArg[2],\n args: args,\n method: methodWithArg[0]\n };\n var inplaceMethod2 = eval(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\n var inplaceMethodS = eval(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\n var inplaceMethodM = eval(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\n var staticMethod2 = eval(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\n Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM;\n Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS;\n Matrix[methodWithArg[i]] = staticMethod2;\n }\n }\n }\n\n function fillTemplateFunction(template, values) {\n for (var value in values) {\n template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]);\n }\n return template;\n }\n\n return Matrix;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/abstractMatrix.js\n// module id = 37\n// module chunks = 0","'use strict';\n\nvar Matrix = require('../matrix');\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\nfunction LuDecomposition(matrix) {\n if (!(this instanceof LuDecomposition)) {\n return new LuDecomposition(matrix);\n }\n\n matrix = Matrix.Matrix.checkMatrix(matrix);\n\n var lu = matrix.clone(),\n rows = lu.rows,\n columns = lu.columns,\n pivotVector = new Array(rows),\n pivotSign = 1,\n i, j, k, p, s, t, v,\n LUrowi, LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Array(rows);\n\n for (j = 0; j < columns; j++) {\n\n for (i = 0; i < rows; i++) {\n LUcolj[i] = lu[i][j];\n }\n\n for (i = 0; i < rows; i++) {\n LUrowi = lu[i];\n kmax = Math.min(i, j);\n s = 0;\n for (k = 0; k < kmax; k++) {\n s += LUrowi[k] * LUcolj[k];\n }\n LUrowi[j] = LUcolj[i] -= s;\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[p][k];\n lu[p][k] = lu[j][k];\n lu[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[j][j] !== 0) {\n for (i = j + 1; i < rows; i++) {\n lu[i][j] /= lu[j][j];\n }\n }\n }\n\n this.LU = lu;\n this.pivotVector = pivotVector;\n this.pivotSign = pivotSign;\n}\n\nLuDecomposition.prototype = {\n isSingular: function () {\n var data = this.LU,\n col = data.columns;\n for (var j = 0; j < col; j++) {\n if (data[j][j] === 0) {\n return true;\n }\n }\n return false;\n },\n get determinant() {\n var data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n var determinant = this.pivotSign, col = data.columns;\n for (var j = 0; j < col; j++) {\n determinant *= data[j][j];\n }\n return determinant;\n },\n get lowerTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix.Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i > j) {\n X[i][j] = data[i][j];\n } else if (i === j) {\n X[i][j] = 1;\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get upperTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix.Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i <= j) {\n X[i][j] = data[i][j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get pivotPermutationVector() {\n return this.pivotVector.slice();\n },\n solve: function (value) {\n value = Matrix.Matrix.checkMatrix(value);\n\n var lu = this.LU,\n rows = lu.rows;\n\n if (rows !== value.rows) {\n throw new Error('Invalid matrix dimensions');\n }\n if (this.isSingular()) {\n throw new Error('LU matrix is singular');\n }\n\n var count = value.columns;\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n var columns = lu.columns;\n var i, j, k;\n\n for (k = 0; k < columns; k++) {\n for (i = k + 1; i < columns; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= lu[k][k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n return X;\n }\n};\n\nmodule.exports = LuDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/lu.js\n// module id = 38\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\nvar Stat = require('ml-stat');\n\nmodule.exports.NaiveBayes = NaiveBayes;\nmodule.exports.separateClasses = separateClasses;\n\n/**\n * Constructor for the Naive Bayes classifier, the parameters here is just for loading purposes.\n *\n * @param reload\n * @param model\n * @constructor\n */\nfunction NaiveBayes(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 trainingSet\n * @param trainingLabels\n */\nNaiveBayes.prototype.train = function (trainingSet, trainingLabels) {\n var C1 = Math.sqrt(2*Math.PI); // constant to precalculate the squared root\n if(!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet);\n else trainingSet = trainingSet.clone();\n\n if(trainingSet.rows !== trainingLabels.length)\n throw new RangeError(\"the size of the training set and the training labels must be the same.\");\n\n var separatedClasses = separateClasses(trainingSet, trainingLabels);\n var calculateProbabilities = new Array(separatedClasses.length);\n this.means = new Array(separatedClasses.length);\n for(var i = 0; i < separatedClasses.length; ++i) {\n var means = Stat.matrix.mean(separatedClasses[i]);\n var std = Stat.matrix.standardDeviation(separatedClasses[i], means);\n\n var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows);\n calculateProbabilities[i] = new Array(means.length + 1);\n\n calculateProbabilities[i][0] = logPriorProbability;\n for(var j = 1; j < means.length + 1; ++j) {\n var currentStd = std[j - 1];\n calculateProbabilities[i][j] = [(1 / (C1 * currentStd)), -2*currentStd*currentStd];\n }\n\n this.means[i] = means;\n }\n\n this.calculateProbabilities = calculateProbabilities;\n};\n\n/**\n * function that predicts each row of the dataset (must be a matrix).\n *\n * @param dataset\n * @returns {Array}\n */\nNaiveBayes.prototype.predict = function (dataset) {\n if(dataset[0].length === this.calculateProbabilities[0].length)\n throw new RangeError('the dataset must have the same features as the training set');\n\n var predictions = new Array(dataset.length);\n\n for(var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities);\n }\n\n return predictions;\n};\n\n/**\n * Function the retrieves a prediction with one case.\n *\n * @param currentCase\n * @param mean - Precalculated means of each class trained\n * @param classes - Precalculated value of each class (Prior probability and probability function of each feature)\n * @returns {number}\n */\nfunction getCurrentClass(currentCase, mean, classes) {\n var maxProbability = 0;\n var predictedClass = -1;\n\n // going through all precalculated values for the classes\n for(var i = 0; i < classes.length; ++i) {\n var currentProbability = classes[i][0]; // initialize with the prior probability\n for(var j = 1; j < classes[0][1].length + 1; ++j) {\n currentProbability += calculateLogProbability(currentCase[j - 1], mean[i][j - 1], classes[i][j][0], classes[i][j][1]);\n }\n\n currentProbability = Math.exp(currentProbability);\n if(currentProbability > maxProbability) {\n maxProbability = currentProbability;\n predictedClass = i;\n }\n }\n\n return predictedClass;\n}\n\n/**\n * Function that export the NaiveBayes model.\n * @returns {{modelName: string, means: *, calculateProbabilities: *}}\n */\nNaiveBayes.prototype.export = function () {\n return {\n modelName: \"NaiveBayes\",\n means: this.means,\n calculateProbabilities: this.calculateProbabilities\n };\n};\n\n/**\n * Function that create a Naive Bayes classifier with the given model.\n * @param model\n * @returns {NaiveBayes}\n */\nNaiveBayes.load = function (model) {\n if(model.modelName !== 'NaiveBayes')\n throw new RangeError(\"The given model is invalid!\");\n\n return new NaiveBayes(true, model);\n};\n\n/**\n * function that retrieves the probability of the feature given the class.\n * @param value - value of the feature.\n * @param mean - mean of the feature for the given class.\n * @param C1 - precalculated value of (1 / (sqrt(2*pi) * std)).\n * @param C2 - precalculated value of (2 * std^2) for the denominator of the exponential.\n * @returns {number}\n */\nfunction calculateLogProbability(value, mean, C1, C2) {\n var value = value - mean;\n return Math.log(C1 * Math.exp((value * value) / C2))\n}\n\n/**\n * Function that retuns an array of matrices of the cases that belong to each class.\n * @param X - dataset\n * @param y - predictions\n * @returns {Array}\n */\nfunction separateClasses(X, y) {\n var features = X.columns;\n\n var classes = 0;\n var totalPerClasses = new Array(100); // max upperbound of classes\n for (var i = 0; i < y.length; i++) {\n if(totalPerClasses[y[i]] === undefined) {\n totalPerClasses[y[i]] = 0;\n classes++;\n }\n totalPerClasses[y[i]]++;\n }\n var separatedClasses = new Array(classes);\n var currentIndex = new Array(classes);\n for(i = 0; i < classes; ++i) {\n separatedClasses[i] = new Matrix(totalPerClasses[i], features);\n currentIndex[i] = 0;\n }\n for(i = 0; i < X.rows; ++i) {\n separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i));\n currentIndex[y[i]]++;\n }\n return separatedClasses;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-naivebayes/src/naiveBayes.js\n// module id = 39\n// module chunks = 0","'use strict';\n\n/**\n * Function that return a constants of the M degree polynomial that\n * fit the given points, this constants is given from lower to higher\n * order of the polynomial.\n *\n * @param {Vector} X - Vector of the x positions of the points.\n * @param {Vector} Y - Vector of the y positions of the points.\n * @param {Number|BigNumber} M - Degree of the polynomial.\n * @param {Vector} constants - Vector of constants of the function.\n * Created by acastillo on 5/12/16.\n */\n\nconst maybeToPrecision = require('./util').maybeToPrecision;\nconst BaseRegression = require('./base-regression');\nconst Matrix = require('ml-matrix');\n\n\nclass PolynomialRegression extends BaseRegression {\n /**\n * @constructor\n * @param x: Independent variable\n * @param y: Dependent variable\n * @param M: Maximum degree of the polynomial\n * @param options\n */\n constructor(x, y, M, options) {\n super();\n let opt = options || {};\n if (x === true) { // reloading model\n this.coefficients = y.coefficients;\n this.powers = y.powers;\n this.M = y.M;\n if (y.quality) {\n this.quality = y.quality;\n }\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n\n let powers;\n if (Array.isArray(M)) {\n powers = M;\n M = powers.length;\n } else {\n M++;\n powers = new Array(M);\n for (k = 0; k < M; k++) {\n powers[k] = k;\n }\n }\n var F = new Matrix(n, M);\n var Y = new Matrix([y]);\n var k, i;\n for (k = 0; k < M; k++) {\n for (i = 0; i < n; i++) {\n if (powers[k] === 0) {\n F[i][k] = 1;\n } else {\n F[i][k] = Math.pow(x[i], powers[k]);\n }\n }\n }\n\n var FT = F.transposeView();\n var A = FT.mmul(F);\n var B = FT.mmul(Y.transposeView());\n\n this.coefficients = A.solve(B).to1DArray();\n this.powers = powers;\n this.M = M - 1;\n if (opt.computeQuality) {\n this.quality = this.modelQuality(x, y);\n }\n }\n }\n\n _predict(x) {\n var y = 0;\n for (var 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 var out = {name: 'polynomialRegression',\n coefficients: this.coefficients,\n powers: this.powers,\n M: this.M\n };\n\n if (this.quality) {\n out.quality = this.quality;\n }\n return out;\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 var sup = '^';\n var closeSup = '';\n var times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n var fn = '', str;\n for (var k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === ' + ') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'polynomialRegression') {\n throw new TypeError('not a polynomial regression model');\n }\n return new PolynomialRegression(true, json);\n }\n}\n\nmodule.exports = PolynomialRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/polynomial-regression.js\n// module id = 40\n// module chunks = 0","'use strict';\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n/**\n * Computes the sum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.sum = function sum(values) {\n var sum = 0;\n for (var i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum;\n};\n\n/**\n * Computes the maximum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.max = function max(values) {\n var max = -Infinity;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] > max) max = values[i];\n }\n return max;\n};\n\n/**\n * Computes the minimum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.min = function min(values) {\n var min = Infinity;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] < min) min = values[i];\n }\n return min;\n};\n\n/**\n * Computes the min and max of the given values\n * @param {Array} values\n * @returns {{min: number, max: number}}\n */\nexports.minMax = function minMax(values) {\n var min = Infinity;\n var max = -Infinity;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] < min) min = values[i];\n if (values[i] > max) max = values[i];\n }\n return {\n min: min,\n max: max\n };\n};\n\n/**\n * Computes the arithmetic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.arithmeticMean = function arithmeticMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n sum += values[i];\n }\n return sum / l;\n};\n\n/**\n * {@link arithmeticMean}\n */\nexports.mean = exports.arithmeticMean;\n\n/**\n * Computes the geometric mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.geometricMean = function geometricMean(values) {\n var mul = 1;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n mul *= values[i];\n }\n return Math.pow(mul, 1 / l);\n};\n\n/**\n * Computes the mean of the log of the given values\n * If the return value is exponentiated, it gives the same result as the\n * geometric mean.\n * @param {Array} values\n * @returns {number}\n */\nexports.logMean = function logMean(values) {\n var lnsum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n lnsum += Math.log(values[i]);\n }\n return lnsum / l;\n};\n\n/**\n * Computes the weighted grand mean for a list of means and sample sizes\n * @param {Array} means - Mean values for each set of samples\n * @param {Array} samples - Number of original values for each set of samples\n * @returns {number}\n */\nexports.grandMean = function grandMean(means, samples) {\n var sum = 0;\n var n = 0;\n var l = means.length;\n for (var i = 0; i < l; i++) {\n sum += samples[i] * means[i];\n n += samples[i];\n }\n return sum / n;\n};\n\n/**\n * Computes the truncated mean of the given values using a given percentage\n * @param {Array} values\n * @param {number} percent - The percentage of values to keep (range: [0,1])\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = values.slice().sort(compareNumbers);\n }\n var l = values.length;\n var k = Math.floor(l * percent);\n var sum = 0;\n for (var i = k; i < (l - k); i++) {\n sum += values[i];\n }\n return sum / (l - 2 * k);\n};\n\n/**\n * Computes the harmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.harmonicMean = function harmonicMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] === 0) {\n throw new RangeError('value at index ' + i + 'is zero');\n }\n sum += 1 / values[i];\n }\n return l / sum;\n};\n\n/**\n * Computes the contraharmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.contraHarmonicMean = function contraHarmonicMean(values) {\n var r1 = 0;\n var r2 = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n r1 += values[i] * values[i];\n r2 += values[i];\n }\n if (r2 < 0) {\n throw new RangeError('sum of values is negative');\n }\n return r1 / r2;\n};\n\n/**\n * Computes the median of the given values\n * @param {Array} values\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.median = function median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = values.slice().sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n};\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.variance = function variance(values, unbiased) {\n if (unbiased === undefined) unbiased = true;\n var theMean = exports.mean(values);\n var theVariance = 0;\n var l = values.length;\n\n for (var i = 0; i < l; i++) {\n var x = values[i] - theMean;\n theVariance += x * x;\n }\n\n if (unbiased) {\n return theVariance / (l - 1);\n } else {\n return theVariance / l;\n }\n};\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.standardDeviation = function standardDeviation(values, unbiased) {\n return Math.sqrt(exports.variance(values, unbiased));\n};\n\nexports.standardError = function standardError(values) {\n return exports.standardDeviation(values) / Math.sqrt(values.length);\n};\n\nexports.quartiles = function quartiles(values, alreadySorted) {\n if (typeof(alreadySorted) === 'undefined') alreadySorted = false;\n if (!alreadySorted) {\n values = values.slice();\n values.sort(compareNumbers);\n }\n\n var quart = values.length / 4;\n var q1 = values[Math.ceil(quart) - 1];\n var q2 = exports.median(values, true);\n var q3 = values[Math.ceil(quart * 3) - 1];\n\n return {q1: q1, q2: q2, q3: q3};\n};\n\nexports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {\n return Math.sqrt(exports.pooledVariance(samples, unbiased));\n};\n\nexports.pooledVariance = function pooledVariance(samples, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var sum = 0;\n var length = 0, l = samples.length;\n for (var i = 0; i < l; i++) {\n var values = samples[i];\n var vari = exports.variance(values);\n\n sum += (values.length - 1) * vari;\n\n if (unbiased)\n length += values.length - 1;\n else\n length += values.length;\n }\n return sum / length;\n};\n\nexports.mode = function mode(values) {\n var l = values.length,\n itemCount = new Array(l),\n i;\n for (i = 0; i < l; i++) {\n itemCount[i] = 0;\n }\n var itemArray = new Array(l);\n var count = 0;\n\n for (i = 0; i < l; i++) {\n var index = itemArray.indexOf(values[i]);\n if (index >= 0)\n itemCount[index]++;\n else {\n itemArray[count] = values[i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (i = 0; i < count; i++) {\n if (itemCount[i] > maxValue) {\n maxValue = itemCount[i];\n maxIndex = i;\n }\n }\n\n return itemArray[maxIndex];\n};\n\nexports.covariance = function covariance(vector1, vector2, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var mean1 = exports.mean(vector1);\n var mean2 = exports.mean(vector2);\n\n if (vector1.length !== vector2.length)\n throw \"Vectors do not have the same dimensions\";\n\n var cov = 0, l = vector1.length;\n for (var i = 0; i < l; i++) {\n var x = vector1[i] - mean1;\n var y = vector2[i] - mean2;\n cov += x * y;\n }\n\n if (unbiased)\n return cov / (l - 1);\n else\n return cov / l;\n};\n\nexports.skewness = function skewness(values, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n\n var s2 = 0, s3 = 0, l = values.length;\n for (var i = 0; i < l; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n var m2 = s2 / l;\n var m3 = s3 / l;\n\n var g = m3 / (Math.pow(m2, 3 / 2.0));\n if (unbiased) {\n var a = Math.sqrt(l * (l - 1));\n var b = l - 2;\n return (a / b) * g;\n }\n else {\n return g;\n }\n};\n\nexports.kurtosis = function kurtosis(values, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n var n = values.length, s2 = 0, s4 = 0;\n\n for (var i = 0; i < n; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n\n return a * b - 3 * c;\n }\n else {\n return m4 / (m2 * m2) - 3;\n }\n};\n\nexports.entropy = function entropy(values, eps) {\n if (typeof(eps) === 'undefined') eps = 0;\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * Math.log(values[i] + eps);\n return -sum;\n};\n\nexports.weightedMean = function weightedMean(values, weights) {\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * weights[i];\n return sum;\n};\n\nexports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {\n return Math.sqrt(exports.weightedVariance(values, weights));\n};\n\nexports.weightedVariance = function weightedVariance(values, weights) {\n var theMean = exports.weightedMean(values, weights);\n var vari = 0, l = values.length;\n var a = 0, b = 0;\n\n for (var i = 0; i < l; i++) {\n var z = values[i] - theMean;\n var w = weights[i];\n\n vari += w * (z * z);\n b += w;\n a += w * w;\n }\n\n return vari * (b / (b * b - a));\n};\n\nexports.center = function center(values, inPlace) {\n if (typeof(inPlace) === 'undefined') inPlace = false;\n\n var result = values;\n if (!inPlace)\n result = values.slice();\n\n var theMean = exports.mean(result), l = result.length;\n for (var i = 0; i < l; i++)\n result[i] -= theMean;\n};\n\nexports.standardize = function standardize(values, standardDev, inPlace) {\n if (typeof(standardDev) === 'undefined') standardDev = exports.standardDeviation(values);\n if (typeof(inPlace) === 'undefined') inPlace = false;\n var l = values.length;\n var result = inPlace ? values : new Array(l);\n for (var i = 0; i < l; i++)\n result[i] = values[i] / standardDev;\n return result;\n};\n\nexports.cumulativeSum = function cumulativeSum(array) {\n var l = array.length;\n var result = new Array(l);\n result[0] = array[0];\n for (var i = 1; i < l; i++)\n result[i] = result[i - 1] + array[i];\n return result;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-savitzky-golay-generalized/~/ml-stat/array.js\n// module id = 41\n// module chunks = 0","function NodeSquare(x, y, weights, som) {\n this.x = x;\n this.y = y;\n this.weights = weights;\n this.som = som;\n this.neighbors = {};\n}\n\nNodeSquare.prototype.adjustWeights = function adjustWeights(target, learningRate, influence) {\n for (var i = 0, ii = this.weights.length; i < ii; i++) {\n this.weights[i] += learningRate * influence * (target[i] - this.weights[i]);\n }\n};\n\nNodeSquare.prototype.getDistance = function getDistance(otherNode) {\n return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y));\n};\n\nNodeSquare.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.x - otherNode.x),\n distY = Math.abs(this.y - otherNode.y);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY));\n};\n\nNodeSquare.prototype.getNeighbors = function getNeighbors(xy) {\n if (!this.neighbors[xy]) {\n this.neighbors[xy] = new Array(2);\n\n // left or bottom neighbor\n var v;\n if (this[xy] > 0) {\n v = this[xy] - 1;\n } else if (this.som.torus) {\n v = this.som.gridDim[xy] - 1\n }\n if (typeof v !== 'undefined') {\n var x, y;\n if (xy === 'x') {\n x = v;\n y = this.y;\n } else {\n x = this.x;\n y = v;\n }\n this.neighbors[xy][0] = this.som.nodes[x][y];\n }\n\n // top or right neighbor\n var w;\n if (this[xy] < (this.som.gridDim[xy] - 1)) {\n w = this[xy] + 1;\n } else if (this.som.torus) {\n w = 0;\n }\n if (typeof w !== 'undefined') {\n if (xy === 'x') {\n x = w;\n y = this.y;\n } else {\n x = this.x;\n y = w;\n }\n this.neighbors[xy][1] = this.som.nodes[x][y];\n }\n }\n return this.neighbors[xy];\n};\n\nNodeSquare.prototype.getPos = function getPos(xy, element) {\n var neighbors = this.getNeighbors(xy),\n distance = this.som.distance,\n bestNeighbor,\n direction;\n if(neighbors[0]) {\n if (neighbors[1]) {\n var dist1 = distance(element, neighbors[0].weights),\n dist2 = distance(element, neighbors[1].weights);\n if(dist1 < dist2) {\n bestNeighbor = neighbors[0];\n direction = -1;\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n } else {\n bestNeighbor = neighbors[0];\n direction = -1;\n }\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n var simA = 1 - distance(element, this.weights),\n simB = 1 - distance(element, bestNeighbor.weights);\n var factor = ((simA - simB) / (2 - simA - simB));\n return 0.5 + 0.5 * factor * direction;\n};\n\nNodeSquare.prototype.getPosition = function getPosition(element) {\n return [\n this.getPos('x', element),\n this.getPos('y', element)\n ];\n};\n\nmodule.exports = NodeSquare;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-som/src/node-square.js\n// module id = 42\n// module chunks = 0","'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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-bit-array/src/index.js\n// module id = 43\n// module chunks = 0","'use strict';\n\nconst ConfusionMatrix = require('./ConfusionMatrix');\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 validation\n * set while the rest is used as the training set. This is repeated once for each observation. LOO-CV is a special case\n * of LPO-CV. @see leavePout\n * @param {constructor} Classifier - The classifier 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 * @returns {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leaveOneOut = function (Classifier, features, labels, classifierOptions) {\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 Classifier - The classifier 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} p - The size of the validation sub-samples' set\n * @returns {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leavePOut = function (Classifier, features, labels, classifierOptions, p) {\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n var i, N = features.length;\n var gen = combinations(p, N);\n var allIdx = new Array(N);\n for (i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n for (const testIdx of gen) {\n var trainIdx = allIdx.slice();\n\n for (i = testIdx.length - 1; i >= 0; i--) {\n trainIdx.splice(testIdx[i], 1);\n }\n\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\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 Classifier - The classifier 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 * @returns {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.kFold = function (Classifier, features, labels, classifierOptions, k) {\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 validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\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 var testFeatures = testIdx.map(function (index) {\n return features[index];\n });\n var trainFeatures = trainIdx.map(function (index) {\n return features[index];\n });\n var testLabels = testIdx.map(function (index) {\n return labels[index];\n });\n var trainLabels = trainIdx.map(function (index) {\n return labels[index];\n });\n\n var classifier = new Classifier(classifierOptions);\n classifier.train(trainFeatures, trainLabels);\n var predictedLabels = classifier.predict(testFeatures);\n for (var i = 0; i < predictedLabels.length; i++) {\n confusionMatrix[distinct.indexOf(testLabels[i])][distinct.indexOf(predictedLabels[i])]++;\n }\n}\n\nmodule.exports = CV;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-cross-validation/src/crossValidation.js\n// module id = 44\n// module chunks = 0","'use strict';\n\n\n/**\n * Computes a distance/similarity matrix given an array of data and a distance/similarity function.\n * @param {Array} data An array of data\n * @param {function} distanceFn A function that accepts two arguments and computes a distance/similarity between them\n * @return {Array} The similarity matrix. The similarity matrix is square and has a size equal to the length of\n * the data array\n */\nfunction distanceMatrix(data, distanceFn) {\n const length = data.length;\n let result = Array.from({length}).map(() => Array.from({length}));\n\n // Compute upper distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n }\n }\n\n // Copy to lower distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = i + 1; j < length; j++) {\n result[i][j] = result[j][i];\n }\n }\n\n return result;\n}\n\nmodule.exports = distanceMatrix;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance-matrix/src/index.js\n// module id = 45\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix');\n\nconst Layer = require('./Layer');\nconst OutputLayer = require('./OutputLayer');\nconst Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass FeedForwardNeuralNetworks {\n\n /**\n * Create a new Feedforword neural network model.\n * @param {object} options\n * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers.\n * @oaram {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 * @poram {number} [options.regularization=0.01] - Regularization parameter af the neural net.\n * @poram {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 === undefined ? [10] : options.hiddenLayers;\n this.iterations = options.iterations === undefined ? 50 : options.iterations;\n\n this.learningRate = options.learningRate === undefined ? 0.01 : options.learningRate;\n //this.momentum = options.momentum === undefined ? 0.1 : options.momentum;\n this.regularization = options.regularization === undefined ? 0.01 : options.regularization;\n\n this.activation = options.activation === undefined ? 'tanh' : options.activation;\n this.activationParam = options.activationParam === undefined ? 1 : options.activationParam;\n if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) {\n this.activation = 'tanh';\n }\n }\n }\n\n /**\n * Function that build and initialize the neural net.\n * @param {number} inputSize - total of features to fit.\n * @param {number} outputSize - total of labels of the prediction set.\n */\n buildNetwork(inputSize, outputSize) {\n var size = 2 + (this.hiddenLayers.length - 1);\n this.model = new Array(size);\n\n // input layer\n this.model[0] = new Layer({\n inputSize: inputSize,\n outputSize: this.hiddenLayers[0],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n\n // hidden layers\n for (var i = 1; i < this.hiddenLayers.length; ++i) {\n this.model[i] = new Layer({\n inputSize: this.hiddenLayers[i - 1],\n outputSize: this.hiddenLayers[i],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n // output layer\n this.model[size - 1] = new OutputLayer({\n inputSize: this.hiddenLayers[this.hiddenLayers.length - 1],\n outputSize: outputSize,\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n /**\n * Train the neural net with the given features and labels.\n * @param {Matrix|Array} features\n * @param {Matrix|Array} labels\n */\n train(features, labels) {\n features = Matrix.checkMatrix(features);\n this.dicts = Utils.dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n this.buildNetwork(inputSize, outputSize);\n\n for (var i = 0; i < this.iterations; ++i) {\n var probabilities = this.propagate(features);\n this.backpropagation(features, labels, probabilities);\n }\n }\n\n /**\n * Propagate the input(training set) and retrives the probabilities of each class.\n * @param {Matrix} X\n * @return {Matrix} probabilities of each class.\n */\n propagate(X) {\n var input = X;\n for (var i = 0; i < this.model.length; ++i) {\n //console.log(i);\n input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(Utils.sumRow(input));\n }\n\n /**\n * Function that applies the backpropagation algorithm on each layer of the network\n * in order to fit the features and labels.\n * @param {Matrix} features\n * @param {Array} labels\n * @param {Matrix} probabilities - probabilities of each class of the feature set.\n */\n backpropagation(features, labels, probabilities) {\n for (var i = 0; i < probabilities.length; ++i) {\n probabilities[i][this.dicts.inputs[labels[i]]] -= 1;\n }\n\n // remember, the last delta doesn't matter\n var delta = probabilities;\n for (i = this.model.length - 1; i >= 0; --i) {\n var a = i > 0 ? this.model[i - 1].a : features;\n delta = this.model[i].backpropagation(delta, a);\n }\n\n for (i = 0; i < this.model.length; ++i) {\n this.model[i].update();\n }\n }\n\n /**\n * Predict the output given the feature set.\n * @param {Array|Matrix} features\n * @return {Array}\n */\n predict(features) {\n features = Matrix.checkMatrix(features);\n var outputs = new Array(features.rows);\n var probabilities = this.propagate(features);\n for (var i = 0; i < features.rows; ++i) {\n outputs[i] = this.dicts.outputs[probabilities.maxRowIndex(i)[1]];\n }\n\n return outputs;\n }\n\n /**\n * Export the current model to JSOM.\n * @return {object} model\n */\n toJSON() {\n var model = {\n model: 'FNN',\n hiddenLayers: this.hiddenLayers,\n iterations: this.iterations,\n learningRate: this.learningRate,\n regularization: this.regularization,\n activation: this.activation,\n activationParam: this.activationParam,\n dicts: this.dicts,\n layers: new Array(this.model.length)\n };\n\n for (var i = 0; i < this.model.length; ++i) {\n model.layers[i] = this.model[i].toJSON();\n }\n\n return model;\n }\n\n /**\n * Load a Feedforward Neural Network with the current model.\n * @param {object} model\n * @return {FeedForwardNeuralNetworks}\n */\n static load(model) {\n if (model.model !== 'FNN') {\n throw new RangeError('the current model is not a feed forward network');\n }\n\n return new FeedForwardNeuralNetworks(model);\n }\n}\n\nmodule.exports = FeedForwardNeuralNetworks;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-fnn/src/FeedForwardNeuralNetwork.js\n// module id = 46\n// module chunks = 0","exports.agnes = require('./agnes');\nexports.diana = require('./diana');\n//exports.birch = require('./birch');\n//exports.cure = require('./cure');\n//exports.chameleon = require('./chameleon');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/index.js\n// module id = 47\n// module chunks = 0","'use strict';\n\nconst utils = require('./utils');\nconst init = require('./initialization');\nconst KMeansResult = require('./KMeansResult');\nconst squaredDistance = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n maxIterations: 100,\n tolerance: 1e-6,\n withIterations: false,\n initialization: 'mostDistant',\n distanceFunction: squaredDistance\n};\n\n/**\n * Each step operation for kmeans\n * @ignore\n * @param {Array>} centers - the K centers in format [x,y,z,...]\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 * @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 = utils.updateClusterID(data, centers, clusterID, options.distanceFunction);\n var newCenters = utils.updateCenters(data, clusterID, K);\n var converged = utils.converged(newCenters, centers, options.distanceFunction, options.tolerance);\n return new KMeansResult(clusterID, newCenters, converged, iterations, options.distanceFunction);\n}\n\n/**\n * Generator version for the algorithm\n * @ignore\n * @param {Array>} centers - the K centers in format [x,y,z,...]\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 * @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 {String|Array>} [options.initialization = 'moreDistant'] - K centers in format [x,y,z,...] or a method for initialize the data:\n * * `'random'` will choose K random different values.\n * * `'mostDistant'` will choose the more distant points to a first random pick\n * @returns {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 */\nfunction 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('K should be a positive integer bigger than the number of points');\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 'random':\n centers = init.random(data, K);\n break;\n case 'mostDistant':\n centers = init.mostDistant(data, K, utils.calculateDistanceMatrix(data, options.distanceFunction));\n break;\n default:\n throw new Error('Unknown initialization method: \"' + options.initialization + '\"');\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\nmodule.exports = kmeans;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kmeans/src/kmeans.js\n// module id = 48\n// module chunks = 0","'use strict';\n\nmodule.exports = require('./knn');\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-knn/src/index.js\n// module id = 49\n// module chunks = 0","'use strict';\n\nmodule.exports = exports = require('./naiveBayes').NaiveBayes;\nexports.separateClasses = require('./naiveBayes').separateClasses;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-naivebayes/src/index.js\n// module id = 50\n// module chunks = 0","'use strict';\n\nvar LM = require('ml-curve-fitting');\nvar math = LM.Matrix.algebra;\nvar Matrix = require('ml-matrix');\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 * @param c Constant parameters(Not used)\n * @returns {*}\n */\nfunction sumOfLorentzians(t,p,c){\n var nL = p.length/3,factor,i, j,p2, cols = t.rows;\n var result = Matrix.zeros(t.length,1);\n\n for(i=0;imaxY)\n maxY = y[i];\n }\n }\n else{\n //It is a colum matrix\n if(typeof x[0] === \"object\"){\n for(i=0;imaxY)\n maxY = y[i][0];\n }\n }\n\n }\n\n //}\n }\n else{\n //Looks like a column wise matrix [[x],[y]]\n var nbPoints = nbSeries;\n //if(nbPoints<3)\n // throw new SizeException(nbPoints);\n //else {\n t = new Array(nbPoints);//new Matrix(nbPoints, 1);\n y_data = new Array(nbPoints);//new Matrix(nbPoints, 1);\n for (i = 0; i < nbPoints; i++) {\n t[i] = xy[i][0];\n y_data[i] = xy[i][1];\n if(y_data[i]>maxY)\n maxY = y_data[i];\n }\n //}\n }\n for (i = 0; i < nbPoints; i++) {\n y_data[i]/=maxY;\n }\n if(threshold){\n for (i = nbPoints-1; i >=0; i--) {\n if(y_data[i]0)\n return [(new Matrix([t])).transpose(),(new Matrix([y_data])).transpose(),maxY];\n return null;\n}\n\nfunction sizeException(nbPoints) {\n return new RangeError(\"Not enough points to perform the optimization: \"+nbPoints +\"< 3\");\n}\n\nmodule.exports.optimizeSingleLorentzian = optimizeSingleLorentzian;\nmodule.exports.optimizeLorentzianSum = optimizeLorentzianSum;\nmodule.exports.optimizeSingleGaussian = optimizeSingleGaussian;\nmodule.exports.optimizeGaussianSum = optimizeGaussianSum;\nmodule.exports.singleGaussian = singleGaussian;\nmodule.exports.singleLorentzian = singleLorentzian;\nmodule.exports.optimizeGaussianTrain = optimizeGaussianTrain;\nmodule.exports.optimizeLorentzianTrain = optimizeLorentzianTrain;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-optimize-lorentzian/src/index.js\n// module id = 51\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix');\nconst EVD = Matrix.DC.EVD;\nconst SVD = Matrix.DC.SVD;\nconst Stat = require('ml-stat').matrix;\nconst mean = Stat.mean;\nconst stdev = Stat.standardDeviation;\n\nconst defaultOptions = {\n isCovarianceMatrix: false,\n center: true,\n scale: false\n};\n\n/**\n * Creates new PCA (Principal Component Analysis) from the dataset\n * @param {Matrix} dataset - dataset or covariance matrix\n * @param {Object} options\n * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix\n * @param {boolean} [options.center=true] - should the data be centered (subtract the mean)\n * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation)\n * */\nclass PCA {\n constructor(dataset, options) {\n if (dataset === true) {\n const model = options;\n this.center = model.center;\n this.scale = model.scale;\n this.means = model.means;\n this.stdevs = model.stdevs;\n this.U = Matrix.checkMatrix(model.U);\n this.S = model.S;\n return;\n }\n\n options = Object.assign({}, defaultOptions, options);\n\n this.center = false;\n this.scale = false;\n this.means = null;\n this.stdevs = null;\n\n if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n var useCovarianceMatrix;\n if (typeof options.useCovarianceMatrix === 'boolean') {\n useCovarianceMatrix = options.useCovarianceMatrix;\n } else {\n useCovarianceMatrix = dataset.length > dataset[0].length;\n }\n\n if (useCovarianceMatrix) { // user provided a dataset but wants us to compute and use the covariance matrix\n dataset = this._adjust(dataset, options);\n const covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n } else {\n dataset = this._adjust(dataset, options);\n var svd = new SVD(dataset, {\n computeLeftSingularVectors: false,\n computeRightSingularVectors: true,\n autoTranspose: true\n });\n\n this.U = svd.rightSingularVectors;\n\n const singularValues = svd.diagonal;\n const eigenvalues = new Array(singularValues.length);\n for (var i = 0; i < singularValues.length; i++) {\n eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1);\n }\n this.S = eigenvalues;\n }\n }\n\n /**\n * Load a PCA model from JSON\n * @param {Object} model\n * @return {PCA}\n */\n static load(model) {\n if (model.name !== 'PCA')\n throw new RangeError('Invalid model: ' + model.name);\n return new PCA(true, model);\n }\n\n /**\n * Project the dataset into the PCA space\n * @param {Matrix} dataset\n * @return {Matrix} dataset projected in the PCA space\n */\n predict(dataset) {\n dataset = new Matrix(dataset);\n\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n dataset.divRowVector(this.stdevs);\n }\n }\n\n return dataset.mmul(this.U);\n }\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (var i = 0; i < this.S.length; i++) {\n sum += this.S[i];\n }\n return this.S.map(value => value / sum);\n }\n\n /**\n * Returns the cumulative proportion of variance\n * @return {[number]}\n */\n getCumulativeVariance() {\n var explained = this.getExplainedVariance();\n for (var i = 1; i < explained.length; i++) {\n explained[i] += explained[i - 1];\n }\n return explained;\n }\n\n /**\n * Returns the Eigenvectors of the covariance matrix\n * @returns {Matrix}\n */\n getEigenvectors() {\n return this.U;\n }\n\n /**\n * Returns the Eigenvalues (on the diagonal)\n * @returns {[number]}\n */\n getEigenvalues() {\n return this.S;\n }\n\n /**\n * Returns the standard deviations of the principal components\n * @returns {[number]}\n */\n getStandardDeviations() {\n return this.S.map(x => Math.sqrt(x));\n }\n\n /**\n * Returns the loadings matrix\n * @return {Matrix}\n */\n getLoadings() {\n return this.U.transpose();\n }\n\n /**\n * Export the current model to a JSON object\n * @return {Object} model\n */\n toJSON() {\n return {\n name: 'PCA',\n center: this.center,\n scale: this.scale,\n means: this.means,\n stdevs: this.stdevs,\n U: this.U,\n S: this.S,\n };\n }\n\n _adjust(dataset, options) {\n this.center = !!options.center;\n this.scale = !!options.scale;\n\n dataset = new Matrix(dataset);\n\n if (this.center) {\n const means = mean(dataset);\n const stdevs = this.scale ? stdev(dataset, means, true) : null;\n this.means = means;\n dataset.subRowVector(means);\n if (this.scale) {\n for (var i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i);\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n\n return dataset;\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, {assumeSymmetric: true});\n this.U = evd.eigenvectorMatrix;\n for (var i = 0; i < this.U.length; i++) {\n this.U[i].reverse();\n }\n this.S = evd.realEigenvalues.reverse();\n }\n}\n\nmodule.exports = PCA;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pca/src/pca.js\n// module id = 52\n// module chunks = 0","'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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-performance/src/index.js\n// module id = 53\n// module chunks = 0","module.exports = exports = require('./pls');\nexports.Utils = require('./utils');\nexports.OPLS = require('./opls');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pls/src/index.js\n// module id = 54\n// module chunks = 0","'use strict';\n\nexports.SimpleLinearRegression = exports.SLR = require('./regression/simple-linear-regression');\nexports.NonLinearRegression = exports.NLR = {\n PolynomialRegression: require('./regression/polynomial-regression'),\n PotentialRegression: require('./regression/potential-regression'),\n ExpRegression: require('./regression/exp-regression'),\n PowerRegression: require('./regression/power-regression')\n};\nexports.KernelRidgeRegression = exports.KRR = require('./regression/kernel-ridge-regression');\n//exports.MultipleLinearRegression = exports.MLR = require('./regression/multiple-linear-regression');\n//exports.MultivariateLinearRegression = exports.MVLR = require('./regression/multivariate-linear-regression');\nexports.PolinomialFitting2D = require('./regression/poly-fit-regression2d');\nexports.TheilSenRegression = require('./regression/theil-sen-regression');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/index.js\n// module id = 55\n// module chunks = 0","//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007\nvar extend = require('extend');\nvar stat = require('ml-stat');\n\nvar defaultOptions = {\n windowSize: 9,\n derivative: 0,\n polynomial: 3,\n};\n\n\nfunction SavitzkyGolay(data, h, options) {\n options = extend({}, defaultOptions, options);\n\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)')\n\n\n if (options.windowSize>data.length)\n throw new RangeError('Window size is higher than the data length '+options.windowSize+\">\"+data.length);\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n if (options.polynomial >= 6)\n console.warn('You should not use polynomial grade higher than 5 if you are' +\n ' not sure that your data arises from such a model. Possible polynomial oscillation problems');\n\n var windowSize = options.windowSize;\n\n var half = Math.floor(windowSize/2);\n var np = data.length;\n var ans = new Array(np);\n var weights = fullWeights(windowSize,options.polynomial,options.derivative);\n var hs = 0;\n var constantH = true;\n if( Object.prototype.toString.call( h ) === '[object Array]' ) {\n constantH = false;\n }\n else{\n hs = Math.pow(h, options.derivative);\n }\n //console.log(\"Constant h: \"+constantH);\n //For the borders\n for(var i=0;i=0 && i < h.length-1){\n hs+= (h[i+1]-h[i]);\n count++;\n }\n }\n return Math.pow(hs/count,derivative);\n}\n\nfunction GramPoly(i,m,k,s){\n var Grampoly = 0;\n if(k>0){\n Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) +\n s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s);\n }\n else{\n if(k==0&&s==0){\n Grampoly=1;\n }\n else{\n Grampoly=0;\n }\n }\n //console.log(Grampoly);\n return Grampoly;\n}\n\nfunction GenFact(a,b){\n var gf=1;\n if(a>=b){\n for(var j=a-b+1;j<=a;j++){\n gf*=j;\n }\n }\n return gf;\n}\n\nfunction Weight(i,t,m,n,s){\n var sum=0;\n for(var k=0;k<=n;k++){\n //console.log(k);\n sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s)\n }\n return sum;\n}\n\n/**\n *\n * @param m Number of points\n * @param n Polynomial grade\n * @param s Derivative\n */\nfunction fullWeights(m,n,s){\n var weights = new Array(m);\n var np = Math.floor(m/2);\n for(var t=-np;t<=np;t++){\n weights[t+np] = new Array(m);\n for(var j=-np;j<=np;j++){\n weights[t+np][j+np]=Weight(j,t,np,n,s);\n }\n }\n return weights;\n}\n\n/*function entropy(data,h,options){\n var trend = SavitzkyGolay(data,h,trendOptions);\n var copy = new Array(data.length);\n var sum = 0;\n var max = 0;\n for(var i=0;i} data\n * @param {number} h\n * @param {Object} options\n * @returns {Array}\n */\nfunction SavitzkyGolay (data, h, options) {\n options = extend({}, defaultOptions, options);\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n\n var C, norm;\n var step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, {size: step, value: options.padValue});\n }\n\n var ans = new Array(data.length - 2*step);\n\n if ((options.windowSize === 5) && (options.polynomial === 2) && ((options.derivative === 1) || (options.derivative === 2))) {\n if (options.derivative === 1) {\n C = [-2,-1,0,1,2];\n norm = 10;\n }\n else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n }\n else {\n var J = Matrix.ones(options.windowSize, options.polynomial + 1);\n var inic = -(options.windowSize - 1) / 2;\n for (var i = 0; i < J.length; i++) {\n for (var j = 0; j < J[i].length; j++) {\n if ((inic + 1 !== 0) || (j !== 0))\n J[i][j] = Math.pow((inic + i), j);\n }\n }\n var Jtranspose = J.transposeView();\n var Jinv = (Jtranspose.mmul(J)).inverse();\n C = Jinv.mmul(Jtranspose);\n C = C[options.derivative];\n norm = 1;\n }\n var det = norm * Math.pow(h, options.derivative);\n for (var k = step; k < (data.length - step); k++) {\n var d = 0;\n for (var l = 0; l < C.length; l++)\n d += C[l] * data[l + k - step] / det;\n ans[k - step] = d;\n }\n\n if (options.pad === 'post') {\n ans = padArray(ans, {size: step, value: options.padValue});\n }\n\n return ans;\n}\n\nmodule.exports = SavitzkyGolay;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-savitzky-golay/src/index.js\n// module id = 57\n// module chunks = 0","'use strict';\n\nvar NodeSquare = require('./node-square'),\n NodeHexagonal = require('./node-hexagonal');\n\nvar defaultOptions = {\n fields: 3,\n randomizer: Math.random,\n distance: squareEuclidean,\n iterations: 10,\n learningRate: 0.1,\n gridType: 'rect',\n torus: true,\n method: 'random'\n};\n\nfunction SOM(x, y, options, reload) {\n\n this.x = x;\n this.y = y;\n\n options = options || {};\n this.options = {};\n for (var i in defaultOptions) {\n if (options.hasOwnProperty(i)) {\n this.options[i] = options[i];\n } else {\n this.options[i] = defaultOptions[i];\n }\n }\n\n if (typeof this.options.fields === 'number') {\n this.numWeights = this.options.fields;\n } else if (Array.isArray(this.options.fields)) {\n this.numWeights = this.options.fields.length;\n var converters = getConverters(this.options.fields);\n this.extractor = converters.extractor;\n this.creator = converters.creator;\n } else {\n throw new Error('Invalid fields definition');\n }\n\n if (this.options.gridType === 'rect') {\n this.nodeType = NodeSquare;\n this.gridDim = {\n x: x,\n y: y\n };\n } else {\n this.nodeType = NodeHexagonal;\n var hx = this.x - Math.floor(this.y / 2);\n this.gridDim = {\n x: hx,\n y: this.y,\n z: -(0 - hx - this.y)\n };\n }\n\n this.torus = this.options.torus;\n this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance';\n\n this.distance = this.options.distance;\n\n this.maxDistance = getMaxDistance(this.distance, this.numWeights);\n\n if (reload === true) { // For model loading\n this.done = true;\n return;\n }\n if (!(x > 0 && y > 0)) {\n throw new Error('x and y must be positive');\n }\n\n this.times = {\n findBMU: 0,\n adjust: 0\n };\n\n this.randomizer = this.options.randomizer;\n\n this.iterationCount = 0;\n this.iterations = this.options.iterations;\n\n this.startLearningRate = this.learningRate = this.options.learningRate;\n\n this.mapRadius = Math.floor(Math.max(x, y) / 2);\n\n this.algorithmMethod = this.options.method;\n\n this._initNodes();\n\n this.done = false;\n}\n\nSOM.load = function loadModel(model, distance) {\n if (model.name === 'SOM') {\n var x = model.data.length,\n y = model.data[0].length;\n if (distance) {\n model.options.distance = distance;\n } else if (model.options.distance) {\n model.options.distance = eval('(' + model.options.distance + ')');\n }\n var som = new SOM(x, y, model.options, true);\n som.nodes = new Array(x);\n for (var i = 0; i < x; i++) {\n som.nodes[i] = new Array(y);\n for (var j = 0; j < y; j++) {\n som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som);\n }\n }\n return som;\n } else {\n throw new Error('expecting a SOM model');\n }\n};\n\nSOM.prototype.export = function exportModel(includeDistance) {\n if (!this.done) {\n throw new Error('model is not ready yet');\n }\n var model = {\n name: 'SOM'\n };\n model.options = {\n fields: this.options.fields,\n gridType: this.options.gridType,\n torus: this.options.torus\n };\n model.data = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n model.data[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n model.data[i][j] = this.nodes[i][j].weights;\n }\n }\n if (includeDistance) {\n model.options.distance = this.distance.toString();\n }\n return model;\n};\n\nSOM.prototype._initNodes = function initNodes() {\n var now = Date.now(),\n i, j, k;\n this.nodes = new Array(this.x);\n for (i = 0; i < this.x; i++) {\n this.nodes[i] = new Array(this.y);\n for (j = 0; j < this.y; j++) {\n var weights = new Array(this.numWeights);\n for (k = 0; k < this.numWeights; k++) {\n weights[k] = this.randomizer();\n }\n this.nodes[i][j] = new this.nodeType(i, j, weights, this);\n }\n }\n this.times.initNodes = Date.now() - now;\n};\n\nSOM.prototype.setTraining = function setTraining(trainingSet) {\n if (this.trainingSet) {\n throw new Error('training set has already been set');\n }\n var now = Date.now();\n var convertedSet = trainingSet;\n var i, l = trainingSet.length;\n if (this.extractor) {\n convertedSet = new Array(l);\n for (i = 0; i < l; i++) {\n convertedSet[i] = this.extractor(trainingSet[i]);\n }\n }\n this.numIterations = this.iterations * l;\n\n if (this.algorithmMethod === 'random') {\n this.timeConstant = this.numIterations / Math.log(this.mapRadius);\n } else {\n this.timeConstant = l / Math.log(this.mapRadius);\n }\n this.trainingSet = convertedSet;\n this.times.setTraining = Date.now() - now;\n};\n\nSOM.prototype.trainOne = function trainOne() {\n if (this.done) {\n\n return false;\n\n } else if (this.numIterations-- > 0) {\n\n var neighbourhoodRadius,\n trainingValue,\n trainingSetFactor;\n\n if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step\n neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant);\n trainingValue = getRandomValue(this.trainingSet, this.randomizer);\n this._adjust(trainingValue, neighbourhoodRadius);\n this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations);\n } else { // Get next input vector\n trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length);\n neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant);\n trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length];\n this._adjust(trainingValue, neighbourhoodRadius);\n if (((this.iterationCount + 1) % this.trainingSet.length) === 0) {\n this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length));\n }\n }\n\n this.iterationCount++;\n\n return true;\n\n } else {\n\n this.done = true;\n return false;\n\n }\n};\n\nSOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) {\n var now = Date.now(),\n x, y, dist, influence;\n\n var bmu = this._findBestMatchingUnit(trainingValue);\n\n var now2 = Date.now();\n this.times.findBMU += now2 - now;\n\n var radiusLimit = Math.floor(neighbourhoodRadius);\n var xMin = bmu.x - radiusLimit,\n xMax = bmu.x + radiusLimit,\n yMin = bmu.y - radiusLimit,\n yMax = bmu.y + radiusLimit;\n\n for (x = xMin; x <= xMax; x++) {\n var theX = x;\n if (x < 0) {\n theX += this.x;\n } else if (x >= this.x) {\n theX -= this.x;\n }\n for (y = yMin; y <= yMax; y++) {\n var theY = y;\n if (y < 0) {\n theY += this.y;\n } else if (y >= this.y) {\n theY -= this.y;\n }\n\n dist = bmu[this.distanceMethod](this.nodes[theX][theY]);\n\n if (dist < neighbourhoodRadius) {\n influence = Math.exp(-dist / (2 * neighbourhoodRadius));\n this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence);\n }\n\n }\n }\n\n this.times.adjust += (Date.now() - now2);\n\n};\n\nSOM.prototype.train = function train(trainingSet) {\n if (!this.done) {\n this.setTraining(trainingSet);\n while (this.trainOne()) {\n }\n }\n};\n\nSOM.prototype.getConvertedNodes = function getConvertedNodes() {\n var result = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n result[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n var node = this.nodes[i][j];\n result[i][j] = this.creator ? this.creator(node.weights) : node.weights;\n }\n }\n return result;\n};\n\nSOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) {\n\n var bmu,\n lowest = Infinity,\n dist;\n\n for (var i = 0; i < this.x; i++) {\n for (var j = 0; j < this.y; j++) {\n dist = this.distance(this.nodes[i][j].weights, candidate);\n if (dist < lowest) {\n lowest = dist;\n bmu = this.nodes[i][j];\n }\n }\n }\n\n return bmu;\n\n};\n\nSOM.prototype.predict = function predict(data, computePosition) {\n if (typeof data === 'boolean') {\n computePosition = data;\n data = null;\n }\n if (!data) {\n data = this.trainingSet;\n }\n if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset\n var self = this;\n return data.map(function (element) {\n return self._predict(element, computePosition);\n });\n } else { // predict a single element\n return this._predict(data, computePosition);\n }\n};\n\nSOM.prototype._predict = function _predict(element, computePosition) {\n if (!Array.isArray(element)) {\n element = this.extractor(element);\n }\n var bmu = this._findBestMatchingUnit(element);\n var result = [bmu.x, bmu.y];\n if (computePosition) {\n result[2] = bmu.getPosition(element);\n }\n return result;\n};\n\n// As seen in http://www.scholarpedia.org/article/Kohonen_network\nSOM.prototype.getQuantizationError = function getQuantizationError() {\n var fit = this.getFit(),\n l = fit.length,\n sum = 0;\n for (var i = 0; i < l; i++) {\n sum += fit[i];\n }\n return sum / l;\n};\n\nSOM.prototype.getFit = function getFit(dataset) {\n if (!dataset) {\n dataset = this.trainingSet;\n }\n var l = dataset.length,\n bmu,\n result = new Array(l);\n for (var i = 0; i < l; i++) {\n bmu = this._findBestMatchingUnit(dataset[i]);\n result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights));\n }\n return result;\n};\n\nfunction getConverters(fields) {\n var l = fields.length,\n normalizers = new Array(l),\n denormalizers = new Array(l);\n for (var i = 0; i < l; i++) {\n normalizers[i] = getNormalizer(fields[i].range);\n denormalizers[i] = getDenormalizer(fields[i].range);\n }\n return {\n extractor: function extractor(value) {\n var result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = normalizers[i](value[fields[i].name]);\n }\n return result;\n },\n creator: function creator(value) {\n var result = {};\n for (var i = 0; i < l; i++) {\n result[fields[i].name] = denormalizers[i](value[i]);\n }\n return result;\n }\n };\n}\n\nfunction getNormalizer(minMax) {\n return function normalizer(value) {\n return (value - minMax[0]) / (minMax[1] - minMax[0]);\n };\n}\n\nfunction getDenormalizer(minMax) {\n return function denormalizer(value) {\n return (minMax[0] + value * (minMax[1] - minMax[0]));\n };\n}\n\nfunction squareEuclidean(a, b) {\n var d = 0;\n for (var i = 0, ii = a.length; i < ii; i++) {\n d += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return d;\n}\n\nfunction getRandomValue(arr, randomizer) {\n return arr[Math.floor(randomizer() * arr.length)];\n}\n\nfunction getMaxDistance(distance, numWeights) {\n var zero = new Array(numWeights),\n one = new Array(numWeights);\n for (var i = 0; i < numWeights; i++) {\n zero[i] = 0;\n one[i] = 1;\n }\n return distance(zero, one);\n}\n\nmodule.exports = SOM;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-som/src/index.js\n// module id = 58\n// module chunks = 0","const HashTable = require('ml-hash-table');\n\nclass SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) { // clone\n const other = rows;\n this._init(other.rows, other.columns, other.elements.clone(), other.threshold);\n return;\n }\n\n if (Array.isArray(rows)) {\n const matrix = rows;\n rows = matrix.length;\n options = columns || {};\n columns = matrix[0].length;\n this._init(rows, columns, new HashTable(options), options.threshold);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = matrix[i][j];\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value !== 0) {\n this.elements.set(i * columns + j, matrix[i][j]);\n }\n }\n }\n } else {\n this._init(rows, columns, new HashTable(options), options.threshold);\n }\n }\n\n _init(rows, columns, elements, threshold) {\n this.rows = rows;\n this.columns = columns;\n this.elements = elements;\n this.threshold = threshold || 0;\n }\n \n static eye(rows = 1, columns = rows) {\n const min = Math.min(rows, columns);\n const matrix = new SparseMatrix(rows, columns, {initialCapacity: min});\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, 1);\n }\n return matrix;\n }\n\n clone() {\n return new SparseMatrix(this);\n }\n \n to2DArray() {\n const copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (!this.isSquare()) return false;\n\n var symmetric = true;\n this.forEachNonZero((i, j, v) => {\n if (this.get(j, i) !== v) {\n symmetric = false;\n return false;\n }\n return v;\n });\n return symmetric;\n }\n\n 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 console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\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\nSparseMatrix.prototype.klass = 'Matrix';\n\nSparseMatrix.identity = SparseMatrix.eye;\nSparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct;\n\nmodule.exports = SparseMatrix;\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\nvar 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 (var operator of operators) {\n for (var i = 1; i < operator.length; i++) {\n SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]}));\n\n SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]}));\n }\n}\n\nvar methods = [\n ['~', 'not']\n];\n\n[\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n});\n\nfor (var method of methods) {\n for (var i = 1; i < method.length; i++) {\n SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, {name: method[i], method: method[0]}));\n SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, {name: method[i]}));\n }\n}\n\nfunction fillTemplateFunction(template, values) {\n for (var i in values) {\n template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]);\n }\n return template;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-sparse-matrix/src/SparseMatrix.js\n// module id = 59\n// module chunks = 0","'use strict';\nconst Kernel = require('ml-kernel');\nconst stat = require('ml-stat').array;\n\nvar defaultOptions = {\n C: 1,\n tol: 1e-4,\n maxPasses: 10,\n maxIterations: 10000,\n kernel: 'linear',\n alphaTol: 1e-6,\n random: Math.random,\n whitening: true\n};\n\n/**\n * Simplified version of the Sequential Minimal Optimization algorithm for training\n * support vector machines\n * @param {{Object}} options - SVM options\n * @param {Number} [options.C=1] - regularization parameter\n * @param {Number} [options.tol=1e-4] - numerical tolerance\n * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors\n * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing\n * @param {Number} [options.maxIterations=10000] - max number of iterations\n * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels}\n * @param {Function} [options.random=Math.random] - custom random number generator\n * @constructor\n */\nfunction SVM(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions);\n this.b = 0;\n}\n\n/**\n * Train the SVM model\n * @param {Array >} features - training data features\n * @param {Array } labels - training data labels in the domain {1,-1}\n */\nSVM.prototype.train = function (features, labels) {\n if (features.length !== labels.length) {\n throw new Error('Features and labels should have the same length');\n }\n if (features.length < 2) {\n throw new Error('Cannot train with less than 2 observations');\n }\n this._trained = false;\n this._loaded = false;\n this.N = labels.length;\n this.D = features[0].length;\n if (this.options.whitening) {\n this.X = new Array(this.N);\n for (var i = 0; i < this.N; i++) {\n this.X[i] = new Array(this.D);\n }\n this.minMax = new Array(this.D);\n // Apply normalization and keep normalization parameters\n for (var j = 0; j < this.D; j++) {\n var d = new Array(this.N);\n for (i = 0; i < this.N; i++) {\n d[i] = features[i][j];\n }\n this.minMax[j] = stat.minMax(d);\n for (i = 0; i < this.N; i++) {\n this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n }\n } else {\n this.X = features;\n }\n this.Y = labels;\n this.b = 0;\n this.W = undefined;\n\n var kernel = this.kernel.compute(this.X);\n var m = labels.length;\n var alpha = new Array(m).fill(0);\n this.alphas = alpha;\n for (var a = 0; a < m; a++)\n alpha[a] = 0;\n\n var b1 = 0,\n b2 = 0,\n iter = 0,\n passes = 0,\n Ei = 0,\n Ej = 0,\n ai = 0,\n aj = 0,\n L = 0,\n H = 0,\n eta = 0;\n\n while (passes < this.options.maxPasses && iter < this.options.maxIterations) {\n var numChange = 0;\n for (i = 0; i < m; i++) {\n Ei = this._marginOnePrecomputed(i, kernel) - labels[i];\n if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) {\n j = i;\n while (j === i) j = Math.floor(this.options.random() * m);\n Ej = this._marginOnePrecomputed(j, kernel) - labels[j];\n ai = alpha[i];\n aj = alpha[j];\n if (labels[i] === labels[j]) {\n L = Math.max(0, ai + aj - this.options.C);\n H = Math.min(this.options.C, ai + aj);\n } else {\n L = Math.max(0, aj - ai);\n H = Math.min(this.options.C, this.options.C + aj + ai);\n }\n if (Math.abs(L - H) < 1e-4) continue;\n\n eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j];\n if (eta >= 0) continue;\n var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta;\n if (newaj > H)\n newaj = H;\n else if (newaj < L)\n newaj = L;\n if (Math.abs(aj - newaj) < 10e-4) continue;\n alpha[j] = newaj;\n alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj);\n b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j];\n b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j];\n this.b = (b1 + b2) / 2;\n if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1;\n if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2;\n numChange += 1;\n }\n }\n iter++;\n if (numChange === 0)\n passes += 1;\n else\n passes = 0;\n }\n if (iter === this.options.maxIterations) {\n throw new Error('max iterations reached');\n }\n\n this.iterations = iter;\n\n // Compute the weights (useful for fast decision on new test instances when linear SVM)\n if (this.options.kernel === 'linear') {\n this.W = new Array(this.D);\n for (var r = 0; r < this.D; r++) {\n this.W[r] = 0;\n for (var w = 0; w < m; w++)\n this.W[r] += labels[w] * alpha[w] * this.X[w][r];\n }\n }\n\n // Keep only support vectors\n // It will compute decision on new test instances faster\n // We also keep the index of the support vectors\n // in the original data\n var nX = [];\n var nY = [];\n var nAlphas = [];\n this._supportVectorIdx = [];\n for (i = 0; i < this.N; i++) {\n if (this.alphas[i] > this.options.alphaTol) {\n nX.push(this.X[i]);\n nY.push(labels[i]);\n nAlphas.push(this.alphas[i]);\n this._supportVectorIdx.push(i);\n\n }\n }\n this.X = nX;\n this.Y = nY;\n this.N = nX.length;\n this.alphas = nAlphas;\n\n\n // A flag to say this SVM has been trained\n this._trained = true;\n};\n\n/**\n * Get prediction ({-1,1}) given one observation's features.\n * @private\n * @param p The observation's features.\n * @returns {number} Classification result ({-1,1})\n */\nSVM.prototype.predictOne = function (p) {\n var margin = this.marginOne(p);\n return margin > 0 ? 1 : -1;\n};\n\n/**\n * Predict the classification outcome of a trained svm given one or several observations' features.\n * @param {Array} features - The observation(s)' features\n * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation\n * is given\n */\nSVM.prototype.predict = function (features) {\n if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first');\n if (Array.isArray(features) && Array.isArray(features[0])) {\n return features.map(this.predictOne.bind(this));\n } else {\n return this.predictOne(features);\n }\n};\n\n/**\n * Get margin given one observation's features\n * @private\n * @param {Array} features - Features\n * @returns {Number} - The computed margin\n */\nSVM.prototype.marginOne = function (features, noWhitening) {\n // Apply normalization\n if (this.options.whitening && !noWhitening) {\n features = this._applyWhitening(features);\n }\n var ans = this.b, i;\n if (this.options.kernel === 'linear' && this.W) {\n // Use weights, it's faster\n for (i = 0; i < this.W.length; i++) {\n ans += this.W[i] * features[i];\n }\n } else {\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0];\n }\n }\n return ans;\n};\n\n\n/**\n * Get a margin using the precomputed kernel. Much faster than normal margin computation\n * @private\n * @param {Number} index - Train data index\n * @param {Array< Array >} kernel - The precomputed kernel\n * @returns {number} Computed margin\n * @private\n */\nSVM.prototype._marginOnePrecomputed = function (index, kernel) {\n var ans = this.b, i;\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * kernel[index][i];\n }\n return ans;\n};\n\n\n/**\n * Returns the margin of one or several observations given its features\n * @param {Array >|Array} features - Features from on or several observations.\n * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if\n * only one observation's features given\n */\nSVM.prototype.margin = function (features) {\n if (Array.isArray(features)) {\n return features.map(this.marginOne.bind(this));\n } else {\n return this.marginOne(features);\n }\n};\n\n/**\n * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances\n * created from {@link #SVM.load load} if linear kernel\n * @returns {Array} The indices in the training vector of the support vectors\n */\nSVM.prototype.supportVectors = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first');\n if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them');\n return this._supportVectorIdx;\n};\n\n/**\n * Create a SVM instance from a saved model\n * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON}\n * @returns {SVM} Instance of svm classifier\n */\nSVM.load = function (model) {\n this._loaded = true;\n this._trained = false;\n var svm = new SVM(model.options);\n if (model.options.kernel === 'linear') {\n svm.W = model.W.slice();\n svm.D = svm.W.length;\n } else {\n svm.X = model.X.slice();\n svm.Y = model.Y.slice();\n svm.alphas = model.alphas.slice();\n svm.N = svm.X.length;\n svm.D = svm.X[0].length;\n }\n svm.minMax = model.minMax;\n svm.b = model.b;\n svm._loaded = true;\n svm._trained = false;\n return svm;\n};\n\n/**\n * Export the minimal object that enables to reload the model\n * @returns {Object} Model object that can be reused with {@link #SVM.load load}\n */\nSVM.prototype.toJSON = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first');\n var model = {};\n model.options = Object.assign({}, this.options);\n model.b = this.b;\n model.minMax = this.minMax;\n if (model.options.kernel === 'linear') {\n model.W = this.W.slice();\n } else {\n // Exporting non-linear models is heavier\n model.X = this.X.slice();\n model.Y = this.Y.slice();\n model.alphas = this.alphas.slice();\n }\n return model;\n};\n\nSVM.prototype._applyWhitening = function (features) {\n if (!this.minMax) throw new Error('Could not apply whitening');\n var whitened = new Array(features.length);\n for (var j = 0; j < features.length; j++) {\n whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n return whitened;\n};\n\nmodule.exports = SVM;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-svm/src/svm.js\n// module id = 60\n// module chunks = 0","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar LOOP = 8;\nvar FLOAT_MUL = 1 / 16777216;\n\nfunction multiply_uint32(n, m) {\n n >>>= 0;\n m >>>= 0;\n var nlo = n & 0xffff;\n var nhi = n - nlo;\n return (nhi * m >>> 0) + nlo * m >>> 0;\n}\n\nvar XSadd = (function () {\n function XSadd() {\n var seed = arguments.length <= 0 || arguments[0] === undefined ? Date.now() : arguments[0];\n\n _classCallCheck(this, XSadd);\n\n this.state = new Uint32Array(4);\n this.init(seed);\n }\n\n _createClass(XSadd, [{\n key: \"init\",\n value: function init(seed) {\n this.state[0] = seed;\n this.state[1] = 0;\n this.state[2] = 0;\n this.state[3] = 0;\n for (var i = 1; i < LOOP; i++) {\n this.state[i & 3] ^= i + multiply_uint32(1812433253, this.state[i - 1 & 3] ^ this.state[i - 1 & 3] >>> 30 >>> 0) >>> 0;\n }\n period_certification(this);\n for (var i = 0; i < LOOP; i++) {\n next_state(this);\n }\n }\n\n /**\n * Returns a 32-bit integer r (0 <= r < 2^32)\n */\n }, {\n key: \"getUint32\",\n value: function getUint32() {\n next_state(this);\n return this.state[3] + this.state[2] >>> 0;\n }\n\n /**\n * Returns a floating point number r (0.0 <= r < 1.0)\n */\n }, {\n key: \"getFloat\",\n value: function getFloat() {\n return (this.getUint32() >>> 8) * FLOAT_MUL;\n }\n }, {\n key: \"random\",\n get: function get() {\n if (!this._random) {\n this._random = this.getFloat.bind(this);\n }\n return this._random;\n }\n }]);\n\n return XSadd;\n})();\n\nexports[\"default\"] = XSadd;\n\nfunction period_certification(xsadd) {\n if (xsadd.state[0] === 0 && xsadd.state[1] === 0 && xsadd.state[2] === 0 && xsadd.state[3] === 0) {\n xsadd.state[0] = 88; // X\n xsadd.state[1] = 83; // S\n xsadd.state[2] = 65; // A\n xsadd.state[3] = 68; // D\n }\n}\n\nvar sh1 = 15;\nvar sh2 = 18;\nvar sh3 = 11;\nfunction next_state(xsadd) {\n var t = xsadd.state[0];\n t ^= t << sh1;\n t ^= t >>> sh2;\n t ^= xsadd.state[3] << sh3;\n xsadd.state[0] = xsadd.state[1];\n xsadd.state[1] = xsadd.state[2];\n xsadd.state[2] = xsadd.state[3];\n xsadd.state[3] = t;\n}\nmodule.exports = exports[\"default\"];\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-xsadd/xsadd-es5.js\n// module id = 61\n// module chunks = 0","(function(undefined) {\r\n 'use strict';\r\n\r\n // Node.js usage:\r\n //\r\n // var Picker = require('RandomSelection').Picker;\r\n // var greetingPicker = new Picker(['hello', 'hi', 'howdy']);\r\n // var greeting = greetingPicker.pick();\r\n\r\n // Our namespace. Exported members will be attached to this.\r\n var ns;\r\n\r\n // Set our namespace based on whether we are running in Node.js or the browser.\r\n if (typeof module !== 'undefined' && module.exports) {\r\n // We are running in Node.\r\n ns = module.exports;\r\n }\r\n else {\r\n // We are running in the browser.\r\n // `this` is the `window`.\r\n // Use window.RandomSelection as our namespace.\r\n ns = this.RandomSelection = {};\r\n }\r\n\r\n // Gets a shallow copy of the given array.\r\n function clone(arr) {\r\n \tvar newArr = [];\r\n \tfor (var i=0; i y) {\n return 1;\n }\n return 0;\n };\n\n\n /*\n Insert item x in list a, and keep it sorted assuming a is sorted.\n \n If x is already in a, insert it to the right of the rightmost x.\n \n Optional args lo (default 0) and hi (default a.length) bound the slice\n of a to be searched.\n */\n\n insort = function(a, x, lo, hi, cmp) {\n var mid;\n if (lo == null) {\n lo = 0;\n }\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (lo < 0) {\n throw new Error('lo must be non-negative');\n }\n if (hi == null) {\n hi = a.length;\n }\n while (lo < hi) {\n mid = floor((lo + hi) / 2);\n if (cmp(x, a[mid]) < 0) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n };\n\n\n /*\n Push item onto heap, maintaining the heap invariant.\n */\n\n heappush = function(array, item, cmp) {\n if (cmp == null) {\n cmp = defaultCmp;\n }\n array.push(item);\n return _siftdown(array, 0, array.length - 1, cmp);\n };\n\n\n /*\n Pop the smallest item off the heap, maintaining the heap invariant.\n */\n\n heappop = function(array, cmp) {\n var lastelt, returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n lastelt = array.pop();\n if (array.length) {\n returnitem = array[0];\n array[0] = lastelt;\n _siftup(array, 0, cmp);\n } else {\n returnitem = lastelt;\n }\n return returnitem;\n };\n\n\n /*\n Pop and return the current smallest value, and add the new item.\n \n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed size heap. Note that the value\n returned may be larger than item! That constrains reasonable use of\n this routine unless written as part of a conditional replacement:\n if item > array[0]\n item = heapreplace(array, item)\n */\n\n heapreplace = function(array, item, cmp) {\n var returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n returnitem = array[0];\n array[0] = item;\n _siftup(array, 0, cmp);\n return returnitem;\n };\n\n\n /*\n Fast version of a heappush followed by a heappop.\n */\n\n heappushpop = function(array, item, cmp) {\n var _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (array.length && cmp(array[0], item) < 0) {\n _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n _siftup(array, 0, cmp);\n }\n return item;\n };\n\n\n /*\n Transform list into a heap, in-place, in O(array.length) time.\n */\n\n heapify = function(array, cmp) {\n var i, _i, _j, _len, _ref, _ref1, _results, _results1;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n _ref1 = (function() {\n _results1 = [];\n for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n return _results1;\n }).apply(this).reverse();\n _results = [];\n for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n i = _ref1[_i];\n _results.push(_siftup(array, i, cmp));\n }\n return _results;\n };\n\n\n /*\n Update the position of the given item in the heap.\n This function should be called every time the item is being modified.\n */\n\n updateItem = function(array, item, cmp) {\n var pos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n pos = array.indexOf(item);\n if (pos === -1) {\n return;\n }\n _siftdown(array, 0, pos, cmp);\n return _siftup(array, pos, cmp);\n };\n\n\n /*\n Find the n largest elements in a dataset.\n */\n\n nlargest = function(array, n, cmp) {\n var elem, result, _i, _len, _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n result = array.slice(0, n);\n if (!result.length) {\n return result;\n }\n heapify(result, cmp);\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n heappushpop(result, elem, cmp);\n }\n return result.sort(cmp).reverse();\n };\n\n\n /*\n Find the n smallest elements in a dataset.\n */\n\n nsmallest = function(array, n, cmp) {\n var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (n * 10 <= array.length) {\n result = array.slice(0, n).sort(cmp);\n if (!result.length) {\n return result;\n }\n los = result[result.length - 1];\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n if (cmp(elem, los) < 0) {\n insort(result, elem, 0, null, cmp);\n result.pop();\n los = result[result.length - 1];\n }\n }\n return result;\n }\n heapify(array, cmp);\n _results = [];\n for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {\n _results.push(heappop(array, cmp));\n }\n return _results;\n };\n\n _siftdown = function(array, startpos, pos, cmp) {\n var newitem, parent, parentpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n newitem = array[pos];\n while (pos > startpos) {\n parentpos = (pos - 1) >> 1;\n parent = array[parentpos];\n if (cmp(newitem, parent) < 0) {\n array[pos] = parent;\n pos = parentpos;\n continue;\n }\n break;\n }\n return array[pos] = newitem;\n };\n\n _siftup = function(array, pos, cmp) {\n var childpos, endpos, newitem, rightpos, startpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n endpos = array.length;\n startpos = pos;\n newitem = array[pos];\n childpos = 2 * pos + 1;\n while (childpos < endpos) {\n rightpos = childpos + 1;\n if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n childpos = rightpos;\n }\n array[pos] = array[childpos];\n pos = childpos;\n childpos = 2 * pos + 1;\n }\n array[pos] = newitem;\n return _siftdown(array, startpos, pos, cmp);\n };\n\n Heap = (function() {\n Heap.push = heappush;\n\n Heap.pop = heappop;\n\n Heap.replace = heapreplace;\n\n Heap.pushpop = heappushpop;\n\n Heap.heapify = heapify;\n\n Heap.updateItem = updateItem;\n\n Heap.nlargest = nlargest;\n\n Heap.nsmallest = nsmallest;\n\n function Heap(cmp) {\n this.cmp = cmp != null ? cmp : defaultCmp;\n this.nodes = [];\n }\n\n Heap.prototype.push = function(x) {\n return heappush(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pop = function() {\n return heappop(this.nodes, this.cmp);\n };\n\n Heap.prototype.peek = function() {\n return this.nodes[0];\n };\n\n Heap.prototype.contains = function(x) {\n return this.nodes.indexOf(x) !== -1;\n };\n\n Heap.prototype.replace = function(x) {\n return heapreplace(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pushpop = function(x) {\n return heappushpop(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.heapify = function() {\n return heapify(this.nodes, this.cmp);\n };\n\n Heap.prototype.updateItem = function(x) {\n return updateItem(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.clear = function() {\n return this.nodes = [];\n };\n\n Heap.prototype.empty = function() {\n return this.nodes.length === 0;\n };\n\n Heap.prototype.size = function() {\n return this.nodes.length;\n };\n\n Heap.prototype.clone = function() {\n var heap;\n heap = new Heap();\n heap.nodes = this.nodes.slice(0);\n return heap;\n };\n\n Heap.prototype.toArray = function() {\n return this.nodes.slice(0);\n };\n\n Heap.prototype.insert = Heap.prototype.push;\n\n Heap.prototype.top = Heap.prototype.peek;\n\n Heap.prototype.front = Heap.prototype.peek;\n\n Heap.prototype.has = Heap.prototype.contains;\n\n Heap.prototype.copy = Heap.prototype.clone;\n\n return Heap;\n\n })();\n\n (function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n return define([], factory);\n } else if (typeof exports === 'object') {\n return module.exports = factory();\n } else {\n return root.Heap = factory();\n }\n })(this, function() {\n return Heap;\n });\n\n}).call(this);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/heap/lib/heap.js\n// module id = 64\n// module chunks = 0","'use strict';\n\nconst Stat = require('ml-stat').array;\n/**\n * Function that returns an array of points given 1D array as follows:\n *\n * [x1, y1, .. , x2, y2, ..]\n *\n * And receive the number of dimensions of each point.\n * @param array\n * @param dimensions\n * @returns {Array} - Array of points.\n */\nfunction coordArrayToPoints(array, dimensions) {\n if(array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var length = array.length / dimensions;\n var pointsArr = new Array(length);\n\n var k = 0;\n for(var i = 0; i < array.length; i += dimensions) {\n var point = new Array(dimensions);\n for(var j = 0; j < dimensions; ++j) {\n point[j] = array[i + j];\n }\n\n pointsArr[k] = point;\n k++;\n }\n\n return pointsArr;\n}\n\n\n/**\n * Function that given an array as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * Returns an array as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * And receives the number of dimensions of each coordinate.\n * @param array\n * @param dimensions\n * @returns {Array} - Matrix of coordinates\n */\nfunction coordArrayToCoordMatrix(array, dimensions) {\n if(array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var coordinatesArray = new Array(dimensions);\n var points = array.length / dimensions;\n for (var i = 0; i < coordinatesArray.length; i++) {\n coordinatesArray[i] = new Array(points);\n }\n\n for(i = 0; i < array.length; i += dimensions) {\n for(var j = 0; j < dimensions; ++j) {\n var currentPoint = Math.floor(i / dimensions);\n coordinatesArray[j][currentPoint] = array[i + j];\n }\n }\n\n return coordinatesArray;\n}\n\n/**\n * Function that receives a coordinate matrix as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * Returns an array of coordinates as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param coordMatrix\n * @returns {Array}\n */\nfunction coordMatrixToCoordArray(coordMatrix) {\n var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length);\n var k = 0;\n for(var i = 0; i < coordMatrix[0].length; ++i) {\n for(var j = 0; j < coordMatrix.length; ++j) {\n coodinatesArray[k] = coordMatrix[j][i];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Tranpose a matrix, this method is for coordMatrixToPoints and\n * pointsToCoordMatrix, that because only transposing the matrix\n * you can change your representation.\n *\n * @param matrix\n * @returns {Array}\n */\nfunction transpose(matrix) {\n var resultMatrix = new Array(matrix[0].length);\n for(var i = 0; i < resultMatrix.length; ++i) {\n resultMatrix[i] = new Array(matrix.length);\n }\n\n for (i = 0; i < matrix.length; ++i) {\n for(var j = 0; j < matrix[0].length; ++j) {\n resultMatrix[j][i] = matrix[i][j];\n }\n }\n\n return resultMatrix;\n}\n\n/**\n * Function that transform an array of points into a coordinates array\n * as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param points\n * @returns {Array}\n */\nfunction pointsToCoordArray(points) {\n var coodinatesArray = new Array(points.length * points[0].length);\n var k = 0;\n for(var i = 0; i < points.length; ++i) {\n for(var j = 0; j < points[0].length; ++j) {\n coodinatesArray[k] = points[i][j];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Apply the dot product between the smaller vector and a subsets of the\n * largest one.\n *\n * @param firstVector\n * @param secondVector\n * @returns {Array} each dot product of size of the difference between the\n * larger and the smallest one.\n */\nfunction applyDotProduct(firstVector, secondVector) {\n var largestVector, smallestVector;\n if(firstVector.length <= secondVector.length) {\n smallestVector = firstVector;\n largestVector = secondVector;\n } else {\n smallestVector = secondVector;\n largestVector = firstVector;\n }\n\n var difference = largestVector.length - smallestVector.length + 1;\n var dotProductApplied = new Array(difference);\n\n for (var i = 0; i < difference; ++i) {\n var sum = 0;\n for (var j = 0; j < smallestVector.length; ++j) {\n sum += smallestVector[j] * largestVector[i + j];\n }\n dotProductApplied[i] = sum;\n }\n\n return dotProductApplied;\n}\n/**\n * To scale the input array between the specified min and max values. The operation is performed inplace\n * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling\n * will multiply the input array by min/min(input) or max/max(input)\n * @param input\n * @param options\n * @returns {*}\n */\nfunction scale(input, options){\n var y;\n if(options.inPlace){\n y = input;\n }\n else{\n y = new Array(input.length);\n }\n const max = options.max;\n const min = options.min;\n if(typeof max === \"number\"){\n if(typeof min === \"number\"){\n var minMax = Stat.minMax(input);\n var factor = (max - min)/(minMax.max-minMax.min);\n for(var i=0;i< y.length;i++){\n y[i]=(input[i]-minMax.min)*factor+min;\n }\n }\n else{\n var currentMin = Stat.max(input);\n var factor = max/currentMin;\n for(var i=0;i< y.length;i++){\n y[i] = input[i]*factor;\n }\n }\n }\n else{\n if(typeof min === \"number\"){\n var currentMin = Stat.min(input);\n var factor = min/currentMin;\n for(var i=0;i< y.length;i++){\n y[i] = input[i]*factor;\n }\n }\n }\n return y;\n}\n\nmodule.exports = {\n coordArrayToPoints: coordArrayToPoints,\n coordArrayToCoordMatrix: coordArrayToCoordMatrix,\n coordMatrixToCoordArray: coordMatrixToCoordArray,\n coordMatrixToPoints: transpose,\n pointsToCoordArray: pointsToCoordArray,\n pointsToCoordMatrix: transpose,\n applyDotProduct: applyDotProduct,\n scale:scale\n};\n\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-array-utils/src/ArrayUtils.js\n// module id = 65\n// module chunks = 0","'use strict';\n\n/**\n *\n * Function that returns a Number array of equally spaced numberOfPoints\n * containing a representation of intensities of the spectra arguments x\n * and y.\n *\n * The options parameter contains an object in the following form:\n * from: starting point\n * to: last point\n * numberOfPoints: number of points between from and to\n * variant: \"slot\" or \"smooth\" - smooth is the default option\n *\n * The slot variant consist that each point in the new array is calculated\n * averaging the existing points between the slot that belongs to the current\n * value. The smooth variant is the same but takes the integral of the range\n * of the slot and divide by the step size between two points in the new array.\n *\n * @param x - sorted increasing x values\n * @param y\n * @param options\n * @returns {Array} new array with the equally spaced data.\n *\n */\nfunction getEquallySpacedData(x, y, options) {\n if (x.length>1 && x[0]>x[1]) {\n x=x.slice().reverse();\n y=y.slice().reverse();\n }\n\n var xLength = x.length;\n if(xLength !== y.length)\n throw new RangeError(\"the x and y vector doesn't have the same size.\");\n\n if (options === undefined) options = {};\n\n var from = options.from === undefined ? x[0] : options.from\n if (isNaN(from) || !isFinite(from)) {\n throw new RangeError(\"'From' value must be a number\");\n }\n var to = options.to === undefined ? x[x.length - 1] : options.to;\n if (isNaN(to) || !isFinite(to)) {\n throw new RangeError(\"'To' value must be a number\");\n }\n\n var reverse = from > to;\n if(reverse) {\n var temp = from;\n from = to;\n to = temp;\n }\n\n var numberOfPoints = options.numberOfPoints === undefined ? 100 : options.numberOfPoints;\n if (isNaN(numberOfPoints) || !isFinite(numberOfPoints)) {\n throw new RangeError(\"'Number of points' value must be a number\");\n }\n if(numberOfPoints < 1)\n throw new RangeError(\"the number of point must be higher than 1\");\n\n var algorithm = options.variant === \"slot\" ? \"slot\" : \"smooth\"; // default value: smooth\n\n var output = algorithm === \"slot\" ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints);\n\n return reverse ? output.reverse() : output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"smooth\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"smooth\"\n */\nfunction getEquallySpacedSmooth(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n var initialOriginalStep = x[1] - x[0];\n var lastOriginalStep = x[x.length - 1] - x[x.length - 2];\n\n // Init main variables\n var min = start;\n var max = start + step;\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 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 j++;\n\n if (j === numberOfPoints)\n break main;\n\n min = max;\n max += step;\n sumAtMin = sumAtMax;\n }\n\n if(previousX <= min && min <= nextX) {\n add = integral(0, min - previousX, slope, previousY);\n sumAtMin = currentValue + add;\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 // updating parameters\n slope = getSlope(previousX, previousY, nextX, nextY);\n intercept = -slope*previousX + previousY;\n }\n\n return output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"slot\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"slot\"\n */\nfunction getEquallySpacedSlot(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n var lastStep = x[x.length - 1] - x[x.length - 2];\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n // Init main variables\n var min = start;\n var max = start + step;\n\n var previousX = -Number.MAX_VALUE;\n var previousY = 0;\n var nextX = x[0];\n var nextY = y[0];\n var frontOutsideSpectra = 0;\n var backOutsideSpectra = true;\n\n var currentValue = 0;\n\n // for slot algorithm\n var currentPoints = 0;\n\n var i = 1; // index of input\n var j = 0; // index of output\n\n main: while(true) {\n if (previousX>=nextX) throw (new Error('x must be an increasing serie'));\n while (previousX - max > 0) {\n // no overlap with original point, just consume current value\n if(backOutsideSpectra) {\n currentPoints++;\n backOutsideSpectra = false;\n }\n\n output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints;\n j++;\n\n if (j === numberOfPoints)\n break main;\n\n 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 previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else {\n nextX += lastStep;\n nextY = 0;\n frontOutsideSpectra++;\n }\n }\n\n return output;\n}\n/**\n * Function that calculates the integral of the line between two\n * x-coordinates, given the slope and intercept of the line.\n *\n * @param x0\n * @param x1\n * @param slope\n * @param intercept\n * @returns {number} integral value.\n */\nfunction integral(x0, x1, slope, intercept) {\n return (0.5 * slope * x1 * x1 + intercept * x1) - (0.5 * slope * x0 * x0 + intercept * x0);\n}\n\nexports.getEquallySpacedData = getEquallySpacedData;\nexports.integral = integral;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-array-utils/src/getEquallySpaced.js\n// module id = 66\n// module chunks = 0","'use strict';\n\nexports.SNV = SNV;\nvar Stat = require('ml-stat').array;\n\n/**\n * Function that applies the standard normal variate (SNV) to an array of values.\n *\n * @param data - Array of values.\n * @returns {Array} - applied the SNV.\n */\nfunction SNV(data) {\n var mean = Stat.mean(data);\n var std = Stat.standardDeviation(data);\n var result = data.slice();\n for (var i = 0; i < data.length; i++) {\n result[i] = (result[i] - mean) / std;\n }\n return result;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-array-utils/src/snv.js\n// module id = 67\n// module chunks = 0","// auxiliary file to create the 256 look at table elements\n\nvar ans = new Array(256);\nfor (var i = 0; i < 256; i++) {\n var num = i;\n var c = 0;\n while (num) {\n num = num & (num - 1);\n c++;\n }\n ans[i] = c;\n}\n\nmodule.exports = ans;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-bit-array/src/creator.js\n// module id = 68\n// module chunks = 0","'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 if (p[j - 1] === 0) {\n for (i = j - 1; i !== 1; i--)\n p[i] = -1;\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 do\n j++;\n while (p[j] > 0);\n k = j - 1;\n i = j;\n while (p[i] === 0)\n p[i++] = -1;\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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-combinations/src/index.js\n// module id = 69\n// module chunks = 0","'use strict';\n\n/**\n * ConfusionMatrix class\n */\nclass ConfusionMatrix {\n /**\n * Constructor\n * @param {Array} matrix - The confusion matrix, a 2D Array\n * @param {Array} labels - Labels of the confusion matrix, a 1D Array\n */\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 * Compute the general prediction accuracy\n * @returns {number} - The prediction accuracy ([0-1]\n */\n get accuracy() {\n var correct = 0, 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\n return correct / (correct + incorrect);\n }\n\n /**\n * Compute the number of predicted observations\n * @returns {number} - The number of predicted observations\n */\n get nbPredicted() {\n var 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\nmodule.exports = ConfusionMatrix;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-cross-validation/src/ConfusionMatrix.js\n// module id = 70\n// module chunks = 0","/**\n * Created by acastillo on 8/5/15.\n */\nvar Matrix = require(\"ml-matrix\");\nvar math = require(\"./algebra\");\n\nvar DEBUG = false;\n/** Levenberg Marquardt curve-fitting: minimize sum of weighted squared residuals\n ---------- INPUT VARIABLES -----------\n func = function of n independent variables, 't', and m parameters, 'p',\n returning the simulated model: y_hat = func(t,p,c)\n p = n-vector of initial guess of parameter values\n t = m-vectors or matrix of independent variables (used as arg to func)\n y_dat = m-vectors or matrix of data to be fit by func(t,p)\n weight = weighting vector for least squares fit ( weight >= 0 ) ...\n inverse of the standard measurement errors\n Default: sqrt(d.o.f. / ( y_dat' * y_dat ))\n dp = fractional increment of 'p' for numerical derivatives\n dp(j)>0 central differences calculated\n dp(j)<0 one sided 'backwards' differences calculated\n dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed\n Default: 0.001;\n p_min = n-vector of lower bounds for parameter values\n p_max = n-vector of upper bounds for parameter values\n c = an optional matrix of values passed to func(t,p,c)\n opts = vector of algorithmic parameters\n parameter defaults meaning\n opts(1) = prnt 3 >1 intermediate results; >2 plots\n opts(2) = MaxIter 10*Npar maximum number of iterations\n opts(3) = epsilon_1 1e-3 convergence tolerance for gradient\n opts(4) = epsilon_2 1e-3 convergence tolerance for parameters\n opts(5) = epsilon_3 1e-3 convergence tolerance for Chi-square\n opts(6) = epsilon_4 1e-2 determines acceptance of a L-M step\n opts(7) = lambda_0 1e-2 initial value of L-M paramter\n opts(8) = lambda_UP_fac 11 factor for increasing lambda\n opts(9) = lambda_DN_fac 9 factor for decreasing lambda\n opts(10) = Update_Type 1 1: Levenberg-Marquardt lambda update\n 2: Quadratic update\n 3: Nielsen's lambda update equations\n\n ---------- OUTPUT VARIABLES -----------\n p = least-squares optimal estimate of the parameter values\n X2 = Chi squared criteria\n sigma_p = asymptotic standard error of the parameters\n sigma_y = asymptotic standard error of the curve-fit\n corr = correlation matrix of the parameters\n R_sq = R-squared cofficient of multiple determination\n cvg_hst = convergence history\n\n Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. 22 Sep 2013\n modified from: http://octave.sourceforge.net/optim/function/leasqr.html\n using references by\n Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15.\n Sam Roweis http://www.cs.toronto.edu/~roweis/notes/lm.pdf\n Manolis Lourakis http://www.ics.forth.gr/~lourakis/levmar/levmar.pdf\n Hans Nielson http://www2.imm.dtu.dk/~hbn/publ/TR9905.ps\n Mathworks optimization toolbox reference manual\n K. Madsen, H.B., Nielsen, and O. Tingleff\n http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf\n */\nvar LM = {\n\n optimize: function(func,p,t,y_dat,weight,dp,p_min,p_max,c,opts){\n\n var tensor_parameter = 0;\t\t\t// set to 1 of parameter is a tensor\n\n var iteration = 0;\t\t\t// iteration counter\n //func_calls = 0;\t\t\t// running count of function evaluations\n\n if((typeof p[0])!=\"object\"){\n for(var i=0;i< p.length;i++){\n p[i]=[p[i]];\n }\n\n }\n //p = p(:); y_dat = y_dat(:); \t\t// make column vectors\n var i,k;\n var eps = 2^-52;\n var Npar = p.length;//length(p); \t\t\t// number of parameters\n var Npnt = y_dat.length;//length(y_dat);\t\t// number of data points\n var p_old = Matrix.zeros(Npar,1);\t\t// previous set of parameters\n var y_old = Matrix.zeros(Npnt,1);\t\t// previous model, y_old = y_hat(t;p_old)\n var X2 = 1e-2/eps;\t\t\t// a really big initial Chi-sq value\n var X2_old = 1e-2/eps;\t\t\t// a really big initial Chi-sq value\n var J = Matrix.zeros(Npnt,Npar);\n\n\n if (t.length != y_dat.length) {\n console.log('lm.m error: the length of t must equal the length of y_dat');\n\n length_t = t.length;\n length_y_dat = y_dat.length;\n var X2 = 0, corr = 0, sigma_p = 0, sigma_y = 0, R_sq = 0, cvg_hist = 0;\n if (!tensor_parameter) {\n return;\n }\n }\n\n weight = weight||Math.sqrt((Npnt-Npar+1)/(math.multiply(math.transpose(y_dat),y_dat)));\n dp = dp || 0.001;\n p_min = p_min || math.multiply(Math.abs(p),-100);\n p_max = p_max || math.multiply(Math.abs(p),100);\n c = c || 1;\n // Algorithmic Paramters\n //prnt MaxIter eps1 eps2 epx3 eps4 lam0 lamUP lamDN UpdateType\n opts = opts ||[ 3,10*Npar, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 1 ];\n\n var prnt = opts[0];\t// >1 intermediate results; >2 plots\n var MaxIter = opts[1];\t// maximum number of iterations\n var epsilon_1 = opts[2];\t// convergence tolerance for gradient\n var epsilon_2 = opts[3];\t// convergence tolerance for parameter\n var epsilon_3 = opts[4];\t// convergence tolerance for Chi-square\n var epsilon_4 = opts[5];\t// determines acceptance of a L-M step\n var lambda_0 = opts[6];\t// initial value of damping paramter, lambda\n var lambda_UP_fac = opts[7];\t// factor for increasing lambda\n var lambda_DN_fac = opts[8];\t// factor for decreasing lambda\n var Update_Type = opts[9];\t// 1: Levenberg-Marquardt lambda update\n // 2: Quadratic update\n // 3: Nielsen's lambda update equations\n\n if ( tensor_parameter && prnt == 3 ) prnt = 2;\n\n\n if(!dp.length || dp.length == 1){\n var dp_array = new Array(Npar);\n for(var i=0;i 2;\n //this is a big step\n // --- Are parameters [p+h] much better than [p] ?\n var hidx = new Array(idx.length);\n for(k=0;k epsilon_4 ) {\t\t// it IS significantly better\n //console.log(\"Here\");\n dX2 = X2 - X2_old;\n X2_old = X2;\n p_old = p;\n y_old = y_hat;\n p = p_try;\t\t\t// accept p_try\n\n result = this.lm_matx(func, t, p_old, y_old, dX2, J, p, y_dat, weight_sq, dp, c);\n JtWJ = result.JtWJ,JtWdy=result.JtWdy,X2=result.Chi_sq,y_hat=result.y_hat,J=result.J;\n // decrease lambda ==> Gauss-Newton method\n\n switch (Update_Type) {\n case 1:\t\t\t\t\t\t\t// Levenberg\n lambda = Math.max(lambda / lambda_DN_fac, 1.e-7);\n break;\n case 2:\t\t\t\t\t\t\t// Quadratic\n lambda = Math.max(lambda / (1 + alpha), 1.e-7);\n break;\n case 3:\t\t\t\t\t\t\t// Nielsen\n lambda = math.multiply(Math.max(1 / 3, 1 - (2 * rho - 1) ^ 3),lambda);\n nu = 2;\n break;\n }\n }\n else {\t\t\t\t\t// it IS NOT better\n X2 = X2_old;\t\t\t// do not accept p_try\n if (iteration%(2 * Npar)==0) {\t// rank-1 update of Jacobian\n result = this.lm_matx(func, t, p_old, y_old, -1, J, p, y_dat, weight_sq, dp, c);\n JtWJ = result.JtWJ,JtWdy=result.JtWdy,dX2=result.Chi_sq,y_hat=result.y_hat,J=result.J;\n }\n\n // increase lambda ==> gradient descent method\n switch (Update_Type) {\n case 1:\t\t\t\t\t\t\t// Levenberg\n lambda = Math.min(lambda * lambda_UP_fac, 1.e7);\n break;\n case 2:\t\t\t\t\t\t\t// Quadratic\n lambda = lambda + Math.abs((X2_try - X2) / 2 / alpha);\n break;\n case 3:\t\t\t\t\t\t// Nielsen\n lambda = lambda * nu;\n nu = 2 * nu;\n break;\n }\n }\n }// --- End of Main Loop\n\n // --- convergence achieved, find covariance and confidence intervals\n\n // equal weights for paramter error analysis\n weight_sq = math.multiply(math.multiply(math.transpose(delta_y),delta_y), Matrix.ones(Npnt,1));\n\n weight_sq.apply(function(i,j){\n weight_sq[i][j] = (Npnt-Nfit+1)/weight_sq[i][j];\n });\n //console.log(weight_sq);\n result = this.lm_matx(func,t,p_old,y_old,-1,J,p,y_dat,weight_sq,dp,c);\n JtWJ = result.JtWJ,JtWdy=result.JtWdy,X2=result.Chi_sq,y_hat=result.y_hat,J=result.J;\n\n /*if nargout > 2\t\t\t\t// standard error of parameters\n covar = inv(JtWJ);\n sigma_p = sqrt(diag(covar));\n end\n\n if nargout > 3\t\t\t\t// standard error of the fit\n // sigma_y = sqrt(diag(J * covar * J'));\t// slower version of below\n sigma_y = zeros(Npnt,1);\n for i=1:Npnt\n sigma_y(i) = J(i,:) * covar * J(i,:)';\n end\n sigma_y = sqrt(sigma_y);\n end\n\n if nargout > 4\t\t\t\t// parameter correlation matrix\n corr = covar ./ [sigma_p*sigma_p'];\n end\n\n if nargout > 5\t\t\t\t// coefficient of multiple determination\n R_sq = corrcoef([y_dat y_hat]);\n R_sq = R_sq(1,2).^2;\n end\n\n if nargout > 6\t\t\t\t// convergence history\n cvg_hst = cvg_hst(1:iteration,:);\n end*/\n\n // endfunction # ---------------------------------------------------------- LM\n\n return { p:p, X2:X2};\n },\n\n lm_FD_J:function(func,t,p,y,dp,c) {\n // J = lm_FD_J(func,t,p,y,{dp},{c})\n //\n // partial derivatives (Jacobian) dy/dp for use with lm.m\n // computed via Finite Differences\n // Requires n or 2n function evaluations, n = number of nonzero values of dp\n // -------- INPUT VARIABLES ---------\n // func = function of independent variables, 't', and parameters, 'p',\n // returning the simulated model: y_hat = func(t,p,c)\n // t = m-vector of independent variables (used as arg to func)\n // p = n-vector of current parameter values\n // y = func(t,p,c) n-vector initialised by user before each call to lm_FD_J\n // dp = fractional increment of p for numerical derivatives\n // dp(j)>0 central differences calculated\n // dp(j)<0 one sided differences calculated\n // dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed\n // Default: 0.001;\n // c = optional vector of constants passed to y_hat = func(t,p,c)\n //---------- OUTPUT VARIABLES -------\n // J = Jacobian Matrix J(i,j)=dy(i)/dp(j)\ti=1:n; j=1:m\n\n // Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. November 2005\n // modified from: ftp://fly.cnuce.cnr.it/pub/software/octave/leasqr/\n // Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15.\n\n var m = y.length;\t\t\t// number of data points\n var n = p.length;\t\t\t// number of parameters\n\n dp = dp || math.multiply( Matrix.ones(n, 1), 0.001);\n\n var ps = p.clone();//JSON.parse(JSON.stringify(p));\n //var ps = $.extend(true, [], p);\n var J = new Matrix(m,n), del =new Array(n); // initialize Jacobian to Zero\n\n for (var j = 0;j < n; j++) {\n //console.log(j+\" \"+dp[j]+\" \"+p[j]+\" \"+ps[j]+\" \"+del[j]);\n del[j] = dp[j]*(1+Math.abs(p[j][0])); // parameter perturbation\n p[j] = [ps[j][0]+del[j]];\t // perturb parameter p(j)\n //console.log(j+\" \"+dp[j]+\" \"+p[j]+\" \"+ps[j]+\" \"+del[j]);\n\n if (del[j] != 0){\n y1 = func(t, p, c);\n //func_calls = func_calls + 1;\n if (dp[j][0] < 0) {\t\t// backwards difference\n //J(:,j) = math.dotDivide(math.subtract(y1, y),del[j]);//. / del[j];\n //console.log(del[j]);\n //console.log(y);\n var column = math.dotDivide(math.subtract(y1, y),del[j]);\n for(var k=0;k< m;k++){\n J[k][j]=column[k][0];\n }\n //console.log(column);\n }\n else{\n p[j][0] = ps[j][0] - del[j];\n //J(:,j) = (y1 - feval(func, t, p, c)). / (2. * del[j]);\n var column = math.dotDivide(math.subtract(y1,func(t,p,c)),2*del[j]);\n for(var k=0;k< m;k++){\n J[k][j]=column[k][0];\n }\n\n }\t\t\t// central difference, additional func call\n }\n\n p[j] = ps[j];\t\t// restore p(j)\n\n }\n //console.log(\"lm_FD_J: \"+ JSON.stringify(J));\n return J;\n\n },\n\n // endfunction # -------------------------------------------------- LM_FD_J\n lm_Broyden_J: function(p_old,y_old,J,p,y){\n // J = lm_Broyden_J(p_old,y_old,J,p,y)\n // carry out a rank-1 update to the Jacobian matrix using Broyden's equation\n //---------- INPUT VARIABLES -------\n // p_old = previous set of parameters\n // y_old = model evaluation at previous set of parameters, y_hat(t;p_old)\n // J = current version of the Jacobian matrix\n // p = current set of parameters\n // y = model evaluation at current set of parameters, y_hat(t;p)\n //---------- OUTPUT VARIABLES -------\n // J = rank-1 update to Jacobian Matrix J(i,j)=dy(i)/dp(j)\ti=1:n; j=1:m\n //console.log(p+\" X \"+ p_old)\n var h = math.subtract(p, p_old);\n\n //console.log(\"hhh \"+h);\n var h_t = math.transpose(h);\n h_t.div(math.multiply(h_t,h));\n\n //console.log(h_t);\n //J = J + ( y - y_old - J*h )*h' / (h'*h);\t// Broyden rank-1 update eq'n\n J = math.add(J, math.multiply(math.subtract(y, math.add(y_old,math.multiply(J,h))),h_t));\n return J;\n // endfunction # ---------------------------------------------- LM_Broyden_J\n },\n\n lm_matx : function (func,t,p_old,y_old,dX2,J,p,y_dat,weight_sq,dp,c,iteration){\n // [JtWJ,JtWdy,Chi_sq,y_hat,J] = this.lm_matx(func,t,p_old,y_old,dX2,J,p,y_dat,weight_sq,{da},{c})\n //\n // Evaluate the linearized fitting matrix, JtWJ, and vector JtWdy,\n // and calculate the Chi-squared error function, Chi_sq\n // Used by Levenberg-Marquard algorithm, lm.m\n // -------- INPUT VARIABLES ---------\n // func = function ofpn independent variables, p, and m parameters, p,\n // returning the simulated model: y_hat = func(t,p,c)\n // t = m-vectors or matrix of independent variables (used as arg to func)\n // p_old = n-vector of previous parameter values\n // y_old = m-vector of previous model ... y_old = y_hat(t;p_old);\n // dX2 = previous change in Chi-squared criteria\n // J = m-by-n Jacobian of model, y_hat, with respect to parameters, p\n // p = n-vector of current parameter values\n // y_dat = n-vector of data to be fit by func(t,p,c)\n // weight_sq = square of the weighting vector for least squares fit ...\n //\t inverse of the standard measurement errors\n // dp = fractional increment of 'p' for numerical derivatives\n // dp(j)>0 central differences calculated\n // dp(j)<0 one sided differences calculated\n // dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed\n // Default: 0.001;\n // c = optional vector of constants passed to y_hat = func(t,p,c)\n //---------- OUTPUT VARIABLES -------\n // JtWJ\t = linearized Hessian matrix (inverse of covariance matrix)\n // JtWdy = linearized fitting vector\n // Chi_sq = Chi-squared criteria: weighted sum of the squared residuals WSSR\n // y_hat = model evaluated with parameters 'p'\n // J = m-by-n Jacobian of model, y_hat, with respect to parameters, p\n\n // Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. November 2005\n // modified from: ftp://fly.cnuce.cnr.it/pub/software/octave/leasqr/\n // Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15.\n\n\n var Npnt = y_dat.length;\t\t// number of data points\n var Npar = p.length;\t\t// number of parameters\n\n dp = dp || 0.001;\n\n\n //var JtWJ = new Matrix.zeros(Npar);\n //var JtWdy = new Matrix.zeros(Npar,1);\n\n var y_hat = func(t,p,c);\t// evaluate model using parameters 'p'\n //func_calls = func_calls + 1;\n //console.log(J);\n if ( (iteration%(2*Npar))==0 || dX2 > 0 ) {\n //console.log(\"Par\");\n J = this.lm_FD_J(func, t, p, y_hat, dp, c);\t\t// finite difference\n }\n else{\n //console.log(\"ImPar\");\n J = this.lm_Broyden_J(p_old, y_old, J, p, y_hat); // rank-1 update\n }\n //console.log(y_dat);\n //console.log(y_hat);\n var delta_y = math.subtract(y_dat, y_hat);\t// residual error between model and data\n //console.log(delta_y[0][0]);\n //console.log(delta_y.rows+\" \"+delta_y.columns+\" \"+JSON.stringify(weight_sq));\n //var Chi_sq = delta_y' * ( delta_y .* weight_sq ); \t// Chi-squared error criteria\n var Chi_sq = math.multiply(math.transpose(delta_y),math.dotMultiply(delta_y,weight_sq));\n //JtWJ = J' * ( J .* ( weight_sq * ones(1,Npar) ) );\n var Jt = math.transpose(J);\n\n //console.log(weight_sq);\n\n var JtWJ = math.multiply(Jt, math.dotMultiply(J,math.multiply(weight_sq, Matrix.ones(1,Npar))));\n\n //JtWdy = J' * ( weight_sq .* delta_y );\n var JtWdy = math.multiply(Jt, math.dotMultiply(weight_sq,delta_y));\n\n\n return {JtWJ:JtWJ,JtWdy:JtWdy,Chi_sq:Chi_sq,y_hat:y_hat,J:J};\n // endfunction # ------------------------------------------------------ LM_MATX\n }\n\n\n\n};\n\nmodule.exports = LM;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-curve-fitting/src/LM.js\n// module id = 71\n// module chunks = 0","\"use strict\";\n\nexports.additiveSymmetric = require('./distances/additiveSymmetric');\nexports.avg = require('./distances/avg');\nexports.bhattacharyya = require('./distances/bhattacharyya');\nexports.canberra = require('./distances/canberra');\nexports.chebyshev = require('./distances/chebyshev');\nexports.clark = require('./distances/clark');\nexports.czekanowski = require('./distances/czekanowski');\nexports.dice = require('./distances/dice');\nexports.divergence = require('./distances/divergence');\nexports.euclidean = require('ml-distance-euclidean');\nexports.fidelity = require('./distances/fidelity');\nexports.gower = require('./distances/gower');\nexports.harmonicMean = require('./distances/harmonicMean');\nexports.hellinger = require('./distances/hellinger');\nexports.innerProduct = require('./distances/innerProduct');\nexports.intersection = require('./distances/intersection');\nexports.jaccard = require('./distances/jaccard');\nexports.jeffreys = require('./distances/jeffreys');\nexports.jensenDifference = require('./distances/jensenDifference');\nexports.jensenShannon = require('./distances/jensenShannon');\nexports.kdivergence = require('./distances/kdivergence');\nexports.kulczynski = require('./distances/kulczynski');\nexports.kullbackLeibler = require('./distances/kullbackLeibler');\nexports.kumarHassebrook = require('./distances/kumarHassebrook');\nexports.kumarJohnson = require('./distances/kumarJohnson');\nexports.lorentzian = require('./distances/lorentzian');\nexports.manhattan = require('./distances/manhattan');\nexports.matusita = require('./distances/matusita');\nexports.minkowski = require('./distances/minkowski');\nexports.motyka = require('./distances/motyka');\nexports.neyman = require('./distances/neyman');\nexports.pearson = require('./distances/pearson');\nexports.probabilisticSymmetric = require('./distances/probabilisticSymmetric');\nexports.ruzicka = require('./distances/ruzicka');\nexports.soergel = require('./distances/soergel');\nexports.sorensen = require('./distances/sorensen');\nexports.squared = require('./distances/squared');\nexports.squaredChord = require('./distances/squaredChord');\nexports.squaredEuclidean = require('ml-distance-euclidean').squared;\nexports.taneja = require('./distances/taneja');\nexports.tanimoto = require('./distances/tanimoto');\nexports.topsoe = require('./distances/topsoe');\nexports.tree = require('ml-tree-similarity');\nexports.waveHedges = require('./distances/waveHedges');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances.js\n// module id = 72\n// module chunks = 0","module.exports = function additiveSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]);\n }\n return 2 * d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/additiveSymmetric.js\n// module id = 73\n// module chunks = 0","module.exports = function avg(a, b) {\n var ii = a.length,\n max = 0,\n ans = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n ans += aux;\n if (max < aux) {\n max = aux;\n }\n }\n return (max + ans) / 2;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/avg.js\n// module id = 74\n// module chunks = 0","module.exports = function bhattacharyya(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return - Math.log(ans);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/bhattacharyya.js\n// module id = 75\n// module chunks = 0","module.exports = function canberra(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/canberra.js\n// module id = 76\n// module chunks = 0","module.exports = function chebyshev(a, b) {\n var ii = a.length,\n max = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n if (max < aux) {\n max = aux;\n }\n }\n return max;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/chebyshev.js\n// module id = 77\n// module chunks = 0","module.exports = function clark(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])));\n }\n return 2 * d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/clark.js\n// module id = 78\n// module chunks = 0","'use strict';\n\nconst czekanowskiSimilarity = require('../similarities/czekanowski');\n\nmodule.exports = function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/czekanowski.js\n// module id = 79\n// module chunks = 0","module.exports = function divergence(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]));\n }\n return 2 * d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/divergence.js\n// module id = 80\n// module chunks = 0","module.exports = function fidelity(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/fidelity.js\n// module id = 81\n// module chunks = 0","module.exports = function gower(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]);\n }\n return ans / ii;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/gower.js\n// module id = 82\n// module chunks = 0","module.exports = function harmonicMean(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] * b[i]) / (a[i] + b[i]);\n }\n return 2 * ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/harmonicMean.js\n// module id = 83\n// module chunks = 0","module.exports = function hellinger(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return 2 * Math.sqrt(1 - ans);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/hellinger.js\n// module id = 84\n// module chunks = 0","module.exports = function innerProduct(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/innerProduct.js\n// module id = 85\n// module chunks = 0","module.exports = function jeffreys(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] - b[i]) * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/jeffreys.js\n// module id = 86\n// module chunks = 0","module.exports = function jensenDifference(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += ((a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2) - ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/jensenDifference.js\n// module id = 87\n// module chunks = 0","module.exports = function jensenShannon(a, b) {\n var ii = a.length,\n p = 0,\n q = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n q += b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return (p + q) / 2;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/jensenShannon.js\n// module id = 88\n// module chunks = 0","module.exports = function kdivergence(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kdivergence.js\n// module id = 89\n// module chunks = 0","module.exports = function kullbackLeibler(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kullbackLeibler.js\n// module id = 90\n// module chunks = 0","module.exports = function kumarHassebrook(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (p2 + q2 - p);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kumarHassebrook.js\n// module id = 91\n// module chunks = 0","module.exports = function kumarJohnson(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.pow(a[i] * a[i] - b[i] * b[i],2) / (2 * Math.pow(a[i] * b[i],1.5));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kumarJohnson.js\n// module id = 92\n// module chunks = 0","module.exports = function lorentzian(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.log(Math.abs(a[i] - b[i]) + 1);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/lorentzian.js\n// module id = 93\n// module chunks = 0","module.exports = function manhattan(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/manhattan.js\n// module id = 94\n// module chunks = 0","module.exports = function matusita(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return Math.sqrt(2 - 2 * ans);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/matusita.js\n// module id = 95\n// module chunks = 0","module.exports = function minkowski(a, b, p) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.pow(Math.abs(a[i] - b[i]),p);\n }\n return Math.pow(d,(1/p));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/minkowski.js\n// module id = 96\n// module chunks = 0","module.exports = function neyman(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / a[i];\n }\n return d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/neyman.js\n// module id = 97\n// module chunks = 0","module.exports = function pearson(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / b[i];\n }\n return d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/pearson.js\n// module id = 98\n// module chunks = 0","module.exports = function probabilisticSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return 2 * d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/probabilisticSymmetric.js\n// module id = 99\n// module chunks = 0","module.exports = function ruzicka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i],b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/ruzicka.js\n// module id = 100\n// module chunks = 0","module.exports = function soergel(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/soergel.js\n// module id = 101\n// module chunks = 0","module.exports = function sorensen(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += a[i] + b[i];\n }\n return up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/sorensen.js\n// module id = 102\n// module chunks = 0","module.exports = function squared(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/squared.js\n// module id = 103\n// module chunks = 0","module.exports = function taneja(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/taneja.js\n// module id = 104\n// module chunks = 0","var tanimotoS = require('./../similarities/tanimoto');\n\nmodule.exports = function tanimoto(a, b, bitvector) {\n if (bitvector)\n return 1 - tanimotoS(a, b, bitvector);\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return (p + q - 2 * m) / (p + q - m);\n }\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/tanimoto.js\n// module id = 105\n// module chunks = 0","module.exports = function topsoe(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/topsoe.js\n// module id = 106\n// module chunks = 0","module.exports = function waveHedges(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += 1 - (Math.min(a[i], b[i]) / Math.max(a[i], b[i]));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/waveHedges.js\n// module id = 107\n// module chunks = 0","\"use strict\";\n\nexports.cosine = require('./similarities/cosine');\nexports.czekanowski = require('./similarities/czekanowski');\nexports.dice = require('./similarities/dice');\nexports.intersection = require('./similarities/intersection');\nexports.jaccard = require('./similarities/jaccard');\nexports.kulczynski = require('./similarities/kulczynski');\nexports.motyka = require('./similarities/motyka');\nexports.pearson = require('./similarities/pearson');\nexports.squaredChord = require('./similarities/squaredChord');\nexports.tanimoto = require('./similarities/tanimoto');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities.js\n// module id = 108\n// module chunks = 0","var diceD = require('./../distances/dice');\n\nmodule.exports = function dice(a, b) {\n return 1 - diceD(a,b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/dice.js\n// module id = 109\n// module chunks = 0","var intersectionD = require('./../distances/intersection');\n\nmodule.exports = function intersection(a, b) {\n return 1 - intersectionD(a,b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/intersection.js\n// module id = 110\n// module chunks = 0","var jaccardD = require('./../distances/jaccard');\n\nmodule.exports = function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/jaccard.js\n// module id = 111\n// module chunks = 0","var kulczynskiD = require('./../distances/kulczynski');\n\nmodule.exports = function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/kulczynski.js\n// module id = 112\n// module chunks = 0","var motykaD = require('./../distances/motyka');\n\nmodule.exports = function motyka(a, b) {\n return 1 - motykaD(a,b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/motyka.js\n// module id = 113\n// module chunks = 0","'use strict';\n\nvar stat=require('ml-stat').array;\nvar cosine=require('./cosine');\n\nmodule.exports = function pearson(a, b) {\n var avgA=stat.mean(a);\n var avgB=stat.mean(b);\n\n var newA=new Array(a.length);\n var newB=new Array(b.length);\n for (var i=0; i>} distance - Array of points to be clustered\n * @param {json} options\n * @option isDistanceMatrix: Is the input a distance matrix?\n * @constructor\n */\nfunction agnes(data, options) {\n options = Object.assign({}, defaultOptions, options);\n var len = data.length;\n\n var distance = data;//If source\n if(!options.isDistanceMatrix) {\n distance = new Array(len);\n for(var i = 0;i < len; i++) {\n distance[i] = new Array(len);\n for (var j = 0; j < len; j++) {\n distance[i][j] = options.disFunc(data[i],data[j]);\n }\n }\n }\n\n\n // allows to use a string or a given function\n if (typeof options.kind === \"string\") {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n }\n else if (typeof options.kind !== \"function\")\n throw new TypeError('Undefined kind of similarity');\n\n var list = new Array(len);\n for (var i = 0; i < distance.length; i++)\n list[i] = new ClusterLeaf(i);\n var min = 10e5,\n d = {},\n dis = 0;\n\n while (list.length > 1) {\n // calculates the minimum distance\n d = {};\n min = 10e5;\n for (var j = 0; j < list.length; j++){\n for (var k = j + 1; k < list.length; k++) {\n var fdistance, sdistance;\n if (list[j] instanceof ClusterLeaf)\n fdistance = [list[j].index];\n else {\n fdistance = new Array(list[j].index.length);\n for (var e = 0; e < fdistance.length; e++)\n fdistance[e] = list[j].index[e].index;\n }\n if (list[k] instanceof ClusterLeaf)\n sdistance = [list[k].index];\n else {\n sdistance = new Array(list[k].index.length);\n for (var f = 0; f < sdistance.length; f++)\n sdistance[f] = list[k].index[f].index;\n }\n dis = options.kind(fdistance, sdistance, distance).toFixed(4);\n if (dis in d) {\n d[dis].push([list[j], list[k]]);\n }\n else {\n d[dis] = [[list[j], list[k]]];\n }\n min = Math.min(dis, min);\n }\n }\n // cluster dots\n var dmin = d[min.toFixed(4)];\n var clustered = new Array(dmin.length);\n var aux,\n count = 0;\n while (dmin.length > 0) {\n aux = dmin.shift();\n for (var q = 0; q < dmin.length; q++) {\n var int = dmin[q].filter(function(n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) !== -1\n });\n if (int.length > 0) {\n var diff = dmin[q].filter(function(n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) === -1\n });\n aux = aux.concat(diff);\n dmin.splice(q-- ,1);\n }\n }\n clustered[count++] = aux;\n }\n clustered.length = count;\n\n for (var ii = 0; ii < clustered.length; ii++) {\n var obj = new Cluster();\n obj.children = clustered[ii].concat();\n obj.distance = min;\n obj.index = new Array(len);\n var indCount = 0;\n for (var jj = 0; jj < clustered[ii].length; jj++) {\n if (clustered[ii][jj] instanceof ClusterLeaf)\n obj.index[indCount++] = clustered[ii][jj];\n else {\n indCount += clustered[ii][jj].index.length;\n obj.index = clustered[ii][jj].index.concat(obj.index);\n }\n list.splice((list.indexOf(clustered[ii][jj])), 1);\n }\n obj.index.length = indCount;\n list.push(obj);\n }\n }\n return list[0];\n}\n\nmodule.exports = agnes;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/agnes.js\n// module id = 118\n// module chunks = 0","'use strict';\n\nvar euclidean = require('ml-distance-euclidean');\nvar ClusterLeaf = require('./ClusterLeaf');\nvar Cluster = require('./Cluster');\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++)\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.min(d,m);\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++)\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.max(d,m);\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++)\n for (var j = 0; j < cluster2.length; j++)\n m += disFun(cluster1[i], cluster2[j]);\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1,y1], [x2,y2]);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1,y1], [x2,y2])*cluster1.length*cluster2.length / (cluster1.length+cluster2.length);\n}\n\n/**\n * @private\n * Returns the most distant point and his distance\n * @param {Array >} splitting - Clusters to split\n * @param {Array >} data - Original data\n * @param {function} disFun - Distance function\n * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant\n */\nfunction diff(splitting, data, disFun) {\n var ans = {\n d:0,\n p:0\n };\n\n var Ci = new Array(splitting[0].length);\n for (var e = 0; e < splitting[0].length; e++)\n Ci[e] = data[splitting[0][e]];\n var Cj = new Array(splitting[1].length);\n for (var f = 0; f < splitting[1].length; f++)\n Cj[f] = data[splitting[1][f]];\n\n var dist, ndist;\n for (var i = 0; i < Ci.length; i++) {\n dist = 0;\n for (var j = 0; j < Ci.length; j++)\n if (i !== j)\n dist += disFun(Ci[i], Ci[j]);\n dist /= (Ci.length - 1);\n ndist = 0;\n for (var k = 0; k < Cj.length; k++)\n ndist += disFun(Ci[i], Cj[k]);\n ndist /= Cj.length;\n if ((dist - ndist) > ans.d) {\n ans.d = (dist - ndist);\n ans.p = i;\n }\n }\n return ans;\n}\n\nvar defaultOptions = {\n dist: euclidean,\n kind: 'single'\n};\n\n/**\n * @private\n * Intra-cluster distance\n * @param {Array} index\n * @param {Array} data\n * @param {function} disFun\n * @returns {number}\n */\nfunction intrDist(index, data, disFun) {\n var dist = 0,\n count = 0;\n for (var i = 0; i < index.length; i++)\n for (var j = i; j < index.length; j++) {\n dist += disFun(data[index[i].index], data[index[j].index]);\n count++\n }\n return dist / count;\n}\n\n/**\n * Splits the higher level clusters\n * @param {Array >} data - Array of points to be clustered\n * @param {json} options\n * @constructor\n */\nfunction diana(data, options) {\n options = options || {};\n for (var o in defaultOptions)\n if (!(options.hasOwnProperty(o)))\n options[o] = defaultOptions[o];\n if (typeof options.kind === \"string\") {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n }\n else if (typeof options.kind !== \"function\")\n throw new TypeError('Undefined kind of similarity');\n var tree = new Cluster();\n tree.children = new Array(data.length);\n tree.index = new Array(data.length);\n for (var ind = 0; ind < data.length; ind++) {\n tree.children[ind] = new ClusterLeaf(ind);\n tree.index[ind] = new ClusterLeaf(ind);\n }\n\n tree.distance = intrDist(tree.index, data, options.dist);\n var m, M, clId,\n dist, rebel;\n var list = [tree];\n while (list.length > 0) {\n M = 0;\n clId = 0;\n for (var i = 0; i < list.length; i++) {\n m = 0;\n for (var j = 0; j < list[i].length; j++) {\n for (var l = (j + 1); l < list[i].length; l++) {\n m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m);\n }\n }\n if (m > M) {\n M = m;\n clId = i;\n }\n }\n M = 0;\n if (list[clId].index.length === 2) {\n list[clId].children = [list[clId].index[0], list[clId].index[1]];\n list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]);\n }\n else if (list[clId].index.length === 3) {\n list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]];\n var d = [\n options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]),\n options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index])\n ];\n list[clId].distance = (d[0] + d[1]) / 2;\n }\n else {\n var C = new Cluster();\n var sG = new Cluster();\n var splitting = [new Array(list[clId].index.length), []];\n for (var spl = 0; spl < splitting[0].length; spl++)\n splitting[0][spl] = spl;\n for (var ii = 0; ii < splitting[0].length; ii++) {\n dist = 0;\n for (var jj = 0; jj < splitting[0].length; jj++)\n if (ii !== jj)\n dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]);\n dist /= (splitting[0].length - 1);\n if (dist > M) {\n M = dist;\n rebel = ii;\n }\n }\n splitting[1] = [rebel];\n splitting[0].splice(rebel, 1);\n dist = diff(splitting, data, options.dist);\n while (dist.d > 0) {\n splitting[1].push(splitting[0][dist.p]);\n splitting[0].splice(dist.p, 1);\n dist = diff(splitting, data, options.dist);\n }\n var fData = new Array(splitting[0].length);\n C.index = new Array(splitting[0].length);\n for (var e = 0; e < fData.length; e++) {\n fData[e] = data[list[clId].index[splitting[0][e]].index];\n C.index[e] = list[clId].index[splitting[0][e]];\n C.children[e] = list[clId].index[splitting[0][e]];\n }\n var sData = new Array(splitting[1].length);\n sG.index = new Array(splitting[1].length);\n for (var f = 0; f < sData.length; f++) {\n sData[f] = data[list[clId].index[splitting[1][f]].index];\n sG.index[f] = list[clId].index[splitting[1][f]];\n sG.children[f] = list[clId].index[splitting[1][f]];\n }\n C.distance = intrDist(C.index, data, options.dist);\n sG.distance = intrDist(sG.index, data, options.dist);\n list.push(C);\n list.push(sG);\n list[clId].children = [C, sG];\n }\n list.splice(clId, 1);\n }\n return tree;\n}\n\nmodule.exports = diana;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/diana.js\n// module id = 119\n// module chunks = 0","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass GaussianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = GaussianKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel-gaussian/gaussian-kernel.js\n// module id = 120\n// module chunks = 0","'use strict';\n\nconst defaultOptions = {\n degree: 1,\n constant: 1,\n scale: 1\n};\n\nclass PolynomialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n\n this.degree = options.degree;\n this.constant = options.constant;\n this.scale = options.scale;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.pow(this.scale * sum + this.constant, this.degree);\n }\n}\n\nmodule.exports = PolynomialKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel-polynomial/polynomial-kernel.js\n// module id = 121\n// module chunks = 0","'use strict';\n\nconst defaultOptions = {\n alpha: 0.01,\n constant: -Math.E\n};\n\nclass SigmoidKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.alpha = options.alpha;\n this.constant = options.constant;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.tanh(this.alpha * sum + this.constant);\n }\n}\n\nmodule.exports = SigmoidKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel-sigmoid/sigmoid-kernel.js\n// module id = 122\n// module chunks = 0","'use strict';\n\nconst defaultOptions = {\n sigma: 1,\n degree: 1\n};\n\nclass ANOVAKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.degree = options.degree;\n }\n\n compute(x, y) {\n var sum = 0;\n var len = Math.min(x.length, y.length);\n for (var i = 1; i <= len; ++i) {\n sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) -\n Math.pow(y[i - 1], i), 2)), this.degree);\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/anova-kernel.js\n// module id = 123\n// module chunks = 0","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass CauchyKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma));\n }\n}\n\nmodule.exports = CauchyKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/cauchy-kernel.js\n// module id = 124\n// module chunks = 0","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass ExponentialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = ExponentialKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/exponential-kernel.js\n// module id = 125\n// module chunks = 0","'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 return sum;\n }\n}\n\nmodule.exports = HistogramIntersectionKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/histogram-intersection-kernel.js\n// module id = 126\n// module chunks = 0","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass LaplacianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.sigma);\n }\n}\n\nmodule.exports = LaplacianKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/laplacian-kernel.js\n// module id = 127\n// module chunks = 0","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass MultiquadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant);\n }\n}\n\nmodule.exports = MultiquadraticKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/multiquadratic-kernel.js\n// module id = 128\n// module chunks = 0","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass RationalQuadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return 1 - (distance / (distance + this.constant));\n }\n}\n\nmodule.exports = RationalQuadraticKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/rational-quadratic-kernel.js\n// module id = 129\n// module chunks = 0","'use strict';\n\nconst utils = require('./utils');\nconst distanceSymbol = Symbol('distance');\n\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 */\nfunction KMeansResult(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 */\nKMeansResult.prototype.nearest = function (data) {\n var clusterID = new Array(data.length);\n var centroids = this.centroids.map(function (centroid) {\n return centroid.centroid;\n });\n return utils.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 */\nKMeansResult.prototype.computeInformation = function (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](data[i], this.centroids[this.clusters[i]]);\n enrichedCentroids[this.clusters[i]].size++;\n }\n\n for (var j = 0; j < this.centroids.length; j++) {\n enrichedCentroids[j].error /= enrichedCentroids[j].size;\n }\n\n return new KMeansResult(this.clusters, enrichedCentroids, this.converged, this.iterations, this[distanceSymbol]);\n};\n\nmodule.exports = KMeansResult;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kmeans/src/KMeansResult.js\n// module id = 130\n// module chunks = 0","'use strict';\n\nconst Picker = require('RandomSelection').Picker;\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 * @return {Array>} - Initial random points\n */\nfunction random(data, K) {\n const rand = new Picker(data);\n var ans = new Array(K);\n\n for (var i = 0; i < K; ++i) {\n ans[i] = rand.pick();\n }\n return ans;\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 * @return {Array>} - Initial random points\n */\nfunction mostDistant(data, K, distanceMatrix) {\n var ans = new Array(K);\n\n // chooses a random point as initial cluster\n ans[0] = Math.floor(Math.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\n // minimum distance to centers\n var minDistCent = {dist: Number.MAX_VALUE, index: -1};\n for (var n = 0; n < k; ++n) {\n if (distanceMatrix[n][m] < minDistCent.dist && ans.indexOf(m) === -1) {\n minDistCent = {\n dist: distanceMatrix[n][m],\n index: m\n };\n }\n }\n\n if (minDistCent.dist !== Number.MAX_VALUE && minDistCent.dist > center.dist) {\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\nexports.random = random;\nexports.mostDistant = mostDistant;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kmeans/src/initialization.js\n// module id = 131\n// module chunks = 0","'use strict';\n\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\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\nfunction kdTree(points, metric, dimensions) {\n\n var self = this;\n\n function buildTree(points, depth, parent) {\n var dim = depth % dimensions.length,\n median,\n node;\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(function (a, b) {\n return a[dimensions[dim]] - b[dimensions[dim]];\n });\n\n median = Math.floor(points.length / 2);\n node = new Node(points[median], dim, parent);\n node.left = buildTree(points.slice(0, median), depth + 1, node);\n node.right = buildTree(points.slice(median + 1), depth + 1, node);\n\n return node;\n }\n\n // Reloads a serialied tree\n function loadTree (data) {\n // Just need to restore the `parent` parameter\n self.root = data;\n\n function 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 restoreParent(self.root);\n }\n\n // If points is not an array, assume we're loading a pre-built tree\n if (!Array.isArray(points)) loadTree(points, metric, dimensions);\n else this.root = buildTree(points, 0, null);\n\n // Convert to a JSON serializable structure; this just requires removing\n // the `parent` property\n this.toJSON = function (src) {\n if (!src) src = this.root;\n var dest = new Node(src.obj, src.dimension, null);\n if (src.left) dest.left = self.toJSON(src.left);\n if (src.right) dest.right = self.toJSON(src.right);\n return dest;\n };\n\n this.insert = function (point) {\n function innerSearch(node, parent) {\n\n if (node === null) {\n return parent;\n }\n\n var dimension = dimensions[node.dimension];\n if (point[dimension] < node.obj[dimension]) {\n return innerSearch(node.left, node);\n } else {\n return innerSearch(node.right, node);\n }\n }\n\n var insertPosition = innerSearch(this.root, null),\n newNode,\n dimension;\n\n if (insertPosition === null) {\n this.root = new Node(point, 0, null);\n return;\n }\n\n newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition);\n dimension = dimensions[insertPosition.dimension];\n\n if (point[dimension] < insertPosition.obj[dimension]) {\n insertPosition.left = newNode;\n } else {\n insertPosition.right = newNode;\n }\n };\n\n this.remove = function (point) {\n var node;\n\n function nodeSearch(node) {\n if (node === null) {\n return null;\n }\n\n if (node.obj === point) {\n return node;\n }\n\n var dimension = dimensions[node.dimension];\n\n if (point[dimension] < node.obj[dimension]) {\n return nodeSearch(node.left, node);\n } else {\n return nodeSearch(node.right, node);\n }\n }\n\n function removeNode(node) {\n var nextNode,\n nextObj,\n pDimension;\n\n function findMin(node, dim) {\n var dimension,\n own,\n left,\n right,\n min;\n\n if (node === null) {\n return null;\n }\n\n dimension = dimensions[dim];\n\n if (node.dimension === dim) {\n if (node.left !== null) {\n return findMin(node.left, dim);\n }\n return node;\n }\n\n own = node.obj[dimension];\n left = findMin(node.left, dim);\n right = findMin(node.right, dim);\n min = node;\n\n if (left !== null && left.obj[dimension] < own) {\n min = left;\n }\n if (right !== null && right.obj[dimension] < min.obj[dimension]) {\n min = right;\n }\n return min;\n }\n\n if (node.left === null && node.right === null) {\n if (node.parent === null) {\n self.root = null;\n return;\n }\n\n pDimension = dimensions[node.parent.dimension];\n\n if (node.obj[pDimension] < node.parent.obj[pDimension]) {\n node.parent.left = null;\n } else {\n node.parent.right = null;\n }\n return;\n }\n\n // If the right subtree is not empty, swap with the minimum element on the\n // node's dimension. If it is empty, we swap the left and right subtrees and\n // do the same.\n if (node.right !== null) {\n nextNode = findMin(node.right, node.dimension);\n nextObj = nextNode.obj;\n removeNode(nextNode);\n node.obj = nextObj;\n } else {\n nextNode = findMin(node.left, node.dimension);\n nextObj = nextNode.obj;\n removeNode(nextNode);\n node.right = node.left;\n node.left = null;\n node.obj = nextObj;\n }\n\n }\n\n node = nodeSearch(self.root);\n\n if (node === null) { return; }\n\n removeNode(node);\n };\n\n this.nearest = function (point, maxNodes, maxDistance) {\n var i,\n result,\n bestNodes;\n\n bestNodes = new BinaryHeap(\n function (e) { return -e[1]; }\n );\n\n function nearestSearch(node) {\n var bestChild,\n dimension = dimensions[node.dimension],\n ownDistance = metric(point, node.obj),\n linearPoint = {},\n linearDistance,\n otherChild,\n i;\n\n function saveNode(node, distance) {\n bestNodes.push([node, distance]);\n if (bestNodes.size() > maxNodes) {\n bestNodes.pop();\n }\n }\n\n for (i = 0; i < dimensions.length; i += 1) {\n if (i === node.dimension) {\n linearPoint[dimensions[i]] = point[dimensions[i]];\n } else {\n linearPoint[dimensions[i]] = node.obj[dimensions[i]];\n }\n }\n\n linearDistance = metric(linearPoint, node.obj);\n\n if (node.right === null && node.left === null) {\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n return;\n }\n\n if (node.right === null) {\n bestChild = node.left;\n } else if (node.left === null) {\n bestChild = node.right;\n } else {\n if (point[dimension] < node.obj[dimension]) {\n bestChild = node.left;\n } else {\n bestChild = node.right;\n }\n }\n\n nearestSearch(bestChild);\n\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n\n if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {\n if (bestChild === node.left) {\n otherChild = node.right;\n } else {\n otherChild = node.left;\n }\n if (otherChild !== null) {\n nearestSearch(otherChild);\n }\n }\n }\n\n if (maxDistance) {\n for (i = 0; i < maxNodes; i += 1) {\n bestNodes.push([null, maxDistance]);\n }\n }\n\n if(self.root)\n nearestSearch(self.root);\n\n result = [];\n\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 this.balanceFactor = function () {\n function height(node) {\n if (node === null) {\n return 0;\n }\n return Math.max(height(node.left), height(node.right)) + 1;\n }\n\n function count(node) {\n if (node === null) {\n return 0;\n }\n return count(node.left) + count(node.right) + 1;\n }\n\n return height(self.root) / (Math.log(count(self.root)) / Math.log(2));\n };\n}\n\n// Binary heap implementation from:\n// http://eloquentjavascript.net/appendix2.html\n\nfunction BinaryHeap(scoreFunction){\n this.content = [];\n this.scoreFunction = scoreFunction;\n}\n\nBinaryHeap.prototype = {\n push: function(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: function() {\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: function() {\n return this.content[0];\n },\n\n remove: function(node) {\n var len = this.content.length;\n // To remove a value, we must search through the array to find\n // it.\n for (var i = 0; i < len; i++) {\n if (this.content[i] == node) {\n // When it is found, the process seen in 'pop' is repeated\n // to fill up the hole.\n var end = this.content.pop();\n if (i != len - 1) {\n this.content[i] = end;\n if (this.scoreFunction(end) < this.scoreFunction(node))\n this.bubbleUp(i);\n else\n this.sinkDown(i);\n }\n return;\n }\n }\n throw new Error(\"Node not found.\");\n },\n\n size: function() {\n return this.content.length;\n },\n\n bubbleUp: function(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 var parentN = Math.floor((n + 1) / 2) - 1,\n 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 }\n // Found a parent that is less, no need to move it further.\n else {\n break;\n }\n }\n },\n\n sinkDown: function(n) {\n // Look up the target element and its score.\n var length = this.content.length,\n element = this.content[n],\n elemScore = this.scoreFunction(element);\n\n while(true) {\n // Compute the indices of the child elements.\n var child2N = (n + 1) * 2, 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 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 // Do the same checks for the other child.\n if (child2N < length) {\n var child2 = this.content[child2N],\n 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 }\n // Otherwise, we are done.\n else {\n break;\n }\n }\n }\n};\n\nthis.kdTree = kdTree;\n\nexports.kdTree = kdTree;\nexports.BinaryHeap = BinaryHeap;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-knn/src/kdtree.js\n// module id = 132\n// module chunks = 0","'use strict';\n\nmodule.exports = KNN;\n\nvar KDTree = require('./kdtree').kdTree;\nvar Distances = require('ml-distance');\n\n/**\n * K-Nearest neighboor constructor.\n *\n * @param reload - loading purposes.\n * @param model - loading purposes\n * @constructor\n */\nfunction KNN(reload, model) {\n if(reload) {\n this.kdtree = model.kdtree;\n this.k = model.k;\n this.classes = model.classes;\n }\n}\n\n/**\n * Function that trains the KNN with the given trainingSet and trainingLabels.\n * The third argument is an object with the following options.\n * * distance: that represent the distance function applied (default: euclidean)\n * * k: the number of neighboors to take in count for classify (default: number of features + 1)\n *\n * @param trainingSet\n * @param trainingLabels\n * @param options\n */\nKNN.prototype.train = function (trainingSet, trainingLabels, options) {\n if(options === undefined) options = {};\n if(options.distance === undefined) options.distance = Distances.distance.euclidean;\n if(options.k === undefined) options.k = trainingSet[0].length + 1;\n\n var classes = 0;\n var exist = new Array(1000);\n var j = 0;\n for(var i = 0; i < trainingLabels.length; ++i) {\n if(exist.indexOf(trainingLabels[i]) === -1) {\n classes++;\n exist[j] = trainingLabels[i];\n j++;\n }\n }\n\n // copy dataset\n var points = new Array(trainingSet.length);\n for(i = 0; i < points.length; ++i) {\n points[i] = trainingSet[i].slice();\n }\n\n this.features = trainingSet[0].length;\n for(i = 0; i < trainingLabels.length; ++i) {\n points[i].push(trainingLabels[i]);\n }\n\n var dimensions = new Array(trainingSet[0].length);\n for(i = 0; i < dimensions.length; ++i) {\n dimensions[i] = i;\n }\n\n this.kdtree = new KDTree(points, options.distance, dimensions);\n this.k = options.k;\n this.classes = classes;\n};\n\n/**\n * Function that returns the predictions given the dataset.\n * \n * @param dataset\n * @returns {Array}\n */\nKNN.prototype.predict = function (dataset) {\n var predictions = new Array(dataset.length);\n for(var i = 0; i < dataset.length; ++i) {\n predictions[i] = this.getSinglePrediction(dataset[i]);\n }\n\n return predictions;\n};\n\n/**\n * function that returns a prediction for a single case.\n * @param currentCase\n * @returns {number}\n */\nKNN.prototype.getSinglePrediction = function (currentCase) {\n var nearestPoints = this.kdtree.nearest(currentCase, this.k);\n var pointsPerClass = new Array(this.classes);\n var predictedClass = -1;\n var maxPoints = -1;\n var lastElement = nearestPoints[0][0].length - 1;\n\n for(var i = 0; i < pointsPerClass.length; ++i) {\n pointsPerClass[i] = 0;\n }\n\n for(i = 0; i < nearestPoints.length; ++i) {\n var currentClass = nearestPoints[i][0][lastElement];\n var currentPoints = ++pointsPerClass[currentClass];\n if(currentPoints > maxPoints) {\n predictedClass = currentClass;\n maxPoints = currentPoints;\n }\n }\n\n return predictedClass;\n};\n\n/**\n * function that returns a KNN classifier with the given model.\n *\n * @param model\n */\nKNN.load = function (model) {\n if(model.modelName !== \"KNN\")\n throw new RangeError(\"The given model is invalid!\");\n\n return new KNN(true, model);\n};\n\n/**\n * function that exports the current KNN classifier.\n */\nKNN.prototype.export = function () {\n return {\n modelName: \"KNN\",\n kdtree: this.kdtree,\n k: this.k,\n classes: this.classes\n };\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-knn/src/knn.js\n// module id = 133\n// module chunks = 0","'use strict';\n\nvar Matrix = require('../matrix').Matrix;\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\nfunction CholeskyDecomposition(value) {\n if (!(this instanceof CholeskyDecomposition)) {\n return new CholeskyDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n if (!value.isSymmetric()) {\n throw new Error('Matrix is not symmetric');\n }\n\n var a = value,\n dimension = a.rows,\n l = new Matrix(dimension, dimension),\n positiveDefinite = true,\n i, j, k;\n\n for (j = 0; j < dimension; j++) {\n var Lrowj = l[j];\n var d = 0;\n for (k = 0; k < j; k++) {\n var Lrowk = l[k];\n var s = 0;\n for (i = 0; i < k; i++) {\n s += Lrowk[i] * Lrowj[i];\n }\n Lrowj[k] = s = (a[j][k] - s) / l[k][k];\n d = d + s * s;\n }\n\n d = a[j][j] - d;\n\n positiveDefinite &= (d > 0);\n l[j][j] = Math.sqrt(Math.max(d, 0));\n for (k = j + 1; k < dimension; k++) {\n l[j][k] = 0;\n }\n }\n\n if (!positiveDefinite) {\n throw new Error('Matrix is not positive definite');\n }\n\n this.L = l;\n}\n\nCholeskyDecomposition.prototype = {\n get lowerTriangularMatrix() {\n return this.L;\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var l = this.L,\n dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n\n var count = value.columns,\n B = value.clone(),\n i, j, k;\n\n for (k = 0; k < dimension; k++) {\n for (j = 0; j < count; j++) {\n for (i = 0; i < k; i++) {\n B[k][j] -= B[i][j] * l[k][i];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n for (k = dimension - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n for (i = k + 1; i < dimension; i++) {\n B[k][j] -= B[i][j] * l[i][k];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n return B;\n }\n};\n\nmodule.exports = CholeskyDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/cholesky.js\n// module id = 134\n// module chunks = 0","'use strict';\n\nconst Matrix = require('../matrix').Matrix;\nconst util = require('./util');\nconst hypotenuse = util.hypotenuse;\nconst getFilled2DArray = util.getFilled2DArray;\n\nconst defaultOptions = {\n assumeSymmetric: false\n};\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\nfunction EigenvalueDecomposition(matrix, options) {\n options = Object.assign({}, defaultOptions, options);\n if (!(this instanceof EigenvalueDecomposition)) {\n return new EigenvalueDecomposition(matrix, options);\n }\n matrix = Matrix.checkMatrix(matrix);\n if (!matrix.isSquare()) {\n throw new Error('Matrix is not a square matrix');\n }\n\n var n = matrix.columns,\n V = getFilled2DArray(n, n, 0),\n d = new Array(n),\n e = new Array(n),\n value = matrix,\n i, j;\n\n var isSymmetric = false;\n if (options.assumeSymmetric) {\n isSymmetric = true;\n } else {\n isSymmetric = matrix.isSymmetric();\n }\n\n if (isSymmetric) {\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = value.get(i, j);\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n var H = getFilled2DArray(n, n, 0),\n ort = new Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H[i][j] = value.get(i, j);\n }\n }\n orthes(n, H, ort, V);\n hqr2(n, e, d, V, H);\n }\n\n this.n = n;\n this.e = e;\n this.d = d;\n this.V = V;\n}\n\nEigenvalueDecomposition.prototype = {\n get realEigenvalues() {\n return this.d;\n },\n get imaginaryEigenvalues() {\n return this.e;\n },\n get eigenvectorMatrix() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n var n = this.n,\n e = this.e,\n d = this.d,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X[i][j] = 0;\n }\n X[i][i] = d[i];\n if (e[i] > 0) {\n X[i][i + 1] = e[i];\n } else if (e[i] < 0) {\n X[i][i - 1] = e[i];\n }\n }\n return X;\n }\n};\n\nfunction tred2(n, e, d, V) {\n\n var f, g, h, i, j, k,\n hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n }\n\n for (i = n - 1; i > 0; i--) {\n scale = 0;\n h = 0;\n for (k = 0; k < i; k++) {\n scale = scale + Math.abs(d[k]);\n }\n\n if (scale === 0) {\n e[i] = d[i - 1];\n for (j = 0; j < i; j++) {\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n V[j][i] = 0;\n }\n } else {\n for (k = 0; k < i; k++) {\n d[k] /= scale;\n h += d[k] * d[k];\n }\n\n f = d[i - 1];\n g = Math.sqrt(h);\n if (f > 0) {\n g = -g;\n }\n\n e[i] = scale * g;\n h = h - f * g;\n d[i - 1] = f - g;\n for (j = 0; j < i; j++) {\n e[j] = 0;\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n V[j][i] = f;\n g = e[j] + V[j][j] * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V[k][j] * d[k];\n e[k] += V[k][j] * f;\n }\n e[j] = g;\n }\n\n f = 0;\n for (j = 0; j < i; j++) {\n e[j] /= h;\n f += e[j] * d[j];\n }\n\n hh = f / (h + h);\n for (j = 0; j < i; j++) {\n e[j] -= hh * d[j];\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n g = e[j];\n for (k = j; k <= i - 1; k++) {\n V[k][j] -= (f * e[k] + g * d[k]);\n }\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V[n - 1][i] = V[i][i];\n V[i][i] = 1;\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V[k][i + 1] / h;\n }\n\n for (j = 0; j <= i; j++) {\n g = 0;\n for (k = 0; k <= i; k++) {\n g += V[k][i + 1] * V[k][j];\n }\n for (k = 0; k <= i; k++) {\n V[k][j] -= g * d[k];\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V[k][i + 1] = 0;\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n V[n - 1][j] = 0;\n }\n\n V[n - 1][n - 1] = 1;\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n\n var g, h, i, j, k, l, m, p, r,\n dl1, c, c2, c3, el1, s, s2,\n iter;\n\n for (i = 1; i < n; i++) {\n e[i - 1] = e[i];\n }\n\n e[n - 1] = 0;\n\n var f = 0,\n tst1 = 0,\n eps = Math.pow(2, -52);\n\n for (l = 0; l < n; l++) {\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\n m = l;\n while (m < n) {\n if (Math.abs(e[m]) <= eps * tst1) {\n break;\n }\n m++;\n }\n\n if (m > l) {\n iter = 0;\n do {\n iter = iter + 1;\n\n g = d[l];\n p = (d[l + 1] - g) / (2 * e[l]);\n r = hypotenuse(p, 1);\n if (p < 0) {\n r = -r;\n }\n\n d[l] = e[l] / (p + r);\n d[l + 1] = e[l] * (p + r);\n dl1 = d[l + 1];\n h = g - d[l];\n for (i = l + 2; i < n; i++) {\n d[i] -= h;\n }\n\n f = f + h;\n\n p = d[m];\n c = 1;\n c2 = c;\n c3 = c;\n el1 = e[l + 1];\n s = 0;\n s2 = 0;\n for (i = m - 1; i >= l; i--) {\n c3 = c2;\n c2 = c;\n s2 = s;\n g = c * e[i];\n h = c * p;\n r = hypotenuse(p, e[i]);\n e[i + 1] = s * r;\n s = e[i] / r;\n c = p / r;\n p = c * d[i] - s * g;\n d[i + 1] = h + s * (c * g + s * d[i]);\n\n for (k = 0; k < n; k++) {\n h = V[k][i + 1];\n V[k][i + 1] = s * V[k][i] + c * h;\n V[k][i] = c * V[k][i] - s * h;\n }\n }\n\n p = -s * s2 * c3 * el1 * e[l] / dl1;\n e[l] = s * p;\n d[l] = c * p;\n\n }\n while (Math.abs(e[l]) > eps * tst1);\n }\n d[l] = d[l] + f;\n e[l] = 0;\n }\n\n for (i = 0; i < n - 1; i++) {\n k = i;\n p = d[i];\n for (j = i + 1; j < n; j++) {\n if (d[j] < p) {\n k = j;\n p = d[j];\n }\n }\n\n if (k !== i) {\n d[k] = d[i];\n d[i] = p;\n for (j = 0; j < n; j++) {\n p = V[j][i];\n V[j][i] = V[j][k];\n V[j][k] = p;\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n\n var low = 0,\n high = n - 1,\n f, g, h, i, j, m,\n scale;\n\n for (m = low + 1; m <= high - 1; m++) {\n scale = 0;\n for (i = m; i <= high; i++) {\n scale = scale + Math.abs(H[i][m - 1]);\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H[i][m - 1] / scale;\n h += ort[i] * ort[i];\n }\n\n g = Math.sqrt(h);\n if (ort[m] > 0) {\n g = -g;\n }\n\n h = h - ort[m] * g;\n ort[m] = ort[m] - g;\n\n for (j = m; j < n; j++) {\n f = 0;\n for (i = high; i >= m; i--) {\n f += ort[i] * H[i][j];\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H[i][j] -= f * ort[i];\n }\n }\n\n for (i = 0; i <= high; i++) {\n f = 0;\n for (j = high; j >= m; j--) {\n f += ort[j] * H[i][j];\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H[i][j] -= f * ort[j];\n }\n }\n\n ort[m] = scale * ort[m];\n H[m][m - 1] = scale * g;\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = (i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H[m][m - 1] !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H[i][m - 1];\n }\n\n for (j = m; j <= high; j++) {\n g = 0;\n for (i = m; i <= high; i++) {\n g += ort[i] * V[i][j];\n }\n\n g = (g / ort[m]) / H[m][m - 1];\n for (i = m; i <= high; i++) {\n V[i][j] += g * ort[i];\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n var n = nn - 1,\n low = 0,\n high = nn - 1,\n eps = Math.pow(2, -52),\n exshift = 0,\n norm = 0,\n p = 0,\n q = 0,\n r = 0,\n s = 0,\n z = 0,\n iter = 0,\n i, j, k, l, m, t, w, x, y,\n ra, sa, vr, vi,\n notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H[i][i];\n e[i] = 0;\n }\n\n for (j = Math.max(i - 1, 0); j < nn; j++) {\n norm = norm + Math.abs(H[i][j]);\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H[l][l - 1]) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H[n][n] = H[n][n] + exshift;\n d[n] = H[n][n];\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H[n][n - 1] * H[n - 1][n];\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H[n][n] = H[n][n] + exshift;\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\n x = H[n][n];\n\n if (q >= 0) {\n z = (p >= 0) ? (p + z) : (p - z);\n d[n - 1] = x + z;\n d[n] = d[n - 1];\n if (z !== 0) {\n d[n] = x - w / z;\n }\n e[n - 1] = 0;\n e[n] = 0;\n x = H[n][n - 1];\n s = Math.abs(x) + Math.abs(z);\n p = x / s;\n q = z / s;\n r = Math.sqrt(p * p + q * q);\n p = p / r;\n q = q / r;\n\n for (j = n - 1; j < nn; j++) {\n z = H[n - 1][j];\n H[n - 1][j] = q * z + p * H[n][j];\n H[n][j] = q * H[n][j] - p * z;\n }\n\n for (i = 0; i <= n; i++) {\n z = H[i][n - 1];\n H[i][n - 1] = q * z + p * H[i][n];\n H[i][n] = q * H[i][n] - p * z;\n }\n\n for (i = low; i <= high; i++) {\n z = V[i][n - 1];\n V[i][n - 1] = q * z + p * V[i][n];\n V[i][n] = q * V[i][n] - p * z;\n }\n } else {\n d[n - 1] = x + p;\n d[n] = x + p;\n e[n - 1] = z;\n e[n] = -z;\n }\n\n n = n - 2;\n iter = 0;\n } else {\n x = H[n][n];\n y = 0;\n w = 0;\n if (l < n) {\n y = H[n - 1][n - 1];\n w = H[n][n - 1] * H[n - 1][n];\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H[i][i] -= x;\n }\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\n x = y = 0.75 * s;\n w = -0.4375 * s * s;\n }\n\n if (iter === 30) {\n s = (y - x) / 2;\n s = s * s + w;\n if (s > 0) {\n s = Math.sqrt(s);\n if (y < x) {\n s = -s;\n }\n s = x - w / ((y - x) / 2 + s);\n for (i = low; i <= n; i++) {\n H[i][i] -= s;\n }\n exshift += s;\n x = y = w = 0.964;\n }\n }\n\n iter = iter + 1;\n\n m = n - 2;\n while (m >= l) {\n z = H[m][m];\n r = x - z;\n s = y - z;\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\n q = H[m + 1][m + 1] - z - r - s;\n r = H[m + 2][m + 1];\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\n p = p / s;\n q = q / s;\n r = r / s;\n if (m === l) {\n break;\n }\n if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H[i][i - 2] = 0;\n if (i > m + 2) {\n H[i][i - 3] = 0;\n }\n }\n\n for (k = m; k <= n - 1; k++) {\n notlast = (k !== n - 1);\n if (k !== m) {\n p = H[k][k - 1];\n q = H[k + 1][k - 1];\n r = (notlast ? H[k + 2][k - 1] : 0);\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\n if (x !== 0) {\n p = p / x;\n q = q / x;\n r = r / x;\n }\n }\n\n if (x === 0) {\n break;\n }\n\n s = Math.sqrt(p * p + q * q + r * r);\n if (p < 0) {\n s = -s;\n }\n\n if (s !== 0) {\n if (k !== m) {\n H[k][k - 1] = -s * x;\n } else if (l !== m) {\n H[k][k - 1] = -H[k][k - 1];\n }\n\n p = p + s;\n x = p / s;\n y = q / s;\n z = r / s;\n q = q / p;\n r = r / p;\n\n for (j = k; j < nn; j++) {\n p = H[k][j] + q * H[k + 1][j];\n if (notlast) {\n p = p + r * H[k + 2][j];\n H[k + 2][j] = H[k + 2][j] - p * z;\n }\n\n H[k][j] = H[k][j] - p * x;\n H[k + 1][j] = H[k + 1][j] - p * y;\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H[i][k] + y * H[i][k + 1];\n if (notlast) {\n p = p + z * H[i][k + 2];\n H[i][k + 2] = H[i][k + 2] - p * r;\n }\n\n H[i][k] = H[i][k] - p;\n H[i][k + 1] = H[i][k + 1] - p * q;\n }\n\n for (i = low; i <= high; i++) {\n p = x * V[i][k] + y * V[i][k + 1];\n if (notlast) {\n p = p + z * V[i][k + 2];\n V[i][k + 2] = V[i][k + 2] - p * r;\n }\n\n V[i][k] = V[i][k] - p;\n V[i][k + 1] = V[i][k + 1] - p * q;\n }\n }\n }\n }\n }\n\n if (norm === 0) {\n return;\n }\n\n for (n = nn - 1; n >= 0; n--) {\n p = d[n];\n q = e[n];\n\n if (q === 0) {\n l = n;\n H[n][n] = 1;\n for (i = n - 1; i >= 0; i--) {\n w = H[i][i] - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H[i][j] * H[j][n];\n }\n\n if (e[i] < 0) {\n z = w;\n s = r;\n } else {\n l = i;\n if (e[i] === 0) {\n H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm));\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H[i][n] = t;\n H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z);\n }\n\n t = Math.abs(H[i][n]);\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\n H[n - 1][n - 1] = q / H[n][n - 1];\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\n } else {\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\n H[n - 1][n - 1] = cdivres[0];\n H[n - 1][n] = cdivres[1];\n }\n\n H[n][n - 1] = 0;\n H[n][n] = 1;\n for (i = n - 2; i >= 0; i--) {\n ra = 0;\n sa = 0;\n for (j = l; j <= n; j++) {\n ra = ra + H[i][j] * H[j][n - 1];\n sa = sa + H[i][j] * H[j][n];\n }\n\n w = H[i][i] - p;\n\n if (e[i] < 0) {\n z = w;\n r = ra;\n s = sa;\n } else {\n l = i;\n if (e[i] === 0) {\n cdivres = cdiv(-ra, -sa, w, q);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\n vi = (d[i] - p) * 2 * q;\n if (vr === 0 && vi === 0) {\n vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z));\n }\n cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) {\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\n } else {\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\n H[i + 1][n - 1] = cdivres[0];\n H[i + 1][n] = cdivres[1];\n }\n }\n\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n - 1] = H[j][n - 1] / t;\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n for (j = i; j < nn; j++) {\n V[i][j] = H[i][j];\n }\n }\n }\n\n for (j = nn - 1; j >= low; j--) {\n for (i = low; i <= high; i++) {\n z = 0;\n for (k = low; k <= Math.min(j, high); k++) {\n z = z + V[i][k] * H[k][j];\n }\n V[i][j] = z;\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n var r, d;\n if (Math.abs(yr) > Math.abs(yi)) {\n r = yi / yr;\n d = yr + r * yi;\n return [(xr + r * xi) / d, (xi - r * xr) / d];\n } else {\n r = yr / yi;\n d = yi + r * yr;\n return [(r * xr + xi) / d, (r * xi - xr) / d];\n }\n}\n\nmodule.exports = EigenvalueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/evd.js\n// module id = 135\n// module chunks = 0","'use strict';\n\nvar Matrix = require('../matrix').Matrix;\nvar hypotenuse = require('./util').hypotenuse;\n\n//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\nfunction QrDecomposition(value) {\n if (!(this instanceof QrDecomposition)) {\n return new QrDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n\n var qr = value.clone(),\n m = value.rows,\n n = value.columns,\n rdiag = new Array(n),\n i, j, k, s;\n\n for (k = 0; k < n; k++) {\n var nrm = 0;\n for (i = k; i < m; i++) {\n nrm = hypotenuse(nrm, qr[i][k]);\n }\n if (nrm !== 0) {\n if (qr[k][k] < 0) {\n nrm = -nrm;\n }\n for (i = k; i < m; i++) {\n qr[i][k] /= nrm;\n }\n qr[k][k] += 1;\n for (j = k + 1; j < n; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * qr[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n qr[i][j] += s * qr[i][k];\n }\n }\n }\n rdiag[k] = -nrm;\n }\n\n this.QR = qr;\n this.Rdiag = rdiag;\n}\n\nQrDecomposition.prototype = {\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var qr = this.QR,\n m = qr.rows;\n\n if (value.rows !== m) {\n throw new Error('Matrix row dimensions must agree');\n }\n if (!this.isFullRank()) {\n throw new Error('Matrix is rank deficient');\n }\n\n var count = value.columns;\n var X = value.clone();\n var n = qr.columns;\n var i, j, k, s;\n\n for (k = 0; k < n; k++) {\n for (j = 0; j < count; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * X[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= this.Rdiag[k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * qr[i][k];\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n },\n isFullRank: function () {\n var columns = this.QR.columns;\n for (var i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n },\n get upperTriangularMatrix() {\n var qr = this.QR,\n n = qr.columns,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X[i][j] = qr[i][j];\n } else if (i === j) {\n X[i][j] = this.Rdiag[i];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get orthogonalMatrix() {\n var qr = this.QR,\n rows = qr.rows,\n columns = qr.columns,\n X = new Matrix(rows, columns),\n i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X[i][k] = 0;\n }\n X[k][k] = 1;\n for (j = k; j < columns; j++) {\n if (qr[k][k] !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr[i][k] * X[i][j];\n }\n\n s = -s / qr[k][k];\n\n for (i = k; i < rows; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n }\n return X;\n }\n};\n\nmodule.exports = QrDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/qr.js\n// module id = 136\n// module chunks = 0","'use strict';\n\nvar Matrix = require('../matrix').Matrix;\nvar util = require('./util');\nvar hypotenuse = util.hypotenuse;\nvar getFilled2DArray = util.getFilled2DArray;\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs\nfunction SingularValueDecomposition(value, options) {\n if (!(this instanceof SingularValueDecomposition)) {\n return new SingularValueDecomposition(value, options);\n }\n value = Matrix.checkMatrix(value);\n\n options = options || {};\n\n var m = value.rows,\n n = value.columns,\n nu = Math.min(m, n);\n\n var wantu = true, wantv = true;\n if (options.computeLeftSingularVectors === false) wantu = false;\n if (options.computeRightSingularVectors === false) wantv = false;\n var autoTranspose = options.autoTranspose === true;\n\n var swapped = false;\n var a;\n if (m < n) {\n if (!autoTranspose) {\n a = value.clone();\n // eslint-disable-next-line no-console\n console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose');\n } else {\n a = value.transpose();\n m = a.rows;\n n = a.columns;\n swapped = true;\n var aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n var s = new Array(Math.min(m + 1, n)),\n U = getFilled2DArray(m, nu, 0),\n V = getFilled2DArray(n, n, 0),\n e = new Array(n),\n work = new Array(m);\n\n var nct = Math.min(m - 1, n);\n var nrt = Math.max(0, Math.min(n - 2, m));\n\n var i, j, k, p, t, ks, f, cs, sn, max, kase,\n scale, sp, spm1, epm1, sk, ek, b, c, shift, g;\n\n for (k = 0, max = Math.max(nct, nrt); k < max; k++) {\n if (k < nct) {\n s[k] = 0;\n for (i = k; i < m; i++) {\n s[k] = hypotenuse(s[k], a[i][k]);\n }\n if (s[k] !== 0) {\n if (a[k][k] < 0) {\n s[k] = -s[k];\n }\n for (i = k; i < m; i++) {\n a[i][k] /= s[k];\n }\n a[k][k] += 1;\n }\n s[k] = -s[k];\n }\n\n for (j = k + 1; j < n; j++) {\n if ((k < nct) && (s[k] !== 0)) {\n t = 0;\n for (i = k; i < m; i++) {\n t += a[i][k] * a[i][j];\n }\n t = -t / a[k][k];\n for (i = k; i < m; i++) {\n a[i][j] += t * a[i][k];\n }\n }\n e[j] = a[k][j];\n }\n\n if (wantu && (k < nct)) {\n for (i = k; i < m; i++) {\n U[i][k] = a[i][k];\n }\n }\n\n if (k < nrt) {\n e[k] = 0;\n for (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 (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 (i = k + 1; i < m; i++) {\n work[i] = 0;\n }\n for (j = k + 1; j < n; j++) {\n for (i = k + 1; i < m; i++) {\n work[i] += e[j] * a[i][j];\n }\n }\n for (j = k + 1; j < n; j++) {\n t = -e[j] / e[k + 1];\n for (i = k + 1; i < m; i++) {\n a[i][j] += t * work[i];\n }\n }\n }\n if (wantv) {\n for (i = k + 1; i < n; i++) {\n V[i][k] = e[i];\n }\n }\n }\n }\n\n p = Math.min(n, m + 1);\n if (nct < n) {\n s[nct] = a[nct][nct];\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a[nrt][p - 1];\n }\n e[p - 1] = 0;\n\n if (wantu) {\n for (j = nct; j < nu; j++) {\n for (i = 0; i < m; i++) {\n U[i][j] = 0;\n }\n U[j][j] = 1;\n }\n for (k = nct - 1; k >= 0; k--) {\n if (s[k] !== 0) {\n for (j = k + 1; j < nu; j++) {\n t = 0;\n for (i = k; i < m; i++) {\n t += U[i][k] * U[i][j];\n }\n t = -t / U[k][k];\n for (i = k; i < m; i++) {\n U[i][j] += t * U[i][k];\n }\n }\n for (i = k; i < m; i++) {\n U[i][k] = -U[i][k];\n }\n U[k][k] = 1 + U[k][k];\n for (i = 0; i < k - 1; i++) {\n U[i][k] = 0;\n }\n } else {\n for (i = 0; i < m; i++) {\n U[i][k] = 0;\n }\n U[k][k] = 1;\n }\n }\n }\n\n if (wantv) {\n for (k = n - 1; k >= 0; k--) {\n if ((k < nrt) && (e[k] !== 0)) {\n for (j = k + 1; j < n; j++) {\n t = 0;\n for (i = k + 1; i < n; i++) {\n t += V[i][k] * V[i][j];\n }\n t = -t / V[k + 1][k];\n for (i = k + 1; i < n; i++) {\n V[i][j] += t * V[i][k];\n }\n }\n }\n for (i = 0; i < n; i++) {\n V[i][k] = 0;\n }\n V[k][k] = 1;\n }\n }\n\n var pp = p - 1,\n iter = 0,\n eps = Math.pow(2, -52);\n while (p > 0) {\n for (k = p - 2; k >= -1; k--) {\n if (k === -1) {\n break;\n }\n if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) {\n e[k] = 0;\n break;\n }\n }\n if (k === p - 2) {\n kase = 4;\n } else {\n for (ks = p - 1; ks >= k; ks--) {\n if (ks === k) {\n break;\n }\n t = (ks !== p ? Math.abs(e[ks]) : 0) + (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 f = e[p - 2];\n e[p - 2] = 0;\n for (j = p - 2; j >= k; j--) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][p - 1];\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\n V[i][j] = t;\n }\n }\n }\n break;\n }\n case 2 : {\n f = e[k - 1];\n e[k - 1] = 0;\n for (j = k; j < p; j++) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n sn = f / t;\n s[j] = t;\n f = -sn * e[j];\n e[j] = cs * e[j];\n if (wantu) {\n for (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][k - 1];\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\n U[i][j] = t;\n }\n }\n }\n break;\n }\n case 3 : {\n scale = Math.max(Math.max(Math.max(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]));\n sp = s[p - 1] / scale;\n spm1 = s[p - 2] / scale;\n epm1 = e[p - 2] / scale;\n sk = s[k] / scale;\n ek = e[k] / scale;\n b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\n c = (sp * epm1) * (sp * epm1);\n shift = 0;\n if ((b !== 0) || (c !== 0)) {\n shift = Math.sqrt(b * b + c);\n if (b < 0) {\n shift = -shift;\n }\n shift = c / (b + shift);\n }\n f = (sk + sp) * (sk - sp) + shift;\n g = sk * ek;\n for (j = k; j < p - 1; j++) {\n t = hypotenuse(f, g);\n cs = f / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][j + 1];\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\n V[i][j] = t;\n }\n }\n t = hypotenuse(f, g);\n 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 (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][j + 1];\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\n U[i][j] = t;\n }\n }\n }\n e[p - 2] = f;\n iter = iter + 1;\n break;\n }\n case 4: {\n if (s[k] <= 0) {\n s[k] = (s[k] < 0 ? -s[k] : 0);\n if (wantv) {\n for (i = 0; i <= pp; i++) {\n V[i][k] = -V[i][k];\n }\n }\n }\n while (k < pp) {\n if (s[k] >= s[k + 1]) {\n break;\n }\n t = s[k];\n s[k] = s[k + 1];\n s[k + 1] = t;\n if (wantv && (k < n - 1)) {\n for (i = 0; i < n; i++) {\n t = V[i][k + 1];\n V[i][k + 1] = V[i][k];\n V[i][k] = t;\n }\n }\n if (wantu && (k < m - 1)) {\n for (i = 0; i < m; i++) {\n t = U[i][k + 1];\n U[i][k + 1] = U[i][k];\n U[i][k] = t;\n }\n }\n k++;\n }\n iter = 0;\n p--;\n break;\n }\n // no default\n }\n }\n\n if (swapped) {\n var tmp = V;\n V = U;\n U = tmp;\n }\n\n this.m = m;\n this.n = n;\n this.s = s;\n this.U = U;\n this.V = V;\n}\n\nSingularValueDecomposition.prototype = {\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n },\n get norm2() {\n return this.s[0];\n },\n get rank() {\n var eps = Math.pow(2, -52),\n tol = Math.max(this.m, this.n) * this.s[0] * eps,\n r = 0,\n s = this.s;\n for (var i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n },\n get diagonal() {\n return this.s;\n },\n // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\n get threshold() {\n return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0];\n },\n get leftSingularVectors() {\n if (!Matrix.isMatrix(this.U)) {\n this.U = new Matrix(this.U);\n }\n return this.U;\n },\n get rightSingularVectors() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n },\n solve: function (value) {\n\n var Y = value,\n e = this.threshold,\n scols = this.s.length,\n Ls = Matrix.zeros(scols, scols),\n i;\n\n for (i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls[i][i] = 0;\n } else {\n Ls[i][i] = 1 / this.s[i];\n }\n }\n\n var U = this.U;\n var V = this.rightSingularVectors;\n\n var VL = V.mmul(Ls),\n vrows = V.rows,\n urows = U.length,\n VLU = Matrix.zeros(vrows, urows),\n j, k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < scols; k++) {\n sum += VL[i][k] * U[j][k];\n }\n VLU[i][j] = sum;\n }\n }\n\n return VLU.mmul(Y);\n },\n solveForDiagonal: function (value) {\n return this.solve(Matrix.diag(value));\n },\n inverse: function () {\n var V = this.V;\n var e = this.threshold,\n vrows = V.length,\n vcols = V[0].length,\n X = new Matrix(vrows, this.s.length),\n i, j;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < vcols; j++) {\n if (Math.abs(this.s[j]) > e) {\n X[i][j] = V[i][j] / this.s[j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n\n var U = this.U;\n\n var urows = U.length,\n ucols = U[0].length,\n Y = new Matrix(vrows, urows),\n k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < ucols; k++) {\n sum += X[i][k] * U[j][k];\n }\n Y[i][j] = sum;\n }\n }\n\n return Y;\n }\n};\n\nmodule.exports = SingularValueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/svd.js\n// module id = 137\n// module chunks = 0","'use strict';\n\nvar Matrix = require('./matrix').Matrix;\n\nvar SingularValueDecomposition = require('./dc/svd');\nvar EigenvalueDecomposition = require('./dc/evd');\nvar LuDecomposition = require('./dc/lu');\nvar QrDecomposition = require('./dc/qr');\nvar CholeskyDecomposition = require('./dc/cholesky');\n\nfunction inverse(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n return solve(matrix, Matrix.eye(matrix.rows));\n}\n\n/**\n * Returns the inverse\n * @memberOf Matrix\n * @static\n * @param {Matrix} matrix\n * @return {Matrix} matrix\n * @alias inv\n */\nMatrix.inverse = Matrix.inv = inverse;\n\n/**\n * Returns the inverse\n * @memberOf Matrix\n * @static\n * @param {Matrix} matrix\n * @return {Matrix} matrix\n * @alias inv\n */\nMatrix.prototype.inverse = Matrix.prototype.inv = function () {\n return inverse(this);\n};\n\nfunction solve(leftHandSide, rightHandSide) {\n leftHandSide = Matrix.checkMatrix(leftHandSide);\n rightHandSide = Matrix.checkMatrix(rightHandSide);\n return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide);\n}\n\nMatrix.solve = solve;\nMatrix.prototype.solve = function (other) {\n return solve(this, other);\n};\n\nmodule.exports = {\n SingularValueDecomposition: SingularValueDecomposition,\n SVD: SingularValueDecomposition,\n EigenvalueDecomposition: EigenvalueDecomposition,\n EVD: EigenvalueDecomposition,\n LuDecomposition: LuDecomposition,\n LU: LuDecomposition,\n QrDecomposition: QrDecomposition,\n QR: QrDecomposition,\n CholeskyDecomposition: CholeskyDecomposition,\n CHO: CholeskyDecomposition,\n inverse: inverse,\n solve: solve\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/decompositions.js\n// module id = 138\n// module chunks = 0","'use strict';\n\nif (!Symbol.species) {\n Symbol.species = Symbol.for('@@species');\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/symbol-species.js\n// module id = 139\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n super(matrix, matrix.rows, 1);\n this.column = column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.column, value);\n return this;\n }\n\n get(rowIndex) {\n return this.matrix.get(rowIndex, this.column);\n }\n}\n\nmodule.exports = MatrixColumnView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/column.js\n// module id = 140\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass 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\nmodule.exports = MatrixFlipColumnView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/flipColumn.js\n// module id = 141\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass 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\nmodule.exports = MatrixFlipRowView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/flipRow.js\n// module id = 142\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass MatrixRowView extends BaseView {\n constructor(matrix, row) {\n super(matrix, 1, matrix.columns);\n this.row = row;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.row, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.row, columnIndex);\n }\n}\n\nmodule.exports = MatrixRowView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/row.js\n// module id = 143\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\nvar util = require('../util');\n\nclass MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n var indices = util.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(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]);\n }\n}\n\nmodule.exports = MatrixSelectionView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/selection.js\n// module id = 144\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\nvar util = require('../util');\n\nclass MatrixSubView extends BaseView {\n constructor(matrix, startRow, endRow, startColumn, endColumn) {\n util.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(this.startRow + rowIndex, this.startColumn + columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex);\n }\n}\n\nmodule.exports = MatrixSubView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/sub.js\n// module id = 145\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass 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\nmodule.exports = MatrixTransposeView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/transpose.js\n// module id = 146\n// module chunks = 0","'use strict';\n\nconst squaredDistance = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n distanceFunction: squaredDistance,\n similarityFunction: false,\n returnVector: false\n};\n\n/**\n * Find the nearest vector in a list to a sample vector\n * @param {Array>} listVectors - List of vectors with same dimensions\n * @param {Array} vector - Reference vector to \"classify\"\n * @param {object} [options] - Options object\n * @param {function} [options.distanceFunction = squaredDistance] - Function that receives two vectors and return their distance value as number\n * @param {function} [options.similarityFunction = undefined] - Function that receives two vectors and return their similarity value as number\n * @param {boolean} [options.returnVector = false] - Return the nearest vector instead of its index\n * @return {number|Array} - The index or the content of the nearest vector\n */\nfunction nearestVector(listVectors, vector, options) {\n options = options || defaultOptions;\n const distanceFunction = options.distanceFunction || defaultOptions.distanceFunction;\n const similarityFunction = options.similarityFunction || defaultOptions.similarityFunction;\n const returnVector = options.returnVector || defaultOptions.returnVector;\n\n var vectorIndex = -1;\n if (typeof similarityFunction === 'function') {\n\n // maximum similarity\n var maxSim = Number.MIN_VALUE;\n for (var j = 0; j < listVectors.length; j++) {\n var sim = similarityFunction(vector, listVectors[j]);\n if (sim > maxSim) {\n maxSim = sim;\n vectorIndex = j;\n }\n }\n } else if (typeof distanceFunction === 'function') {\n\n // minimum distance\n var minDist = Number.MAX_VALUE;\n for (var i = 0; i < listVectors.length; i++) {\n var dist = distanceFunction(vector, listVectors[i]);\n if (dist < minDist) {\n minDist = dist;\n vectorIndex = i;\n }\n }\n } else {\n throw new Error('A similarity or distance function it\\'s required');\n }\n\n if (returnVector) {\n return listVectors[vectorIndex];\n } else {\n return vectorIndex;\n }\n}\n\nmodule.exports = nearestVector;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-nearest-vector/src/index.js\n// module id = 147\n// module chunks = 0","'use strict';\n\n// Accuracy\nexports.acc = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1);\n }\n return result;\n};\n\n// Error rate\nexports.err = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.fp[i] / (l - 1));\n }\n return result;\n};\n\n// False positive rate\nexports.fpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fp[i] / pred.nNeg;\n }\n return result;\n};\n\n// True positive rate\nexports.tpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tp[i] / pred.nPos;\n }\n return result;\n};\n\n// False negative rate\nexports.fnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fn[i] / pred.nPos;\n }\n return result;\n};\n\n// True negative rate\nexports.tnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tn[i] / pred.nNeg;\n }\n return result;\n};\n\n// Positive predictive value\nexports.ppv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 0;\n }\n return result;\n};\n\n// Negative predictive value\nexports.npv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 0;\n }\n return result;\n};\n\n// Prediction conditioned fallout\nexports.pcfall = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1;\n }\n return result;\n};\n\n// Prediction conditioned miss\nexports.pcmiss = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1;\n }\n return result;\n};\n\n// Lift value\nexports.lift = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.nPosPred[i] !== 0) ? ((pred.tp[i] / pred.nPos) / (pred.nPosPred[i] / pred.nSamples)) : 0;\n }\n return result;\n};\n\n// Rate of positive predictions\nexports.rpp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nPosPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Rate of negative predictions\nexports.rnp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nNegPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Threshold\nexports.threshold = pred => {\n const clone = pred.cutoffs.slice();\n clone[0] = clone[1]; // Remove the infinite value\n return clone;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-performance/src/measures.js\n// module id = 148\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\nvar Utils = require('./utils');\n\nmodule.exports = OPLS;\n\nfunction OPLS(dataset, predictions, numberOSC) {\n var X = new Matrix(dataset);\n var y = new Matrix(predictions);\n\n X = Utils.featureNormalize(X).result;\n y = Utils.featureNormalize(y).result;\n\n var rows = X.rows;\n var columns = X.columns;\n\n var sumOfSquaresX = X.clone().mul(X).sum();\n var w = X.transpose().mmul(y);\n w.div(Utils.norm(w));\n\n var orthoW = new Array(numberOSC);\n var orthoT = new Array(numberOSC);\n var orthoP = new Array(numberOSC);\n for (var i = 0; i < numberOSC; i++) {\n var t = X.mmul(w);\n\n var numerator = X.transpose().mmul(t);\n var denominator = t.transpose().mmul(t)[0][0];\n var p = numerator.div(denominator);\n\n numerator = w.transpose().mmul(p)[0][0];\n denominator = w.transpose().mmul(w)[0][0];\n var wOsc = p.sub(w.clone().mul(numerator / denominator));\n wOsc.div(Utils.norm(wOsc));\n\n var tOsc = X.mmul(wOsc);\n\n numerator = X.transpose().mmul(tOsc);\n denominator = tOsc.transpose().mmul(tOsc)[0][0];\n var pOsc = numerator.div(denominator);\n\n X.sub(tOsc.mmul(pOsc.transpose()));\n orthoW[i] = wOsc.getColumn(0);\n orthoT[i] = tOsc.getColumn(0);\n orthoP[i] = pOsc.getColumn(0);\n }\n\n this.Xosc = X;\n\n var sumOfSquaresXosx = this.Xosc.clone().mul(this.Xosc).sum();\n this.R2X = 1 - sumOfSquaresXosx/sumOfSquaresX;\n\n this.W = orthoW;\n this.T = orthoT;\n this.P = orthoP;\n this.numberOSC = numberOSC;\n}\n\nOPLS.prototype.correctDataset = function (dataset) {\n var X = new Matrix(dataset);\n\n var sumOfSquaresX = X.clone().mul(X).sum();\n for (var i = 0; i < this.numberOSC; i++) {\n var currentW = this.W.getColumnVector(i);\n var currentP = this.P.getColumnVector(i);\n\n var t = X.mmul(currentW);\n X.sub(t.mmul(currentP));\n }\n var sumOfSquaresXosx = X.clone().mul(X).sum();\n\n var R2X = 1 - sumOfSquaresXosx / sumOfSquaresX;\n\n return {\n datasetOsc: X,\n R2Dataset: R2X\n };\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pls/src/opls.js\n// module id = 149\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\nvar Utils = require('./utils');\n\nclass PLS {\n constructor(X, Y) {\n if (X === true) {\n const model = Y;\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 } else {\n if (X.length !== Y.length)\n throw new RangeError('The number of X rows must be equal to the number of Y rows');\n\n const resultX = Utils.featureNormalize(X);\n this.X = resultX.result;\n this.meanX = resultX.means;\n this.stdDevX = resultX.std;\n\n const resultY = Utils.featureNormalize(Y);\n this.Y = resultY.result;\n this.meanY = resultY.means;\n this.stdDevY = resultY.std;\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 {Object} options - recieves the latentVectors and the tolerance of each step of the PLS\n */\n train(options) {\n if(options === undefined) options = {};\n\n var latentVectors = options.latentVectors;\n if (latentVectors === undefined) {\n latentVectors = Math.min(this.X.length - 1, this.X[0].length);\n }\n\n var tolerance = options.tolerance;\n if (tolerance === undefined) {\n tolerance = 1e-5;\n }\n \n var X = this.X;\n var Y = this.Y;\n\n var rx = X.rows;\n var cx = X.columns;\n var ry = Y.rows;\n var cy = Y.columns;\n\n var ssqXcal = X.clone().mul(X).sum(); // for the r²\n var sumOfSquaresY = Y.clone().mul(Y).sum();\n\n var n = latentVectors; //Math.max(cx, cy); // components of the pls\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(Y) > tolerance && k < n) {\n var transposeX = X.transpose();\n var transposeY = Y.transpose();\n\n var tIndex = maxSumColIndex(X.clone().mulM(X));\n var uIndex = maxSumColIndex(Y.clone().mulM(Y));\n\n var t1 = X.getColumnVector(tIndex);\n var u = Y.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 = X.mmul(w);\n var q = transposeY.mmul(t1);\n q.div(Utils.norm(q));\n u = Y.mmul(q);\n }\n\n t = t1;\n var num = transposeX.mmul(t);\n var den = (t.transpose().mmul(t))[0][0];\n var p = num.div(den);\n var pnorm = Utils.norm(p);\n p.div(pnorm);\n t.mul(pnorm);\n w.mul(pnorm);\n\n num = u.transpose().mmul(t);\n den = (t.transpose().mmul(t))[0][0];\n var b = (num.div(den))[0][0];\n X.sub(t.mmul(p.transpose()));\n Y.sub(t.clone().mul(b).mmul(q.transpose()));\n\n T.setColumn(k, t);\n P.setColumn(k, p);\n U.setColumn(k, u);\n Q.setColumn(k, q);\n W.setColumn(k, w);\n\n B[k][k] = b;\n k++;\n }\n\n k--;\n T = T.subMatrix(0, T.rows - 1, 0, k);\n P = P.subMatrix(0, P.rows - 1, 0, k);\n U = U.subMatrix(0, U.rows - 1, 0, k);\n Q = Q.subMatrix(0, Q.rows - 1, 0, k);\n W = W.subMatrix(0, W.rows - 1, 0, k);\n B = B.subMatrix(0, k, 0, k);\n\n // TODO: review of R2Y\n //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0];\n\n this.ssqYcal = sumOfSquaresY;\n this.E = X;\n this.F = Y;\n this.T = T;\n this.P = P;\n this.U = U;\n this.Q = Q;\n this.W = W;\n this.B = B;\n this.PBQ = P.mmul(B).mmul(Q.transpose());\n this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0];\n }\n\n /**\n * Predicts the behavior of the given dataset.\n * @param dataset - data to be predicted.\n * @returns {Matrix} - predictions of each element of the dataset.\n */\n predict(dataset) {\n var X = Matrix.checkMatrix(dataset);\n X = X.subRowVector(this.meanX).divRowVector(this.stdDevX);\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 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 };\n }\n\n /**\n * Load a PLS model from a JSON Object\n * @param 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 return new PLS(true, model);\n }\n}\n\nmodule.exports = PLS;\n\n/**\n * Retrieves the sum at the column of the given matrix.\n * @param matrix\n * @param column\n * @returns {number}\n */\nfunction getColSum(matrix, column) {\n var sum = 0;\n for (var i = 0; i < matrix.rows; i++) {\n sum += matrix[i][column];\n }\n return sum;\n}\n\n/**\n * Function that returns the index where the sum of each\n * column vector is maximum.\n * @param {Matrix} data\n * @returns {number} index of the maximum\n */\nfunction maxSumColIndex(data) {\n var maxIndex = 0;\n var maxSum = -Infinity;\n for(var i = 0; i < data.columns; ++i) {\n var currentSum = getColSum(data, i);\n if(currentSum > maxSum) {\n maxSum = currentSum;\n maxIndex = i;\n }\n }\n return maxIndex;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pls/src/pls.js\n// module id = 150\n// module chunks = 0","'use strict';\n\n/*\n * Function that calculate the linear fit in the form f(x) = Ce^(A * x) and\n * return the A and C coefficient of the given formula.\n *\n * @param {Vector} X - Vector of the x positions of the points.\n * @param {Vector} Y - Vector of the y positions of the points.\n * @return {Object} coefficients - The A and C coefficients.\n *\n * Created by acastillo on 5/12/16.\n */\n\nconst maybeToPrecision = require('./util').maybeToPrecision;\nconst SimpleLinearRegression = require('./simple-linear-regression');\nconst BaseRegression = require('./base-regression');\n\nclass ExpRegression extends BaseRegression {\n /**\n * @constructor\n * @param {Array} x - Independent variable\n * @param {Array} y - Dependent variable\n * @param {object} options\n */\n constructor(x, y, options) {\n super();\n let opt = options || {};\n if (x === true) { // reloading model\n this.A = y.A;\n this.C = y.C;\n if (y.quality) {\n this.quality = y.quality;\n }\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n var yl = new Array(n);\n for (var i = 0; i < n; i++) {\n yl[i] = Math.log(y[i]);\n }\n\n var linear = new SimpleLinearRegression(x, yl, {computeCoefficient: false});\n this.A = linear.slope;\n this.C = Math.exp(linear.intercept);\n if (opt.computeQuality) {\n this.quality = this.modelQuality(x, y);\n }\n }\n }\n\n _predict(newInputs) {\n return this.C * Math.exp(newInputs * this.A);\n }\n\n toJSON() {\n var out = {name: 'expRegression', A: this.A, C: this.C};\n if (this.quality) {\n out.quality = this.quality;\n }\n return out;\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.C, precision) + ' * exp(' + maybeToPrecision(this.A, precision) + ' * x)';\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.C, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.C, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}';\n }\n\n }\n\n static load(json) {\n if (json.name !== 'expRegression') {\n throw new TypeError('not a exp regression model');\n }\n return new ExpRegression(true, json);\n }\n}\n\n\nmodule.exports = ExpRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/exp-regression.js\n// module id = 151\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix');\nconst Kernel = require('ml-kernel');\n\nconst BaseRegression = require('./base-regression');\n\nconst defaultOptions = {\n lambda: 0.1,\n kernelType: 'gaussian',\n kernelOptions: {},\n computeCoefficient: false\n};\n\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nclass KernelRidgeRegression extends BaseRegression {\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.alpha = outputs.alpha;\n this.inputs = outputs.inputs;\n this.kernelType = outputs.kernelType;\n this.kernelOptions = outputs.kernelOptions;\n this.kernel = new Kernel(outputs.kernelType, outputs.kernelOptions);\n\n if (outputs.quality) {\n this.quality = outputs.quality;\n }\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n const kernelFunction = new Kernel(options.kernelType, options.kernelOptions);\n const K = kernelFunction.compute(inputs);\n const n = inputs.length;\n K.add(Matrix.eye(n, n).mul(options.lambda));\n\n this.alpha = K.solve(outputs);\n this.inputs = inputs;\n this.kernelType = options.kernelType;\n this.kernelOptions = options.kernelOptions;\n this.kernel = kernelFunction;\n\n if (options.computeQuality) {\n this.quality = this.modelQuality(inputs, outputs);\n }\n }\n }\n\n _predict(newInputs) {\n return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0];\n }\n\n toJSON() {\n var out = {\n name: 'kernelRidgeRegression',\n alpha: this.alpha,\n inputs: this.inputs,\n kernelType: this.kernelType,\n kernelOptions: this.kernelOptions\n };\n if (this.quality) {\n out.quality = this.quality;\n }\n return out;\n }\n\n static load(json) {\n if (json.name !== 'kernelRidgeRegression') {\n throw new TypeError('not a KRR model');\n }\n return new KernelRidgeRegression(true, json);\n }\n}\n\nmodule.exports = KernelRidgeRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/kernel-ridge-regression.js\n// module id = 152\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix');\nconst SVD = Matrix.DC.SingularValueDecomposition;\nconst BaseRegression = require('./base-regression');\n\nconst defaultOptions = {\n order: 2\n};\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nclass PolynomialFitRegression2D extends BaseRegression {\n /**\n * Constructor for the 2D polynomial fitting\n *\n * @param inputs\n * @param outputs\n * @param options\n * @constructor\n */\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.coefficients = Matrix.columnVector(outputs.coefficients);\n this.order = outputs.order;\n if (outputs.r) {\n this.r = outputs.r;\n this.r2 = outputs.r2;\n }\n if (outputs.chi2) {\n this.chi2 = outputs.chi2;\n }\n } else {\n options = Object.assign({}, defaultOptions, options);\n this.order = options.order;\n this.coefficients = [];\n this.X = inputs;\n this.y = outputs;\n\n this.train(this.X, this.y, options);\n\n if (options.computeQuality) {\n this.quality = this.modelQuality(inputs, outputs);\n }\n }\n }\n\n /**\n * Function that fits the model given the data(X) and predictions(y).\n * The third argument is an object with the following options:\n * * order: order of the polynomial to fit.\n *\n * @param {Matrix} X - A matrix with n rows and 2 columns.\n * @param {Matrix} y - A vector of the prediction values.\n */\n train(X, y) {\n if (!Matrix.isMatrix(X)) X = new Matrix(X);\n if (!Matrix.isMatrix(y)) y = Matrix.columnVector(y);\n\n //Perhaps y is transpose\n if (y.rows !== X.rows) {\n y = y.transpose();\n }\n\n if (X.columns !== 2) {\n throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2');\n }\n if (X.rows !== y.rows) {\n throw new RangeError('X and y must have the same rows');\n }\n\n var examples = X.rows;\n var coefficients = ((this.order + 2) * (this.order + 1)) / 2;\n this.coefficients = new Array(coefficients);\n\n var x1 = X.getColumnVector(0);\n var x2 = X.getColumnVector(1);\n\n var scaleX1 = 1.0 / x1.clone().apply(abs).max();\n var scaleX2 = 1.0 / x2.clone().apply(abs).max();\n var scaleY = 1.0 / y.clone().apply(abs).max();\n\n x1.mulColumn(0, scaleX1);\n x2.mulColumn(0, scaleX2);\n y.mulColumn(0, scaleY);\n\n var A = new Matrix(examples, coefficients);\n var col = 0;\n\n for (var i = 0; i <= this.order; ++i) {\n var limit = this.order - i;\n for (var j = 0; j <= limit; ++j) {\n var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j));\n A.setColumn(col, result);\n col++;\n }\n }\n\n var svd = new SVD(A.transpose(), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: true,\n autoTranspose: false\n });\n\n var qqs = Matrix.rowVector(svd.diagonal);\n qqs = qqs.apply(function (i, j) {\n if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j];\n else this[i][j] = 0;\n });\n\n var qqs1 = Matrix.zeros(examples, coefficients);\n for (i = 0; i < coefficients; ++i) {\n qqs1[i][i] = qqs[0][i];\n }\n\n qqs = qqs1;\n\n var U = svd.rightSingularVectors;\n var V = svd.leftSingularVectors;\n\n this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y);\n\n col = 0;\n\n for (i = 0; i <= coefficients; ++i) {\n limit = this.order - i;\n for (j = 0; j <= limit; ++j) {\n this.coefficients[col][0] = (this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j)) / scaleY;\n col++;\n }\n }\n }\n\n _predict(newInputs) {\n var x1 = newInputs[0];\n var x2 = newInputs[1];\n\n var y = 0;\n var column = 0;\n\n for (var i = 0; i <= this.order; i++) {\n for (var j = 0; j <= this.order - i; j++) {\n y += Math.pow(x1, i) * (Math.pow(x2, j)) * this.coefficients[column][0];\n column++;\n }\n }\n\n return y;\n }\n\n toJSON() {\n var out = {\n name: 'polyfit2D',\n order: this.order,\n coefficients: this.coefficients\n };\n if (this.quality) {\n out.quality = this.quality;\n }\n return out;\n }\n\n static load(json) {\n if (json.name !== 'polyfit2D') {\n throw new TypeError('not a polyfit2D model');\n }\n return new PolynomialFitRegression2D(true, json);\n }\n\n}\n\nmodule.exports = PolynomialFitRegression2D;\n\n\n/**\n * Function that given a column vector return this: vector^power\n *\n * @param x - Column vector.\n * @param power - Pow number.\n * @return {Suite|Matrix}\n */\nfunction powColVector(x, power) {\n var result = x.clone();\n for (var i = 0; i < x.rows; ++i) {\n result[i][0] = Math.pow(result[i][0], power);\n }\n return result;\n}\n\n/**\n * Function to use in the apply method to get the absolute value\n * of each element of the matrix\n *\n * @param i - current row.\n * @param j - current column.\n */\nfunction abs(i, j) {\n this[i][j] = Math.abs(this[i][j]);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/poly-fit-regression2d.js\n// module id = 153\n// module chunks = 0","'use strict';\n\n/*\n * Function that calculate the potential fit in the form f(x) = A*x^M\n * with a given M and return de A coefficient.\n *\n * @param {Vector} X - Vector of the x positions of the points.\n * @param {Vector} Y - Vector of the x positions of the points.\n * @param {Number, BigNumber} M - The exponent of the potential fit.\n * @return {Number|BigNumber} A - The A coefficient of the potential fit.\n * Created by acastillo on 5/12/16.\n */\n\nconst maybeToPrecision = require('./util').maybeToPrecision;\nconst PolynomialRegression = require('./polynomial-regression');\n// const PowerRegression = require('./power-regression');\nconst BaseRegression = require('./base-regression');\n\nclass PotentialRegression extends BaseRegression {\n /**\n * @constructor\n * @param x: Independent variable\n * @param y: Dependent variable\n * @param M\n * @param options\n */\n constructor(x, y, M, options) {\n super();\n let opt = options || {};\n if (x === true) { // reloading model\n this.A = y.A;\n this.M = y.M;\n if (y.quality) {\n this.quality = y.quality;\n }\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n\n var linear = new PolynomialRegression(x, y, [M], {computeCoefficient: true});\n this.A = linear.coefficients[0];\n this.M = M;\n if (opt.computeQuality) {\n this.quality = this.modelQuality(x, y);\n }\n }\n }\n\n _predict(x) {\n return this.A * Math.pow(x, this.M);\n }\n\n toJSON() {\n var out = {name: 'potentialRegression', A: this.A, M: this.M};\n if (this.quality) {\n out.quality = this.quality;\n }\n return out;\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + this.M;\n }\n\n toLaTeX(precision) {\n\n if (this.M >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + (-this.M) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'potentialRegression') {\n throw new TypeError('not a potential regression model');\n }\n return new PotentialRegression(true, json);\n }\n}\n\nmodule.exports = PotentialRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/potential-regression.js\n// module id = 154\n// module chunks = 0","'use strict';\n\n/**\n * This class implements the power regression f(x)=A*x^B\n * Created by acastillo on 5/12/16.\n */\n\nconst maybeToPrecision = require('./util').maybeToPrecision;\nconst SimpleLinearRegression = require('./simple-linear-regression');\nconst BaseRegression = require('./base-regression');\n\nclass PowerRegression extends BaseRegression {\n /**\n * @constructor\n * @param x: Independent variable\n * @param y: Dependent variable\n * @param options\n */\n constructor(x, y, options) {\n super();\n let opt = options || {};\n if (x === true) { // reloading model\n this.A = y.A;\n this.B = y.B;\n this.quality = y.quality || {};\n if (y.quality.r) {\n this.quality.r = y.quality.r;\n this.quality.r2 = y.quality.r2;\n }\n if (y.quality.chi2) {\n this.quality.chi2 = y.quality.chi2;\n }\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n var xl = new Array(n), yl = new Array(n);\n for (var i = 0; i < n; i++) {\n xl[i] = Math.log(x[i]);\n yl[i] = Math.log(y[i]);\n }\n\n var linear = new SimpleLinearRegression(xl, yl, {computeCoefficient: false});\n this.A = Math.exp(linear.intercept);\n this.B = linear.slope;\n if (opt.computeQuality) {\n this.quality = this.modelQuality(x, y);\n }\n }\n }\n\n _predict(newInputs) {\n return this.A * Math.pow(newInputs, this.B);\n }\n\n toJSON() {\n var out = {name: 'powerRegression', A: this.A, B: this.B};\n if (this.quality) {\n out.quality = this.quality;\n }\n return out;\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + maybeToPrecision(this.B, precision);\n }\n\n toLaTeX(precision) {\n if (this.B >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + maybeToPrecision(-this.B, precision) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'powerRegression') {\n throw new TypeError('not a power regression model');\n }\n return new PowerRegression(true, json);\n }\n}\n\nmodule.exports = PowerRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/power-regression.js\n// module id = 155\n// module chunks = 0","'use strict';\n\nconst BaseRegression = require('./base-regression');\nconst maybeToPrecision = require('./util').maybeToPrecision;\nconst median = require('ml-stat/array').median;\n\nclass TheilSenRegression extends BaseRegression {\n\n /**\n * Theil–Sen estimator\n * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n * @param {Array} x\n * @param {Array} y\n * @param {object} options\n * @constructor\n */\n constructor(x, y, options) {\n options = options || {};\n super();\n if (x === true) {\n // loads the model\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.quality = Object.assign({}, y.quality, this.quality);\n } else {\n // creates the model\n let len = x.length;\n if (len !== y.length) {\n throw new RangeError('Input and output array have a different length');\n }\n\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 this.slope = medianSlope;\n this.intercept = median(cuts);\n this.coefficients = [this.intercept, this.slope];\n if (options.computeQuality) {\n this.quality = this.modelQuality(x, y);\n }\n }\n\n }\n\n toJSON() {\n var out = {\n name: 'TheilSenRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n if (this.quality) {\n out.quality = this.quality;\n }\n\n return out;\n }\n\n _predict(input) {\n return this.slope * input + this.intercept;\n }\n\n computeX(input) {\n return (input - this.intercept) / this.slope;\n }\n\n toString(precision) {\n var result = 'f(x) = ';\n if (this.slope) {\n var xFactor = maybeToPrecision(this.slope, precision);\n result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n var absIntercept = Math.abs(this.intercept);\n var operator = absIntercept === this.intercept ? '+' : '-';\n result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision);\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'TheilSenRegression') {\n throw new TypeError('not a Theil-Sen model');\n }\n return new TheilSenRegression(true, json);\n }\n}\n\nmodule.exports = TheilSenRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/theil-sen-regression.js\n// module id = 156\n// module chunks = 0","'use strict';\n\nexports.array = require('./array');\nexports.matrix = require('./matrix');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-savitzky-golay-generalized/~/ml-stat/index.js\n// module id = 157\n// module chunks = 0","'use strict';\nvar arrayStat = require('./array');\n\n// https://github.com/accord-net/framework/blob/development/Sources/Accord.Statistics/Tools.cs\n\nfunction entropy(matrix, eps) {\n if (typeof(eps) === 'undefined') {\n eps = 0;\n }\n var sum = 0,\n l1 = matrix.length,\n l2 = matrix[0].length;\n for (var i = 0; i < l1; i++) {\n for (var j = 0; j < l2; j++) {\n sum += matrix[i][j] * Math.log(matrix[i][j] + eps);\n }\n }\n return -sum;\n}\n\nfunction mean(matrix, dimension) {\n if (typeof(dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theMean, N, i, j;\n\n if (dimension === -1) {\n theMean = [0];\n N = rows * cols;\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theMean[0] += matrix[i][j];\n }\n }\n theMean[0] /= N;\n } else if (dimension === 0) {\n theMean = new Array(cols);\n N = rows;\n for (j = 0; j < cols; j++) {\n theMean[j] = 0;\n for (i = 0; i < rows; i++) {\n theMean[j] += matrix[i][j];\n }\n theMean[j] /= N;\n }\n } else if (dimension === 1) {\n theMean = new Array(rows);\n N = cols;\n for (j = 0; j < rows; j++) {\n theMean[j] = 0;\n for (i = 0; i < cols; i++) {\n theMean[j] += matrix[j][i];\n }\n theMean[j] /= N;\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theMean;\n}\n\nfunction standardDeviation(matrix, means, unbiased) {\n var vari = variance(matrix, means, unbiased), l = vari.length;\n for (var i = 0; i < l; i++) {\n vari[i] = Math.sqrt(vari[i]);\n }\n return vari;\n}\n\nfunction variance(matrix, means, unbiased) {\n if (typeof(unbiased) === 'undefined') {\n unbiased = true;\n }\n means = means || mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum1 = 0, sum2 = 0, x = 0;\n for (var i = 0; i < rows; i++) {\n x = matrix[i][j] - means[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1);\n } else {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows;\n }\n }\n return vari;\n}\n\nfunction median(matrix) {\n var rows = matrix.length, cols = matrix[0].length;\n var medians = new Array(cols);\n\n for (var i = 0; i < cols; i++) {\n var data = new Array(rows);\n for (var j = 0; j < rows; j++) {\n data[j] = matrix[j][i];\n }\n data.sort();\n var N = data.length;\n if (N % 2 === 0) {\n medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5;\n } else {\n medians[i] = data[Math.floor(N / 2)];\n }\n }\n return medians;\n}\n\nfunction mode(matrix) {\n var rows = matrix.length,\n cols = matrix[0].length,\n modes = new Array(cols),\n i, j;\n for (i = 0; i < cols; i++) {\n var itemCount = new Array(rows);\n for (var k = 0; k < rows; k++) {\n itemCount[k] = 0;\n }\n var itemArray = new Array(rows);\n var count = 0;\n\n for (j = 0; j < rows; j++) {\n var index = itemArray.indexOf(matrix[j][i]);\n if (index >= 0) {\n itemCount[index]++;\n } else {\n itemArray[count] = matrix[j][i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (j = 0; j < count; j++) {\n if (itemCount[j] > maxValue) {\n maxValue = itemCount[j];\n maxIndex = j;\n }\n }\n\n modes[i] = itemArray[maxIndex];\n }\n return modes;\n}\n\nfunction skewness(matrix, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var means = mean(matrix);\n var n = matrix.length, l = means.length;\n var skew = new Array(l);\n\n for (var j = 0; j < l; j++) {\n var s2 = 0, s3 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n\n var m2 = s2 / n;\n var m3 = s3 / n;\n var g = m3 / Math.pow(m2, 3 / 2);\n\n if (unbiased) {\n var a = Math.sqrt(n * (n - 1));\n var b = n - 2;\n skew[j] = (a / b) * g;\n } else {\n skew[j] = g;\n }\n }\n return skew;\n}\n\nfunction kurtosis(matrix, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var means = mean(matrix);\n var n = matrix.length, m = matrix[0].length;\n var kurt = new Array(m);\n\n for (var j = 0; j < m; j++) {\n var s2 = 0, s4 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n kurt[j] = a * b - 3 * c;\n } else {\n kurt[j] = m4 / (m2 * m2) - 3;\n }\n }\n return kurt;\n}\n\nfunction standardError(matrix) {\n var samples = matrix.length;\n var standardDeviations = standardDeviation(matrix), l = standardDeviations.length;\n var standardErrors = new Array(l);\n var sqrtN = Math.sqrt(samples);\n\n for (var i = 0; i < l; i++) {\n standardErrors[i] = standardDeviations[i] / sqrtN;\n }\n return standardErrors;\n}\n\nfunction covariance(matrix, dimension) {\n return scatter(matrix, undefined, dimension);\n}\n\nfunction scatter(matrix, divisor, dimension) {\n if (typeof(dimension) === 'undefined') {\n dimension = 0;\n }\n if (typeof(divisor) === 'undefined') {\n if (dimension === 0) {\n divisor = matrix.length - 1;\n } else if (dimension === 1) {\n divisor = matrix[0].length - 1;\n }\n }\n var means = mean(matrix, dimension),\n rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, s, k;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n}\n\nfunction correlation(matrix) {\n var means = mean(matrix),\n standardDeviations = standardDeviation(matrix, true, means),\n scores = zScores(matrix, means, standardDeviations),\n rows = matrix.length,\n cols = matrix[0].length,\n i, j;\n\n var cor = new Array(cols);\n for (i = 0; i < cols; i++) {\n cor[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n var c = 0;\n for (var k = 0, l = scores.length; k < l; k++) {\n c += scores[k][j] * scores[k][i];\n }\n c /= rows - 1;\n cor[i][j] = c;\n cor[j][i] = c;\n }\n }\n return cor;\n}\n\nfunction zScores(matrix, means, standardDeviations) {\n means = means || mean(matrix);\n if (typeof(standardDeviations) === 'undefined') standardDeviations = standardDeviation(matrix, true, means);\n return standardize(center(matrix, means, false), standardDeviations, true);\n}\n\nfunction center(matrix, means, inPlace) {\n means = means || mean(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var row = result[i];\n for (j = 0, jj = row.length; j < jj; j++) {\n row[j] = matrix[i][j] - means[j];\n }\n }\n return result;\n}\n\nfunction standardize(matrix, standardDeviations, inPlace) {\n if (typeof(standardDeviations) === 'undefined') standardDeviations = standardDeviation(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var resultRow = result[i];\n var sourceRow = matrix[i];\n for (j = 0, jj = resultRow.length; j < jj; j++) {\n if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {\n resultRow[j] = sourceRow[j] / standardDeviations[j];\n }\n }\n }\n return result;\n}\n\nfunction weightedVariance(matrix, weights) {\n var means = mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum = 0;\n var a = 0, b = 0;\n\n for (var i = 0; i < rows; i++) {\n var z = matrix[i][j] - means[j];\n var w = weights[i];\n\n sum += w * (z * z);\n b += w;\n a += w * w;\n }\n\n vari[j] = sum * (b / (b * b - a));\n }\n\n return vari;\n}\n\nfunction weightedMean(matrix, weights, dimension) {\n if (typeof(dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length,\n means, i, ii, j, w, row;\n\n if (dimension === 0) {\n means = new Array(cols);\n for (i = 0; i < cols; i++) {\n means[i] = 0;\n }\n for (i = 0; i < rows; i++) {\n row = matrix[i];\n w = weights[i];\n for (j = 0; j < cols; j++) {\n means[j] += row[j] * w;\n }\n }\n } else if (dimension === 1) {\n means = new Array(rows);\n for (i = 0; i < rows; i++) {\n means[i] = 0;\n }\n for (j = 0; j < rows; j++) {\n row = matrix[j];\n w = weights[j];\n for (i = 0; i < cols; i++) {\n means[j] += row[i] * w;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n var weightSum = arrayStat.sum(weights);\n if (weightSum !== 0) {\n for (i = 0, ii = means.length; i < ii; i++) {\n means[i] /= weightSum;\n }\n }\n return means;\n}\n\nfunction weightedCovariance(matrix, weights, means, dimension) {\n dimension = dimension || 0;\n means = means || weightedMean(matrix, weights, dimension);\n var s1 = 0, s2 = 0;\n for (var i = 0, ii = weights.length; i < ii; i++) {\n s1 += weights[i];\n s2 += weights[i] * weights[i];\n }\n var factor = s1 / (s1 * s1 - s2);\n return weightedScatter(matrix, weights, means, factor, dimension);\n}\n\nfunction weightedScatter(matrix, weights, means, factor, dimension) {\n dimension = dimension || 0;\n means = means || weightedMean(matrix, weights, dimension);\n if (typeof(factor) === 'undefined') {\n factor = 1;\n }\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, k, s;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n}\n\nmodule.exports = {\n entropy: entropy,\n mean: mean,\n standardDeviation: standardDeviation,\n variance: variance,\n median: median,\n mode: mode,\n skewness: skewness,\n kurtosis: kurtosis,\n standardError: standardError,\n covariance: covariance,\n scatter: scatter,\n correlation: correlation,\n zScores: zScores,\n center: center,\n standardize: standardize,\n weightedVariance: weightedVariance,\n weightedMean: weightedMean,\n weightedCovariance: weightedCovariance,\n weightedScatter: weightedScatter\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-savitzky-golay-generalized/~/ml-stat/matrix.js\n// module id = 158\n// module chunks = 0","var NodeSquare = require('./node-square');\n\nfunction NodeHexagonal(x, y, weights, som) {\n\n NodeSquare.call(this, x, y, weights, som);\n\n this.hX = x - Math.floor(y / 2);\n this.z = 0 - this.hX - y;\n\n}\n\nNodeHexagonal.prototype = new NodeSquare;\nNodeHexagonal.prototype.constructor = NodeHexagonal;\n\nNodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) {\n return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z));\n};\n\nNodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.hX - otherNode.hX),\n distY = Math.abs(this.y - otherNode.y),\n distZ = Math.abs(this.z - otherNode.z);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ));\n};\n\nNodeHexagonal.prototype.getPosition = function getPosition() {\n throw new Error('Unimplemented : cannot get position of the points for hexagonal grid');\n};\n\nmodule.exports = NodeHexagonal;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-som/src/node-hexagonal.js\n// module id = 159\n// module chunks = 0","'use strict';\n\nvar arrayStat = require('./array');\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nexports.max = function max(matrix) {\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return max;\n};\n\nexports.min = function min(matrix) {\n var min = Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n }\n }\n return min;\n};\n\nexports.minMax = function minMax(matrix) {\n var min = Infinity;\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return {\n min:min,\n max:max\n };\n};\n\nexports.entropy = function entropy(matrix, eps) {\n if (typeof (eps) === 'undefined') {\n eps = 0;\n }\n var sum = 0,\n l1 = matrix.length,\n l2 = matrix[0].length;\n for (var i = 0; i < l1; i++) {\n for (var j = 0; j < l2; j++) {\n sum += matrix[i][j] * Math.log(matrix[i][j] + eps);\n }\n }\n return -sum;\n};\n\nexports.mean = function mean(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theMean, N, i, j;\n\n if (dimension === -1) {\n theMean = [0];\n N = rows * cols;\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theMean[0] += matrix[i][j];\n }\n }\n theMean[0] /= N;\n } else if (dimension === 0) {\n theMean = new Array(cols);\n N = rows;\n for (j = 0; j < cols; j++) {\n theMean[j] = 0;\n for (i = 0; i < rows; i++) {\n theMean[j] += matrix[i][j];\n }\n theMean[j] /= N;\n }\n } else if (dimension === 1) {\n theMean = new Array(rows);\n N = cols;\n for (j = 0; j < rows; j++) {\n theMean[j] = 0;\n for (i = 0; i < cols; i++) {\n theMean[j] += matrix[j][i];\n }\n theMean[j] /= N;\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theMean;\n};\n\nexports.sum = function sum(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theSum, i, j;\n\n if (dimension === -1) {\n theSum = [0];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theSum[0] += matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theSum = new Array(cols);\n for (j = 0; j < cols; j++) {\n theSum[j] = 0;\n for (i = 0; i < rows; i++) {\n theSum[j] += matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theSum = new Array(rows);\n for (j = 0; j < rows; j++) {\n theSum[j] = 0;\n for (i = 0; i < cols; i++) {\n theSum[j] += matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theSum;\n};\n\nexports.product = function product(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theProduct, i, j;\n\n if (dimension === -1) {\n theProduct = [1];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theProduct[0] *= matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theProduct = new Array(cols);\n for (j = 0; j < cols; j++) {\n theProduct[j] = 1;\n for (i = 0; i < rows; i++) {\n theProduct[j] *= matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theProduct = new Array(rows);\n for (j = 0; j < rows; j++) {\n theProduct[j] = 1;\n for (i = 0; i < cols; i++) {\n theProduct[j] *= matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theProduct;\n};\n\nexports.standardDeviation = function standardDeviation(matrix, means, unbiased) {\n var vari = exports.variance(matrix, means, unbiased), l = vari.length;\n for (var i = 0; i < l; i++) {\n vari[i] = Math.sqrt(vari[i]);\n }\n return vari;\n};\n\nexports.variance = function variance(matrix, means, unbiased) {\n if (typeof (unbiased) === 'undefined') {\n unbiased = true;\n }\n means = means || exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum1 = 0, sum2 = 0, x = 0;\n for (var i = 0; i < rows; i++) {\n x = matrix[i][j] - means[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1);\n } else {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows;\n }\n }\n return vari;\n};\n\nexports.median = function median(matrix) {\n var rows = matrix.length, cols = matrix[0].length;\n var medians = new Array(cols);\n\n for (var i = 0; i < cols; i++) {\n var data = new Array(rows);\n for (var j = 0; j < rows; j++) {\n data[j] = matrix[j][i];\n }\n data.sort(compareNumbers);\n var N = data.length;\n if (N % 2 === 0) {\n medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5;\n } else {\n medians[i] = data[Math.floor(N / 2)];\n }\n }\n return medians;\n};\n\nexports.mode = function mode(matrix) {\n var rows = matrix.length,\n cols = matrix[0].length,\n modes = new Array(cols),\n i, j;\n for (i = 0; i < cols; i++) {\n var itemCount = new Array(rows);\n for (var k = 0; k < rows; k++) {\n itemCount[k] = 0;\n }\n var itemArray = new Array(rows);\n var count = 0;\n\n for (j = 0; j < rows; j++) {\n var index = itemArray.indexOf(matrix[j][i]);\n if (index >= 0) {\n itemCount[index]++;\n } else {\n itemArray[count] = matrix[j][i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (j = 0; j < count; j++) {\n if (itemCount[j] > maxValue) {\n maxValue = itemCount[j];\n maxIndex = j;\n }\n }\n\n modes[i] = itemArray[maxIndex];\n }\n return modes;\n};\n\nexports.skewness = function skewness(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, l = means.length;\n var skew = new Array(l);\n\n for (var j = 0; j < l; j++) {\n var s2 = 0, s3 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n\n var m2 = s2 / n;\n var m3 = s3 / n;\n var g = m3 / Math.pow(m2, 3 / 2);\n\n if (unbiased) {\n var a = Math.sqrt(n * (n - 1));\n var b = n - 2;\n skew[j] = (a / b) * g;\n } else {\n skew[j] = g;\n }\n }\n return skew;\n};\n\nexports.kurtosis = function kurtosis(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, m = matrix[0].length;\n var kurt = new Array(m);\n\n for (var j = 0; j < m; j++) {\n var s2 = 0, s4 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n kurt[j] = a * b - 3 * c;\n } else {\n kurt[j] = m4 / (m2 * m2) - 3;\n }\n }\n return kurt;\n};\n\nexports.standardError = function standardError(matrix) {\n var samples = matrix.length;\n var standardDeviations = exports.standardDeviation(matrix);\n var l = standardDeviations.length;\n var standardErrors = new Array(l);\n var sqrtN = Math.sqrt(samples);\n\n for (var i = 0; i < l; i++) {\n standardErrors[i] = standardDeviations[i] / sqrtN;\n }\n return standardErrors;\n};\n\nexports.covariance = function covariance(matrix, dimension) {\n return exports.scatter(matrix, undefined, dimension);\n};\n\nexports.scatter = function scatter(matrix, divisor, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n if (typeof (divisor) === 'undefined') {\n if (dimension === 0) {\n divisor = matrix.length - 1;\n } else if (dimension === 1) {\n divisor = matrix[0].length - 1;\n }\n }\n var means = exports.mean(matrix, dimension);\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, s, k;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\nexports.correlation = function correlation(matrix) {\n var means = exports.mean(matrix),\n standardDeviations = exports.standardDeviation(matrix, true, means),\n scores = exports.zScores(matrix, means, standardDeviations),\n rows = matrix.length,\n cols = matrix[0].length,\n i, j;\n\n var cor = new Array(cols);\n for (i = 0; i < cols; i++) {\n cor[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n var c = 0;\n for (var k = 0, l = scores.length; k < l; k++) {\n c += scores[k][j] * scores[k][i];\n }\n c /= rows - 1;\n cor[i][j] = c;\n cor[j][i] = c;\n }\n }\n return cor;\n};\n\nexports.zScores = function zScores(matrix, means, standardDeviations) {\n means = means || exports.mean(matrix);\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means);\n return exports.standardize(exports.center(matrix, means, false), standardDeviations, true);\n};\n\nexports.center = function center(matrix, means, inPlace) {\n means = means || exports.mean(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var row = result[i];\n for (j = 0, jj = row.length; j < jj; j++) {\n row[j] = matrix[i][j] - means[j];\n }\n }\n return result;\n};\n\nexports.standardize = function standardize(matrix, standardDeviations, inPlace) {\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var resultRow = result[i];\n var sourceRow = matrix[i];\n for (j = 0, jj = resultRow.length; j < jj; j++) {\n if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {\n resultRow[j] = sourceRow[j] / standardDeviations[j];\n }\n }\n }\n return result;\n};\n\nexports.weightedVariance = function weightedVariance(matrix, weights) {\n var means = exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum = 0;\n var a = 0, b = 0;\n\n for (var i = 0; i < rows; i++) {\n var z = matrix[i][j] - means[j];\n var w = weights[i];\n\n sum += w * (z * z);\n b += w;\n a += w * w;\n }\n\n vari[j] = sum * (b / (b * b - a));\n }\n\n return vari;\n};\n\nexports.weightedMean = function weightedMean(matrix, weights, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length,\n means, i, ii, j, w, row;\n\n if (dimension === 0) {\n means = new Array(cols);\n for (i = 0; i < cols; i++) {\n means[i] = 0;\n }\n for (i = 0; i < rows; i++) {\n row = matrix[i];\n w = weights[i];\n for (j = 0; j < cols; j++) {\n means[j] += row[j] * w;\n }\n }\n } else if (dimension === 1) {\n means = new Array(rows);\n for (i = 0; i < rows; i++) {\n means[i] = 0;\n }\n for (j = 0; j < rows; j++) {\n row = matrix[j];\n w = weights[j];\n for (i = 0; i < cols; i++) {\n means[j] += row[i] * w;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n var weightSum = arrayStat.sum(weights);\n if (weightSum !== 0) {\n for (i = 0, ii = means.length; i < ii; i++) {\n means[i] /= weightSum;\n }\n }\n return means;\n};\n\nexports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n var s1 = 0, s2 = 0;\n for (var i = 0, ii = weights.length; i < ii; i++) {\n s1 += weights[i];\n s2 += weights[i] * weights[i];\n }\n var factor = s1 / (s1 * s1 - s2);\n return exports.weightedScatter(matrix, weights, means, factor, dimension);\n};\n\nexports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n if (typeof (factor) === 'undefined') {\n factor = 1;\n }\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, k, s;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-stat/matrix.js\n// module id = 160\n// module chunks = 0","\"use strict\";\n\n/**\n * Function that creates the tree\n * @param {Array } X - chemical shifts of the signal\n * @param {Array } Y - intensity of the signal\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {number} minWindow - smallest range to accept in x\n * @param {number} threshold - smallest range to accept in y\n * @returns {{sum: number, center: number, left: {json}, right: {json}}}\n * left and right have the same structure than the parent, or have a\n * undefined value if are leafs\n */\nfunction createTree (X, Y, from, to, minWindow, threshold) {\n minWindow = minWindow || 0.16;\n threshold = threshold || 0.01;\n if ((to - from) < minWindow)\n return undefined;\n var sum = 0;\n for (var i = 0; X[i] < to; i++) {\n if (X[i] > from)\n sum += Y[i];\n }\n if (sum < threshold) {\n return undefined;\n }\n var center = 0;\n for (var j = 0; X[j] < to; j++) {\n if (X[i] > from)\n center += X[j] * Y[j];\n }\n center = center / sum;\n if (((center - from) < 10e-6) || ((to - center) < 10e-6)) return undefined;\n if ((center - from) < (minWindow /4)) {\n return createTree(X, Y, center, to, minWindow, threshold);\n }\n else {\n if ((to - center) < (minWindow / 4)) {\n return createTree(X, Y, from, center, minWindow, threshold);\n }\n else {\n return {\n 'sum': sum,\n 'center': center,\n 'left': createTree(X, Y, from, center, minWindow, threshold),\n 'right': createTree(X, Y, center, to, minWindow, threshold)\n };\n }\n }\n}\n\n/**\n * Similarity between two nodes\n * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node\n * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node\n * @param {number} alpha - weights the relative importance of intensity vs. shift match\n * @param {number} beta - weights the relative importance of node matching and children matching\n * @param {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @returns {number} similarity measure between tree nodes\n */\nfunction S(a, b, alpha, beta, gamma) {\n if (a === undefined || b === undefined) {\n return 0;\n }\n else {\n var C = (alpha*Math.min(a.sum, b.sum)/Math.max(a.sum, b.sum)+ (1-alpha)*Math.exp(-gamma*Math.abs(a.center - b.center)));\n }\n return beta*C + (1-beta)*(S(a.left, b.left, alpha, beta, gamma)+S(a.right, b.right, alpha, beta, gamma));\n}\n\n/**\n * @type {number} alpha - weights the relative importance of intensity vs. shift match\n * @type {number} beta - weights the relative importance of node matching and children matching\n * @type {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @type {number} minWindow - smallest range to accept in x\n * @type {number} threshold - smallest range to accept in y\n */\nvar defaultOptions = {\n minWindow: 0.16,\n threshold : 0.01,\n alpha: 0.1,\n beta: 0.33,\n gamma: 0.001\n};\n\n/**\n * Builds a tree based in the spectra and compares this trees\n * @param {{x: Array, y: Array}} A - first spectra to be compared\n * @param {{x: Array, y: Array}} B - second spectra to be compared\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options\n * @returns {number} similarity measure between the spectra\n */\nfunction tree(A, B, from, to, options) {\n options = options || {};\n for (var o in defaultOptions)\n if (!options.hasOwnProperty(o)) {\n options[o] = defaultOptions[o];\n }\n var Atree, Btree;\n if (A.sum)\n Atree = A;\n else\n Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold);\n if (B.sum)\n Btree = B;\n else\n Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold);\n return S(Atree, Btree, options.alpha, options.beta, options.gamma);\n}\n\nmodule.exports = {\n calc: tree,\n createTree: createTree\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-tree-similarity/src/index.js\n// module id = 161\n// module chunks = 0","module.exports = newArray\n\nfunction newArray (n, value) {\n n = n || 0\n var array = new Array(n)\n for (var i = 0; i < n; i++) {\n array[i] = value\n }\n return array\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/new-array/index.js\n// module id = 162\n// module chunks = 0","'use strict';\nmodule.exports = Number.isNaN || function (x) {\n\treturn x !== x;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/number-is-nan/index.js\n// module id = 163\n// module chunks = 0","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/process/browser.js\n// module id = 164\n// module chunks = 0","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/util/~/inherits/inherits_browser.js\n// module id = 165\n// module chunks = 0","module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/util/support/isBufferBrowser.js\n// module id = 166\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n // Allow for deprecating things in the process of starting up.\n if (isUndefined(global.process)) {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n if (process.noDeprecation === true) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexports.debuglog = function(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/util/util.js\n// module id = 167\n// module chunks = 0","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/global.js\n// module id = 168\n// module chunks = 0","'use strict';\n\n// Root packages\nexports.ArrayUtils = exports.AU = require('ml-array-utils');\nexports.BitArray = require('ml-bit-array');\nexports.HashTable = require('ml-hash-table');\nexports.Matrix = require('ml-matrix');\nexports.PadArray = require('ml-pad-array');\nexports.Regression = require('ml-regression');\nexports.binarySearch = require('binary-search');\nexports.numSort = require('num-sort');\n\n\n// Math packages\nvar Math = exports.Math = {};\n\nvar distance = require('ml-distance');\nMath.Distance = distance.distance;\nMath.Similarity = distance.similarity;\nMath.DistanceMatrix = require('ml-distance-matrix');\nMath.SG = require('ml-savitzky-golay');\nMath.SGG = require('ml-savitzky-golay-generalized');\nMath.Matrix = exports.Matrix;\nMath.SparseMatrix = require('ml-sparse-matrix');\nMath.BellOptimizer = require('ml-optimize-lorentzian');\nMath.CurveFitting = require('ml-curve-fitting');\nMath.Kernel = require('ml-kernel');\n\n\n// Statistics packages\nvar Stat = exports.Stat = {};\n\nStat.array = require('ml-stat').array;\nStat.matrix = require('ml-stat').matrix;\nStat.PCA = require('ml-pca');\nStat.Performance = require('ml-performance');\n\n\n// Random number generation\nvar RNG = exports.RNG = {};\nRNG.XSadd = require('ml-xsadd');\n\n\n// Supervised learning\nvar SL = exports.SL = {};\n\nSL.CV = require('ml-cross-validation');\nSL.CrossValidation = SL.CV; // Alias\nSL.SVM = require('ml-svm');\nSL.KNN = require('ml-knn');\nSL.NaiveBayes = require('ml-naivebayes');\nSL.PLS = require('ml-pls');\n\n\n// Clustering\nvar Clust = exports.Clust = {};\n\nClust.kmeans = require('ml-kmeans');\nClust.hclust = require('ml-hclust');\n\n\n// Neural networks\nvar NN = exports.NN = exports.nn = {};\n\nNN.SOM = require('ml-som');\nNN.FNN = require('ml-fnn');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/index.js\n// module id = 169\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///ml/webpack/universalModuleDefinition","webpack:///ml/./~/ml-performance/src/index.js","webpack:///ml/./~/ml-kmeans/src/kmeans.js","webpack:///ml/./~/ml-fnn/src/activationFunctions.js","webpack:///ml/./~/ml-curve-fitting/src/algebra.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/abstractMatrix.js","webpack:///ml/webpack/bootstrap bdc072b449082cbd48ad","webpack:///ml/./~/ml-matrix/src/index.js","webpack:///ml/./~/ml-distance-euclidean/euclidean.js","webpack:///ml/./~/ml-stat/index.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/matrix.js","webpack:///ml/./~/ml-matrix/src/matrix.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/matrix.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/matrix.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/matrix.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/views/base.js","webpack:///ml/./~/ml-matrix/src/views/base.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/views/base.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/base.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/views/base.js","webpack:///ml/./~/ml-array-utils/src/index.js","webpack:///ml/./~/ml-regression-base/src/index.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/util.js","webpack:///ml/./~/ml-matrix/src/util.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/util.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/util.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/util.js","webpack:///ml/./~/ml-kernel/src/kernel.js","webpack:///ml/./~/extend/index.js","webpack:///ml/./~/ml-hclust/src/Cluster.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/dc/lu.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/dc/util.js","webpack:///ml/./~/ml-matrix/src/dc/util.js","webpack:///ml/./~/ml-pls/src/utils.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/abstractMatrix.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/dc/lu.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/dc/util.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/abstractMatrix.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/lu.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/util.js","webpack:///ml/./~/ml-regression-simple-linear/src/index.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/abstractMatrix.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/dc/lu.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/dc/util.js","webpack:///ml/./~/ml-regression/src/regression/base-regression.js","webpack:///ml/./~/binary-search/index.js","webpack:///ml/./~/ml-distance-matrix/src/index.js","webpack:///ml/./~/ml-distance/src/index.js","webpack:///ml/./~/ml-hash-table/src/HashTable.js","webpack:///ml/./~/ml-pad-array/src/index.js","webpack:///ml/./~/num-sort/index.js","webpack:///ml/./~/ml-distance/src/distances/dice.js","webpack:///ml/./~/ml-distance/src/distances/intersection.js","webpack:///ml/./~/ml-distance/src/distances/jaccard.js","webpack:///ml/./~/ml-distance/src/distances/kulczynski.js","webpack:///ml/./~/ml-distance/src/distances/motyka.js","webpack:///ml/./~/ml-distance/src/distances/squaredChord.js","webpack:///ml/./~/ml-distance/src/similarities/cosine.js","webpack:///ml/./~/ml-distance/src/similarities/czekanowski.js","webpack:///ml/./~/ml-distance/src/similarities/tanimoto.js","webpack:///ml/./~/ml-fnn/src/Layer.js","webpack:///ml/./~/ml-fnn/src/utils.js","webpack:///ml/./~/ml-hclust/src/ClusterLeaf.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/dc/qr.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/dc/svd.js","webpack:///ml/./~/ml-kmeans/src/utils.js","webpack:///ml/./~/ml-matrix/src/abstractMatrix.js","webpack:///ml/./~/ml-matrix/src/dc/lu.js","webpack:///ml/./~/ml-matrix/src/dc/svd.js","webpack:///ml/./~/ml-naivebayes/src/naiveBayes.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/dc/qr.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/dc/svd.js","webpack:///ml/./~/ml-regression-polynomial/src/index.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/qr.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/svd.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/dc/qr.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/dc/svd.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/index.js","webpack:///ml/./~/ml-savitzky-golay-generalized/~/ml-stat/array.js","webpack:///ml/./~/ml-som/src/node-square.js","webpack:///ml/./~/ml-stat/array.js","webpack:///ml/./~/ml-bit-array/src/index.js","webpack:///ml/./~/ml-cross-validation/src/crossValidation.js","webpack:///ml/./~/ml-fnn/src/FeedForwardNeuralNetwork.js","webpack:///ml/./~/ml-hclust/src/index.js","webpack:///ml/./~/ml-knn/src/index.js","webpack:///ml/./~/ml-levenberg-marquardt/src/index.js","webpack:///ml/./~/ml-naivebayes/src/index.js","webpack:///ml/./~/ml-optimize-lorentzian/src/index.js","webpack:///ml/./~/ml-pca/src/pca.js","webpack:///ml/./~/ml-pls/src/index.js","webpack:///ml/./~/ml-regression/src/index.js","webpack:///ml/./~/ml-savitzky-golay-generalized/src/index.js","webpack:///ml/./~/ml-savitzky-golay/src/index.js","webpack:///ml/./~/ml-som/src/index.js","webpack:///ml/./~/ml-sparse-matrix/src/SparseMatrix.js","webpack:///ml/./~/ml-svm/src/svm.js","webpack:///ml/./~/ml-xsadd/xsadd-es5.js","webpack:///ml/./~/RandomSelection/lib/Picker.js","webpack:///ml/./src/index.js","webpack:///ml/./~/heap/index.js","webpack:///ml/./~/heap/lib/heap.js","webpack:///ml/./~/ml-array-utils/src/ArrayUtils.js","webpack:///ml/./~/ml-array-utils/src/getEquallySpaced.js","webpack:///ml/./~/ml-array-utils/src/snv.js","webpack:///ml/./~/ml-bit-array/src/creator.js","webpack:///ml/./~/ml-combinations/src/index.js","webpack:///ml/./~/ml-cross-validation/src/ConfusionMatrix.js","webpack:///ml/./~/ml-curve-fitting/src/LM.js","webpack:///ml/./~/ml-curve-fitting/src/index.js","webpack:///ml/./~/ml-distance/src/distances.js","webpack:///ml/./~/ml-distance/src/distances/additiveSymmetric.js","webpack:///ml/./~/ml-distance/src/distances/avg.js","webpack:///ml/./~/ml-distance/src/distances/bhattacharyya.js","webpack:///ml/./~/ml-distance/src/distances/canberra.js","webpack:///ml/./~/ml-distance/src/distances/chebyshev.js","webpack:///ml/./~/ml-distance/src/distances/clark.js","webpack:///ml/./~/ml-distance/src/distances/czekanowski.js","webpack:///ml/./~/ml-distance/src/distances/divergence.js","webpack:///ml/./~/ml-distance/src/distances/fidelity.js","webpack:///ml/./~/ml-distance/src/distances/gower.js","webpack:///ml/./~/ml-distance/src/distances/harmonicMean.js","webpack:///ml/./~/ml-distance/src/distances/hellinger.js","webpack:///ml/./~/ml-distance/src/distances/innerProduct.js","webpack:///ml/./~/ml-distance/src/distances/jeffreys.js","webpack:///ml/./~/ml-distance/src/distances/jensenDifference.js","webpack:///ml/./~/ml-distance/src/distances/jensenShannon.js","webpack:///ml/./~/ml-distance/src/distances/kdivergence.js","webpack:///ml/./~/ml-distance/src/distances/kullbackLeibler.js","webpack:///ml/./~/ml-distance/src/distances/kumarHassebrook.js","webpack:///ml/./~/ml-distance/src/distances/kumarJohnson.js","webpack:///ml/./~/ml-distance/src/distances/lorentzian.js","webpack:///ml/./~/ml-distance/src/distances/manhattan.js","webpack:///ml/./~/ml-distance/src/distances/matusita.js","webpack:///ml/./~/ml-distance/src/distances/minkowski.js","webpack:///ml/./~/ml-distance/src/distances/neyman.js","webpack:///ml/./~/ml-distance/src/distances/pearson.js","webpack:///ml/./~/ml-distance/src/distances/probabilisticSymmetric.js","webpack:///ml/./~/ml-distance/src/distances/ruzicka.js","webpack:///ml/./~/ml-distance/src/distances/soergel.js","webpack:///ml/./~/ml-distance/src/distances/sorensen.js","webpack:///ml/./~/ml-distance/src/distances/squared.js","webpack:///ml/./~/ml-distance/src/distances/taneja.js","webpack:///ml/./~/ml-distance/src/distances/tanimoto.js","webpack:///ml/./~/ml-distance/src/distances/topsoe.js","webpack:///ml/./~/ml-distance/src/distances/waveHedges.js","webpack:///ml/./~/ml-distance/src/similarities.js","webpack:///ml/./~/ml-distance/src/similarities/dice.js","webpack:///ml/./~/ml-distance/src/similarities/intersection.js","webpack:///ml/./~/ml-distance/src/similarities/jaccard.js","webpack:///ml/./~/ml-distance/src/similarities/kulczynski.js","webpack:///ml/./~/ml-distance/src/similarities/motyka.js","webpack:///ml/./~/ml-distance/src/similarities/pearson.js","webpack:///ml/./~/ml-distance/src/similarities/squaredChord.js","webpack:///ml/./~/ml-fnn/src/OutputLayer.js","webpack:///ml/./~/ml-hash-table/src/primeFinder.js","webpack:///ml/./~/ml-hclust/src/agnes.js","webpack:///ml/./~/ml-hclust/src/diana.js","webpack:///ml/./~/ml-kernel-gaussian/gaussian-kernel.js","webpack:///ml/./~/ml-kernel-polynomial/polynomial-kernel.js","webpack:///ml/./~/ml-kernel-sigmoid/sigmoid-kernel.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/dc/cholesky.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/dc/evd.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/decompositions.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/index.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/symbol-species.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/views/column.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/views/flipColumn.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/views/flipRow.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/views/row.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/views/selection.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/views/sub.js","webpack:///ml/./~/ml-kernel/~/ml-matrix/src/views/transpose.js","webpack:///ml/./~/ml-kernel/src/kernels/anova-kernel.js","webpack:///ml/./~/ml-kernel/src/kernels/cauchy-kernel.js","webpack:///ml/./~/ml-kernel/src/kernels/exponential-kernel.js","webpack:///ml/./~/ml-kernel/src/kernels/histogram-intersection-kernel.js","webpack:///ml/./~/ml-kernel/src/kernels/laplacian-kernel.js","webpack:///ml/./~/ml-kernel/src/kernels/multiquadratic-kernel.js","webpack:///ml/./~/ml-kernel/src/kernels/rational-quadratic-kernel.js","webpack:///ml/./~/ml-kmeans/src/KMeansResult.js","webpack:///ml/./~/ml-kmeans/src/initialization.js","webpack:///ml/./~/ml-knn/src/kdtree.js","webpack:///ml/./~/ml-knn/src/knn.js","webpack:///ml/./~/ml-levenberg-marquardt/src/errorCalculation.js","webpack:///ml/./~/ml-levenberg-marquardt/src/step.js","webpack:///ml/./~/ml-matrix/src/dc/cholesky.js","webpack:///ml/./~/ml-matrix/src/dc/evd.js","webpack:///ml/./~/ml-matrix/src/dc/qr.js","webpack:///ml/./~/ml-matrix/src/decompositions.js","webpack:///ml/./~/ml-matrix/src/symbol-species.js","webpack:///ml/./~/ml-matrix/src/views/column.js","webpack:///ml/./~/ml-matrix/src/views/flipColumn.js","webpack:///ml/./~/ml-matrix/src/views/flipRow.js","webpack:///ml/./~/ml-matrix/src/views/row.js","webpack:///ml/./~/ml-matrix/src/views/selection.js","webpack:///ml/./~/ml-matrix/src/views/sub.js","webpack:///ml/./~/ml-matrix/src/views/transpose.js","webpack:///ml/./~/ml-nearest-vector/src/index.js","webpack:///ml/./~/ml-performance/src/measures.js","webpack:///ml/./~/ml-pls/src/opls.js","webpack:///ml/./~/ml-pls/src/pls.js","webpack:///ml/./~/ml-regression-base/src/checkArrayLength.js","webpack:///ml/./~/ml-regression-base/src/maybeToPrecision.js","webpack:///ml/./~/ml-regression-exponential/src/index.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/dc/cholesky.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/dc/evd.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/decompositions.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/index.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/symbol-species.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/views/column.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/views/flipColumn.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/views/flipRow.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/views/row.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/views/selection.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/views/sub.js","webpack:///ml/./~/ml-regression-polynomial/~/ml-matrix/src/views/transpose.js","webpack:///ml/./~/ml-regression-power/src/index.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/cholesky.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/evd.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/decompositions.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/index.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/symbol-species.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/column.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/flipColumn.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/flipRow.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/row.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/selection.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/sub.js","webpack:///ml/./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/transpose.js","webpack:///ml/./~/ml-regression-robust-polynomial/src/index.js","webpack:///ml/./~/ml-regression-theil-sen/src/index.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/dc/cholesky.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/dc/evd.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/decompositions.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/symbol-species.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/views/column.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/views/flipColumn.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/views/flipRow.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/views/row.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/views/selection.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/views/sub.js","webpack:///ml/./~/ml-regression/~/ml-matrix/src/views/transpose.js","webpack:///ml/./~/ml-regression/src/regression/kernel-ridge-regression.js","webpack:///ml/./~/ml-regression/src/regression/poly-fit-regression2d.js","webpack:///ml/./~/ml-regression/src/regression/potential-regression.js","webpack:///ml/./~/ml-regression/src/regression/util.js","webpack:///ml/./~/ml-savitzky-golay-generalized/~/ml-stat/index.js","webpack:///ml/./~/ml-savitzky-golay-generalized/~/ml-stat/matrix.js","webpack:///ml/./~/ml-som/src/node-hexagonal.js","webpack:///ml/./~/ml-stat/matrix.js","webpack:///ml/./~/ml-tree-similarity/src/index.js","webpack:///ml/./~/new-array/index.js","webpack:///ml/./~/number-is-nan/index.js","webpack:///ml/./~/process/browser.js","webpack:///ml/./~/util/~/inherits/inherits_browser.js","webpack:///ml/./~/util/support/isBufferBrowser.js","webpack:///ml/./~/util/util.js","webpack:///ml/(webpack)/buildin/global.js"],"names":[],"mappings":"AAAA,cACA,2BACA,uCACA,sCACA,IACA,aACA,oCAEA,SACA,GAAC,gCC8CD,mBCgDA,6BCxEA,uBCmLA,mCC8zCA,0BAt3CA,gDLhJA,kBMTA,cAMA,IACA,iBAGA,mBACA,CACA,IACA,KAIA,2CAGA,aAGA,OACA,OAIA,IAzBA,eA4BA,MAGA,mBAA2C,CAAc,QAGzD,qBACA,GACA,kCACA,CACA,gBACA,cAGA,OAGA,iBACA,YACA,qBAA2B,UAA0B,UACrD,YAAiC,CAAe,QAChD,EAEA,aADA,QAIA,mBAAsD,wCAA+D,SAGrH,MAGA,+BChEA,aAEA,sBACA,0DCHA,aAEA,eACA,WACA,IAAmB,MAAc,OACjC,yBAEA,MACA,SAEA,eACA,UACA,QAEA,YACA,6BCfA,aAEA,cACA,gFCIC,IAED,+BACA,iBACA,IACA,4BACA,yBAEA,eACA,qBACS,iBACT,QACA,eACA,UAA2B,EAAW,IACtC,YAGA,kCAES,iEACT,MACA,YACA,cACA,2BACA,0BAEA,yDACA,WAAuB,EAAW,QAClC,SACA,gCAEA,mDACA,KACA,CACA,0BAEA,oEACA,YACA,UACA,IAEA,WACA,OACA,cACA,IAEA,SACA,OACA,WAMA,QACA,+DACA,WAAyB,SAAiB,KAC1C,cAAgC,SAAuB,QACvD,mBAGA,UACA,QAOA,aACA,aACA,QACA,mCAEA,+DACA,cACA,EACA,IAQA,YACA,OACA,cACA,WAEA,eACA,sBACA,yBACA,gBACA,EACA,IAOA,gBACA,aACA,QACA,sCAEA,uDAAuB,SAAe,KACtC,qBAEA,wBACA,EACA,IAQA,eACA,CACA,wBACA,WAEA,kBACA,sBACA,kBAAuB,SAAe,KACtC,uBAEA,2BACA,EACA,IACA,yBC5IA,aAEA,OACA,QACA,YAEA,wBACA,iBACA,IACA,4BACA,yBAEA,eACA,qBACS,iBACT,QACA,eACA,UAA2B,EAAW,IACtC,YAGA,kCAES,iEACT,MACA,YACA,cACA,2BACA,0BAEA,yDACA,WAAuB,EAAW,QAClC,SACA,gCAEA,mDACA,KACA,CACA,0BAEA,oEACA,YACA,UACA,IAEA,WACA,OACA,cACA,IAEA,SACA,OACA,WAMA,QACA,+DACA,WAAyB,SAAiB,KAC1C,cAAgC,SAAuB,QACvD,mBAGA,UACA,QAOA,aACA,oBACA,QACA,mCAEA,+DACA,cACA,EACA,IAQA,YACA,OACA,cACA,WAEA,sBACA,8BACA,yBACA,gBACA,EACA,IAOA,gBACA,uBACA,QACA,sCAEA,uDAAuB,SAAe,KACtC,qBAEA,wBACA,EACA,IAQA,eACA,CACA,wBACA,WAEA,4BACA,iCACA,kBAAuB,SAAe,KACtC,uBAEA,2BACA,EACA,IACA,EAEA,WACA,mFCrIC,IAED,+BACA,iBACA,IACA,4BACA,yBAEA,eACA,qBACS,iBACT,QACA,eACA,UAA2B,EAAW,IACtC,YAGA,kCAES,iEACT,MACA,YACA,cACA,2BACA,0BAEA,yDACA,WAAuB,EAAW,QAClC,SACA,gCAEA,mDACA,KACA,CACA,0BAEA,oEACA,YACA,UACA,IAEA,WACA,OACA,cACA,IAEA,SACA,OACA,WAMA,QACA,+DACA,WAAyB,SAAiB,KAC1C,cAAgC,SAAuB,QACvD,mBAGA,UACA,QAOA,aACA,aACA,QACA,mCAEA,+DACA,cACA,EACA,IAQA,YACA,OACA,cACA,WAEA,eACA,sBACA,yBACA,gBACA,EACA,IAOA,gBACA,aACA,QACA,sCAEA,uDAAuB,SAAe,KACtC,qBAEA,wBACA,EACA,IAQA,eACA,CACA,wBACA,WAEA,kBACA,sBACA,kBAAuB,SAAe,KACtC,uBAEA,2BACA,EACA,IACA,wECrIC,IAED,+BACA,iBACA,IACA,4BACA,yBAEA,eACA,qBACS,iBACT,QACA,eACA,UAA2B,EAAW,IACtC,YAGA,kCAES,iEACT,MACA,YACA,cACA,2BACA,0BAEA,yDACA,WAAuB,EAAW,QAClC,SACA,gCAEA,mDACA,KACA,CACA,0BAEA,oEACA,YACA,UACA,IAEA,WACA,OACA,cACA,IAEA,SACA,OACA,WAMA,QACA,+DACA,WAAyB,SAAiB,KAC1C,cAAgC,SAAuB,QACvD,mBAGA,UACA,QAOA,aACA,aACA,QACA,mCAEA,+DACA,cACA,EACA,IAQA,YACA,OACA,cACA,WAEA,eACA,sBACA,yBACA,gBACA,EACA,IAOA,gBACA,aACA,QACA,sCAEA,uDAAuB,SAAe,KACtC,qBAEA,wBACA,EACA,IAQA,eACA,CACA,wBACA,WAEA,kBACA,sBACA,kBAAuB,SAAe,KACtC,uBAEA,2BACA,EACA,IACA,wECrIC,IAED,+BACA,iBACA,IACA,4BACA,yBAEA,eACA,qBACS,iBACT,QACA,eACA,UAA2B,EAAW,IACtC,YAGA,kCAES,iEACT,MACA,YACA,cACA,2BACA,0BAEA,yDACA,WAAuB,EAAW,QAClC,SACA,gCAEA,mDACA,KACA,CACA,0BAEA,oEACA,YACA,UACA,IAEA,WACA,OACA,cACA,IAEA,SACA,OACA,WAMA,QACA,+DACA,WAAyB,SAAiB,KAC1C,cAAgC,SAAuB,QACvD,mBAGA,UACA,QAOA,aACA,aACA,QACA,mCAEA,+DACA,cACA,EACA,IAQA,YACA,OACA,cACA,WAEA,eACA,sBACA,yBACA,gBACA,EACA,IAOA,gBACA,aACA,QACA,sCAEA,uDAAuB,SAAe,KACtC,qBAEA,wBACA,EACA,IAQA,eACA,CACA,wBACA,WAEA,kBACA,sBACA,kBAAuB,SAAe,KACtC,uBAEA,2BACA,EACA,IACA,sDC3IA,GAEA,0BACA,mBACA,CACA,aACA,cACA,YACA,SAEA,6BACA,OACA,IACA,yBCdA,aAEA,QACA,WAEA,mBACA,mBACA,CACA,aACA,cACA,YACA,SAEA,6BACA,UACA,MACA,EAEA,0DCjBA,GAEA,0BACA,mBACA,CACA,aACA,cACA,YACA,SAEA,6BACA,OACA,IACA,sDCbA,GAEA,0BACA,mBACA,CACA,aACA,cACA,YACA,SAEA,6BACA,OACA,IACA,sDCbA,GAEA,0BACA,mBACA,CACA,aACA,cACA,YACA,SAEA,6BACA,OACA,IACA,yBCdA,mBAGA,mDACA,0ICHoC,GAEpC,OACA,cACA,QACA,2BAEA,oCAEA,WACA,IACA,+BACS,gCACT,iBACA,kBAA2B,MAAc,OACzC,uBAEA,MACA,QACA,qBAEA,8BAEA,WACA,iBACA,+BAEA,QAEA,CAEA,WACA,OACA,EAEA,UACA,OACA,EAQA,WACA,uDACA,uBAGA,uDACA,SACA,mBAAuB,EAAO,IAC9B,uBAGA,YACA,IACA,IACA,IACA,IACA,IACA,IACA,YAAuB,EAAO,IAC9B,OACA,QACA,aACA,aACA,aACA,KACA,sCAEA,0BAGA,yCAEA,YACA,CACA,OACA,IACA,YAEA,MACA,0CC5EA,eACA,uBACA,UACA,yBAEA,yBAQA,MACA,eACA,6BACA,UACA,yBAEA,4BASA,MACA,aACA,MACA,gBAEA,0BACA,6BAEA,yDACA,QASA,MACA,aACA,MACA,gBAEA,0BACA,0BAEA,sDACA,cAEA,eACA,mBACA,kBAEA,IAEA,iBACA,kBACA,OAEA,MACA,0BAGA,mDACA,uCAEA,4EACA,oCAEA,SACA,CACA,MAEA,eAEA,mBACA,6CACA,8EACA,OACA,kBACA,4BACA,mGACA,6BAEA,qCAQA,MAEA,WACA,4BACA,KAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,cAEA,WACA,yBACA,WAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,cAEA,WACA,WACA,IAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,SAGA,SACA,kBAnIA,oBCRA,aAEA,QAQA,GACA,+BACA,uBACA,UACA,yBAEA,yBAQA,EACA,kCACA,6BACA,UACA,yBAEA,4BASA,EACA,8BACA,MACA,gBAEA,0BACA,6BAEA,yDACA,QASA,EACA,iCACA,MACA,gBAEA,0BACA,0BAEA,sDACA,UAEA,8BACA,mBACA,kBAEA,IAEA,iBACA,kBACA,OAEA,MACA,0BAGA,mDACA,uCAEA,4EACA,oCAEA,SACA,CACA,MAEA,WAEA,gCACA,6CACA,8EACA,OACA,kBACA,4BACA,mGACA,6BAEA,uCAEA,wBACA,qBACA,KAAmB,MAAgB,OACnC,SAEA,IACA,UAEA,sBACA,iCACA,KAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,UAEA,yBACA,8BACA,WAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,UAEA,oBACA,WACA,IAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,SAGA,SACA,4CCpIA,eACA,uBACA,UACA,yBAEA,yBAQA,MACA,eACA,6BACA,UACA,yBAEA,4BASA,MACA,aACA,MACA,gBAEA,0BACA,6BAEA,yDACA,QASA,MACA,aACA,MACA,gBAEA,0BACA,0BAEA,sDACA,cAEA,eACA,mBACA,kBAEA,IAEA,iBACA,kBACA,OAEA,MACA,0BAGA,mDACA,uCAEA,4EACA,oCAEA,SACA,CACA,MAEA,eAEA,mBACA,6CACA,8EACA,OACA,kBACA,4BACA,mGACA,6BAEA,qCAQA,MAEA,WACA,4BACA,KAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,cAEA,WACA,yBACA,WAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,cAEA,WACA,WACA,IAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,SAGA,SACA,kBAnIA,qCCCA,eACA,uBACA,UACA,yBAEA,yBAQA,MACA,eACA,6BACA,UACA,yBAEA,4BASA,MACA,aACA,MACA,gBAEA,0BACA,6BAEA,yDACA,QASA,MACA,aACA,MACA,gBAEA,0BACA,0BAEA,sDACA,cAEA,eACA,mBACA,kBAEA,IAEA,iBACA,kBACA,OAEA,MACA,0BAGA,mDACA,uCAEA,4EACA,oCAEA,SACA,CACA,MAEA,eAEA,mBACA,6CACA,8EACA,OACA,kBACA,4BACA,mGACA,6BAEA,qCAQA,MAEA,WACA,4BACA,KAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,cAEA,WACA,yBACA,WAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,cAEA,WACA,WACA,IAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,SAGA,SACA,kBAnIA,qCCCA,eACA,uBACA,UACA,yBAEA,yBAQA,MACA,eACA,6BACA,UACA,yBAEA,4BASA,MACA,aACA,MACA,gBAEA,0BACA,6BAEA,yDACA,QASA,MACA,aACA,MACA,gBAEA,0BACA,0BAEA,sDACA,cAEA,eACA,mBACA,kBAEA,IAEA,iBACA,kBACA,OAEA,MACA,0BAGA,mDACA,uCAEA,4EACA,oCAEA,SACA,CACA,MAEA,eAEA,mBACA,6CACA,8EACA,OACA,kBACA,4BACA,mGACA,6BAEA,qCAQA,MAEA,WACA,4BACA,KAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,cAEA,WACA,yBACA,WAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,2BAGA,UACA,cAEA,WACA,WACA,IAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,SAGA,SACA,kBAnIA,oBCRA,aAEA,eAEA,WACA,SACA,SACA,SACA,SACA,SACA,SACA,SACA,SACA,SAEA,OACA,CACA,WACA,MACA,aACA,OACA,QACA,SACA,cACA,YACA,MACA,YACA,iBACA,WACA,UACA,OAoDA,UAlDA,KACA,iBACA,SACA,aAEA,mCACA,KAEA,oBACA,KACA,yBAEA,8BAEA,8BAAS,6BACT,kCAEA,0CAEA,yDAEA,aACA,IACA,aAGA,gCACA,OACA,gCACA,gBAEA,0BACA,cACA,KACA,YAAuB,MAAmB,OAC1C,QAA2B,QAAmB,OAC9C,qDAIA,iBAAuB,MAAmB,OAC1C,UAA2B,MAAsB,OACjD,6CAIA,MACA,QACA,gBChFA,aAEA,uBACA,kCAEA,sBACA,OACA,uCAGA,WACA,4BAEA,eACA,QACA,8BAGA,wBACA,wFAEA,uCACA,GAMA,SAEA,+CACA,WAEA,sBACA,iBAEA,KACA,cACA,OAGA,eANA,EAgBO,IATP,sBACA,gBAEA,SAEA,iCACA,wBAGA,MAAmB,IACnB,SAEA,aAEA,QACA,aACA,OAGA,KAEA,wBAEA,WACA,UAEA,gBAIA,eAGM,UACN,wBAQA,SACA,2BCrFA,aAIA,YACA,MACA,2BACA,OACA,QAMA,CAZA,cAaA,2BACA,6BACA,6BACA,sBACA,yBACA,sBACA,gBACA,IACA,iBACA,SACA,aACA,WAEA,qBAEA,SACA,CACA,QAMA,EACA,6BACA,oCAEA,0EACA,qBACA,QAEA,cAEA,kBACA,SACA,SACA,sBAEA,gCACA,QAEA,OACA,MAIA,oBAHA,0BAEA,UAOA,EACA,gCACA,gBACA,IACA,OACA,qCAAkD,EAAQ,KAC1D,QAGA,cACA,GACA,SAEA,8CxBpEA,2BA2hDA,OACA,IAMA,gBAyNA,QACA,8CAEA,MACA,QAEA,gBAvvDA,yBACA,6BACA,OACA,KASA,0BACA,IACA,QACA,4BAEA,4DACA,aAA6B,EAAe,IAC5C,cAAoC,EAAqB,IACzD,gBAGA,QACA,QAOA,oBACA,wBACA,UAA2B,MAAoB,OAC/C,cAEA,MACA,QAOA,uBACA,6BACA,KAA2B,MAAoB,OAC/C,cAEA,MACA,QAQA,kBACA,WACA,UAQA,kBACA,6BACA,EAQA,iBACA,6BACA,EASA,mBACA,qBACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,cAGA,KACA,QAUA,wBACA,cACA,2BACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,IAAa,IAC5C,QACA,SAGA,WACA,QASA,kBACA,cACA,oBACA,2BAEA,aAA2B,EAAS,IACpC,MAEA,WACA,QASA,mBACA,SACA,oBACA,kBACA,eACA,gBACA,aAA2B,EAAS,IACpC,cAEA,MACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAOA,sBACA,2BACA,QAOA,mBACA,iBACA,kBAKA,WACA,uBACA,OAOA,SACA,IACA,yCAEA,8CACA,YACA,UAA2B,EAAQ,IACnC,cAA+B,EAAQ,IACvC,WAGA,gBACA,KAMA,YACA,sBACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,6BAGA,SACA,QAMA,YACA,sBACA,QAA2B,SAAe,SAC1C,iBACA,mBAA+B,SAAkB,QACjD,iBAEA,QACA,CACA,QAKA,cACA,OACA,cAKA,iBACA,OACA,iBAKA,WACA,uBACA,gBAKA,WACA,yBACA,OAKA,cACA,oBACA,WAA+B,SAAe,KAC9C,cAAmC,EAAQ,KAC3C,4BACA,SAIA,SACA,QACA,CACA,QAUA,MACA,iBACA,8BASA,MACA,iBACA,8BAYA,YACA,MACA,OACA,kEACA,aAA2B,EAAY,IACvC,cAA+B,EAAY,IAC3C,yCAGA,WACA,QAOA,QACA,WAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SAGA,iBACA,KAMA,MACA,mBACA,EAOA,UACA,KACA,6BACA,WAA2B,SAAkB,QAC7C,cAEA,SACA,QAOA,gBACA,wCACA,UAQA,YACA,KACA,cACA,kBAA2B,SAAkB,QAC7C,iBAEA,YACA,KAQA,cACA,KACA,YACA,kBAA2B,WAAkB,QAC7C,WACA,2BACA,eAEA,iBACA,KAOA,aACA,KACA,6BACA,QAA2B,SAAe,KAC1C,cAEA,SACA,QAOA,mBACA,2CACA,aAQA,eACA,KACA,cACA,kBAA2B,SAAe,KAC1C,iBAEA,YACA,KAQA,iBACA,KACA,YACA,kBAA2B,WAAe,KAC1C,WACA,2BACA,eAEA,iBACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAQA,YACA,KACA,kBAA2B,SAAkB,QAC7C,sBAEA,kBACA,KAQA,eACA,KACA,kBAA2B,SAAe,KAC1C,sBAEA,kBACA,KAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAOA,UACA,KACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,KACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,UACA,KACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,KACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,aACA,KACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,KACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAOA,aACA,KACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,KACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAMA,OACA,4BACA,WACA,WAA2B,EAAS,IACpC,cAEA,SACA,QAQA,OAEA,OACA,cACA,MACA,iBAEA,UAEA,KAMA,OACA,wBACA,IAMA,OACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YAGA,SACA,QAMA,gBACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YACA,cAGA,iBACA,KAOA,OACA,qBACA,wBACA,4BACA,4BAEA,+CACA,IAA2B,MAAoB,OAC/C,YAEA,KACA,QAOA,QACA,oBACA,gCAEA,mBAGA,oGACA,YACA,YAEA,sCAEA,gBACA,WAA2B,EAAO,QAClC,WAA+B,EAAO,IACtC,WAGA,mBAA+B,IAAO,QACtC,OACA,IAA+B,EAAO,IACtC,qBAGA,OACA,UACA,CACA,CACA,QAEA,eACA,8CACA,sBACA,aACA,gBACA,aACA,gBACA,aACA,gBACA,aAGA,YACA,QACA,YACA,UACA,QACA,OAcA,eAJA,EALA,aADA,cAOA,EALA,aAMA,EALA,aAMA,EAJA,aARA,OAeA,eACA,8CAEA,sBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBAEA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aAEA,YAEA,kBAEA,gBACA,QACA,gBACA,iBACA,cACA,kBAGA,gBACA,OACA,aACA,kBACA,gBACA,cACA,MA0BA,eATA,EAVA,IANA,aAiBA,GAnCA,gBAyBA,sBAWA,EAVA,OAjBA,gCA4BA,EAVA,KAzBA,mCAoCA,EAVA,QATA,aAoBA,EAVA,QATA,aAoBA,EAVA,SApBA,+BA+BA,EAVA,QAVA,aAqBA,EATA,QAVA,MA2BA,gBACA,kBAaA,SACA,SACA,kBACA,MAEA,iBACA,WAGA,4BAFA,IASA,oBAQA,YACA,gBAIA,gBACA,oBACA,eACiB,IACjB,gBACA,aACiB,MACjB,mBACA,aAGA,0BACA,wBAEA,2BACA,2BAEA,mCACA,mCAEA,gCACA,gCAEA,wCACA,wCAGA,oBACA,oBACA,wBACA,sBACA,oBACA,iCACA,+BAGA,kBACA,WACA,SACA,eACA,aACA,aACA,WACA,SAGA,kCACA,qCACA,6BACA,0BACA,qCACA,+BACA,EACA,YA9FA,YACA,SACA,YACA,SACA,QAEA,oBAA4C,gBAAQ,OAAU,SAAQ,OAKtE,2CAkBA,SACA,gBACA,WAGA,SA6DA,UAQA,eACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAe,KAC1C,mCAAoD,MACpD,UAEA,YACA,QAWA,kBACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAkB,QAC7C,qCACA,CACA,MAEA,UAEA,eACA,QASA,oBACA,oBAEA,8BACA,YACA,YACA,SAEA,mDACA,OAA2B,EAAO,IAClC,cAA+B,EAAO,IACtC,cAAmC,EAAO,IAC1C,cAAuC,EAAO,IAC9C,oCAKA,SACA,QAMA,YACA,kEACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,mBAGA,UACA,QAOA,YACA,cACA,eAA2B,SAAe,KAC1C,iCAEA,eACA,KAOA,eACA,cACA,eAA2B,SAAkB,QAC7C,uCAEA,eACA,KAUA,mBACA,KACA,uEACA,GAAkC,IAAa,KAC/C,WAAyC,KAAgB,KACzD,qBAGA,SACA,QASA,oBACA,mBACA,+BACA,2CACA,6BAGA,qFACA,KAA2B,MAAoB,OAC/C,WAAyC,KAAgB,SACzD,uBACA,qDAEA,2BACA,QAEA,CACA,QASA,uBACA,mBACA,4BACA,wCACA,0BAGA,gFACA,UAA2B,MAAoB,OAC/C,WAAsC,KAAa,SACnD,uBACA,2DAEA,6BACA,MAEA,CACA,QASA,oBACA,oBACA,8BACA,gBACA,MACA,wBAA2B,MAAiB,KAC5C,cAA+B,MAAoB,QACnD,qBAGA,eACA,KAQA,eACA,eACA,4DACA,UAA2B,YAAwB,WACnD,KACA,iBAA+B,eAA2B,OAC1D,QACA,uBAEA,QACA,CACA,QAMA,QACA,4BACA,WACA,IAA2B,EAAS,IACpC,YAEA,SACA,QAUA,gBACA,gBACA,KAOA,WACA,YACA,gBACA,OAOA,cACA,YACA,gBACA,OAMA,cACA,gBACA,KAMA,iBACA,gBACA,KAUA,uBACA,gBACA,aAWA,mBACA,gBACA,SASA,MACA,oBACA,WACA,KAEA,qCACA,gBACA,gBACA,gBAEA,OACiB,wBAEjB,SACA,gBACA,kCACA,kCACA,wCACA,gBACA,gBAEA,2BACA,KAEA,sBAGA,WACA,aAEA,0DAOA,iBACA,2CAGA,uBACA,wBACA,yBAEA,WAA2B,MAAc,OACzC,WACA,UAOA,iDACA,wBACA,iBAGA,oBAEA,oBASA,kBACA,sCACA,kBACA,mCACA,0CACA,qDAMA,UAOA;;;;;IAWA;;;;;;;;;IAgBA;;;;;;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAQA;;;;;IAUA;;;;;;;;;IAgBA;;;;;;;;;;;;;;IASA;;;;;EAgBA,8OAEA,KADA,iBAEA,cAAqE,eACrE,eAA4E,mBAC5E,eAA4E,mBAC5E,eAAmE,OACnE,YAAmB,MAAqB,OACxC,gBACA,yBACA,wBACA,SAEA,OAEA,IAIA,iBAIA,+NACA,SACA,aAEA,EAzsDA,gBA0sDA,cAAqE,mBACrE,eAAmE,OACnE,YAAmB,MAAmB,OACtC,gBACA,UAEA,OAEA,IAIA,yCACA,OACA,aAAmB,MAAsB,GACzC,OAA4B,SAE5B,eACA,aACA,QACA,YACA,GAEA,mBAAuF,UACvF,gBAAuB,MAA0B,OACjD,gBACA,UAEA,OAAS,KACT,OACA,QACA,GACA,gBAEA,QACA,YACA,YACA,YACA,cAAuB,MAA0B,OACjD,gBACA,yBACA,wBACA,SAEA,OACA,CAEA,CAQA,iHApwDA,mCyBPA,aACA,MACA,yBAGA,gBAEA,uBACA,YACA,SACA,UACA,WACA,cACA,MAEA,QAAe,EAAU,IACzB,IAGA,aAEA,WAAe,EAAa,QAE5B,OAAmB,EAAU,IAC7B,SAGA,cAAmB,EAAU,QAC7B,OACA,OACA,SACA,IAAuB,EAAU,IACjC,YAEA,UACA,OAEA,KACA,QAAuB,EAAU,IACjC,cACA,QAIA,cACA,OAAuB,EAAa,IACpC,MACA,gBACA,QAGA,YACA,UACA,KAEA,SACA,EAEA,SACA,oBAA2B,EAAU,IACrC,aAGA,OAEA,MACA,UACA,mBACA,oBArEA,GAuEA,YACA,sBACA,gBACA,OACA,UAAuB,EAAS,IAChC,OACA,YAGA,SACA,QACA,mBACA,YACA,SACA,2BAEA,sDACA,UAAuB,EAAS,IAChC,OAEA,QACA,QACA,6BACA,gBACA,OACA,SACA,aACA,YAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,IACiB,QACjB,MAEA,EAIA,EACA,QACA,6BACA,gBACA,OACA,SACA,aACA,YAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,KAEA,QAIA,EACA,QACA,8BACA,yBACA,OACA,mBACA,OAEA,0BACA,OAEA,cACA,qBAEA,qCACA,6BAGA,iCACA,8CACA,OACA,YAEA,QAAmB,EAAa,IAChC,YAA2B,EAAa,IACxC,UAA2B,EAAW,IACtC,qBAIA,gBAA6B,EAAQ,SACrC,OAAuB,EAAW,IAClC,aAEA,cAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OACA,CACA,QAGA,yCC3KA,aACA,IACA,eACA,QACA,aAEA,MACA,MAIA,KAHA,aAEA,KAaA,MAEA,eACA,WACA,WAAmB,EAAU,QAC7B,MACA,mBAAuB,EAAa,IACpC,IAEA,SACA,CACA,yBClCA,aAEA,0BACA,IACA,eACA,QACA,aAEA,MACA,MAIA,KAHA,aAEA,KAMA,EACA,+BACA,WACA,WAAmB,EAAU,IAC7B,SAEA,SACA,UAEA,kCACA,WACA,WAAmB,EAAU,QAC7B,MACA,mBAAuB,EAAa,IACpC,IAEA,SACA,CACA,2BCpCA,aAqBA,eACA,oBACA,WACA,IAQA,CA9BA,UACA,OAMA,GA+BA,UACA,CACA,KAhCA,WACA,6BACA,MAQA,EAuBA,YACA,iBAXA,WACA,gBACA,mBACA,6CACA,uBAAY,iCACZ,2CC1BA,2BA2hDA,OACA,IAMA,gBAyNA,QACA,8CAEA,MACA,QAEA,gBAvvDA,yBACA,6BACA,OACA,KASA,0BACA,IACA,QACA,4BAEA,4DACA,aAA6B,EAAe,IAC5C,cAAoC,EAAqB,IACzD,gBAGA,QACA,QAOA,oBACA,wBACA,UAA2B,MAAoB,OAC/C,cAEA,MACA,QAOA,uBACA,6BACA,KAA2B,MAAoB,OAC/C,cAEA,MACA,QAQA,kBACA,WACA,UAQA,kBACA,6BACA,EAQA,iBACA,6BACA,EASA,mBACA,qBACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,cAGA,KACA,QAUA,wBACA,cACA,2BACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,IAAa,IAC5C,QACA,SAGA,WACA,QASA,kBACA,cACA,oBACA,aACA,cACA,aAA2B,EAAS,IACpC,MAEA,WACA,QASA,mBACA,SACA,oBACA,kBACA,eACA,gBACA,aAA2B,EAAS,IACpC,cAEA,MACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAOA,sBACA,2BACA,QAOA,mBACA,iBACA,kBAKA,WACA,uBACA,OAOA,SACA,IACA,yCAEA,8CACA,YACA,UAA2B,EAAQ,IACnC,cAA+B,EAAQ,IACvC,WAGA,gBACA,KAMA,YACA,sBACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,6BAGA,SACA,QAMA,YACA,sBACA,QAA2B,SAAe,SAC1C,iBACA,mBAA+B,SAAkB,QACjD,iBAEA,QACA,CACA,QAKA,cACA,OACA,cAKA,iBACA,OACA,iBAKA,WACA,uBACA,gBAKA,WACA,yBACA,OAKA,cACA,oBACA,WAA+B,SAAe,KAC9C,cAAmC,EAAQ,KAC3C,4BACA,SAIA,SACA,QACA,CACA,QAUA,MACA,iBACA,8BASA,MACA,iBACA,8BAYA,YACA,MACA,OACA,kEACA,aAA2B,EAAY,IACvC,cAA+B,EAAY,IAC3C,yCAGA,WACA,QAOA,QACA,WAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SAGA,iBACA,KAMA,MACA,mBACA,EAOA,UACA,KACA,6BACA,WAA2B,SAAkB,QAC7C,cAEA,SACA,QAOA,gBACA,wCACA,UAQA,YACA,KACA,cACA,kBAA2B,SAAkB,QAC7C,iBAEA,YACA,KAQA,cACA,KACA,YACA,kBAA2B,WAAkB,QAC7C,WACA,2BACA,eAEA,iBACA,KAOA,aACA,KACA,6BACA,QAA2B,SAAe,KAC1C,cAEA,SACA,QAOA,mBACA,2CACA,aAQA,eACA,KACA,cACA,kBAA2B,SAAe,KAC1C,iBAEA,YACA,KAQA,iBACA,KACA,YACA,kBAA2B,WAAe,KAC1C,WACA,2BACA,eAEA,iBACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAQA,YACA,KACA,kBAA2B,SAAkB,QAC7C,sBAEA,kBACA,KAQA,eACA,KACA,kBAA2B,SAAe,KAC1C,sBAEA,kBACA,KAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAOA,UACA,KACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,KACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,UACA,KACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,KACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,aACA,KACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,KACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAOA,aACA,KACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,KACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAMA,OACA,4BACA,WACA,WAA2B,EAAS,IACpC,cAEA,SACA,QAQA,OAEA,OACA,cACA,MACA,iBAEA,UAEA,KAMA,OACA,wBACA,IAMA,OACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YAGA,SACA,QAMA,gBACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YACA,cAGA,iBACA,KAOA,OACA,qBACA,wBACA,4BACA,4BAEA,+CACA,IAA2B,MAAoB,OAC/C,YAEA,KACA,QAOA,QACA,oBACA,gCAEA,mBAGA,oGACA,YACA,YAEA,sCAEA,gBACA,WAA2B,EAAO,QAClC,WAA+B,EAAO,IACtC,WAGA,mBAA+B,IAAO,QACtC,OACA,IAA+B,EAAO,IACtC,qBAGA,OACA,UACA,CACA,CACA,QAEA,eACA,8CACA,sBACA,aACA,gBACA,aACA,gBACA,aACA,gBACA,aAGA,YACA,QACA,YACA,UACA,QACA,OAcA,eAJA,EALA,aADA,cAOA,EALA,aAMA,EALA,aAMA,EAJA,aARA,OAeA,eACA,8CAEA,sBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBAEA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aAEA,YAEA,kBAEA,gBACA,QACA,gBACA,iBACA,cACA,kBAGA,gBACA,OACA,aACA,kBACA,gBACA,cACA,MA0BA,eATA,EAVA,IANA,aAiBA,GAnCA,gBAyBA,sBAWA,EAVA,OAjBA,gCA4BA,EAVA,KAzBA,mCAoCA,EAVA,QATA,aAoBA,EAVA,QATA,aAoBA,EAVA,SApBA,+BA+BA,EAVA,QAVA,aAqBA,EATA,QAVA,MA2BA,gBACA,kBAaA,SACA,SACA,kBACA,MAEA,iBACA,WAGA,4BAFA,IASA,oBAQA,YACA,gBAIA,gBACA,oBACA,eACiB,IACjB,gBACA,aACiB,MACjB,mBACA,aAGA,0BACA,wBAEA,2BACA,2BAEA,mCACA,mCAEA,gCACA,gCAEA,wCACA,wCAGA,oBACA,oBACA,wBACA,sBACA,oBACA,iCACA,+BAGA,kBACA,WACA,SACA,eACA,aACA,aACA,WACA,SAGA,kCACA,qCACA,6BACA,0BACA,qCACA,+BACA,EACA,YA9FA,YACA,SACA,YACA,SACA,QAEA,oBAA4C,gBAAQ,OAAU,SAAQ,OAKtE,2CAkBA,SACA,gBACA,WAGA,SA6DA,UAQA,eACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAe,KAC1C,mCAAoD,MACpD,UAEA,YACA,QAWA,kBACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAkB,QAC7C,qCACA,CACA,MAEA,UAEA,eACA,QASA,oBACA,oBAEA,8BACA,YACA,YACA,SAEA,mDACA,OAA2B,EAAO,IAClC,cAA+B,EAAO,IACtC,cAAmC,EAAO,IAC1C,cAAuC,EAAO,IAC9C,oCAKA,SACA,QAMA,YACA,kEACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,mBAGA,UACA,QAOA,YACA,cACA,eAA2B,SAAe,KAC1C,iCAEA,eACA,KAOA,eACA,cACA,eAA2B,SAAkB,QAC7C,uCAEA,eACA,KAUA,mBACA,KACA,uEACA,GAAkC,IAAa,KAC/C,WAAyC,KAAgB,KACzD,qBAGA,SACA,QASA,oBACA,mBACA,+BACA,2CACA,6BAGA,qFACA,KAA2B,MAAoB,OAC/C,WAAyC,KAAgB,SACzD,uBACA,qDAEA,2BACA,QAEA,CACA,QASA,uBACA,mBACA,4BACA,wCACA,0BAGA,gFACA,UAA2B,MAAoB,OAC/C,WAAsC,KAAa,SACnD,uBACA,2DAEA,6BACA,MAEA,CACA,QASA,oBACA,oBACA,8BACA,gBACA,MACA,wBAA2B,MAAiB,KAC5C,cAA+B,MAAoB,QACnD,qBAGA,eACA,KAQA,eACA,eACA,4DACA,UAA2B,YAAwB,WACnD,KACA,iBAA+B,eAA2B,OAC1D,QACA,uBAEA,QACA,CACA,QAMA,QACA,4BACA,WACA,IAA2B,EAAS,IACpC,YAEA,SACA,QAUA,gBACA,gBACA,KAOA,WACA,YACA,gBACA,OAOA,cACA,YACA,gBACA,OAMA,cACA,gBACA,KAMA,iBACA,gBACA,KAUA,uBACA,gBACA,aAWA,mBACA,gBACA,SASA,MACA,oBACA,WACA,KAEA,qCACA,gBACA,gBACA,gBAEA,OACiB,wBAEjB,SACA,gBACA,kCACA,kCACA,wCACA,gBACA,gBAEA,2BACA,KAEA,sBAGA,WACA,aAEA,0DAOA,iBACA,cACA,6BAEA,uBACA,wBACA,yBAEA,WAA2B,MAAc,OACzC,WACA,UAOA,iDACA,wBACA,iBAGA,oBAEA,oBASA,kBACA,sCACA,kBACA,mCACA,0CACA,qDAMA,UAOA;;;;;IAWA;;;;;;;;;IAgBA;;;;;;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAQA;;;;;IAUA;;;;;;;;;IAgBA;;;;;;;;;;;;;;IASA;;;;;EAgBA,8OAEA,KADA,iBAEA,cAAqE,eACrE,eAA4E,mBAC5E,eAA4E,mBAC5E,eAAmE,OACnE,YAAmB,MAAqB,OACxC,gBACA,yBACA,wBACA,SAEA,OAEA,IAIA,iBAIA,+NACA,SACA,aAEA,EAzsDA,gBA0sDA,cAAqE,mBACrE,eAAmE,OACnE,YAAmB,MAAmB,OACtC,gBACA,UAEA,OAEA,IAIA,yCACA,OACA,aAAmB,MAAsB,GACzC,OAA4B,SAE5B,eACA,aACA,QACA,YACA,GAEA,mBAAuF,UACvF,gBAAuB,MAA0B,OACjD,gBACA,UAEA,OAAS,KACT,OACA,QACA,GACA,gBAEA,QACA,YACA,YACA,YACA,cAAuB,MAA0B,OACjD,gBACA,yBACA,wBACA,SAEA,OACA,CAEA,CAQA,iHApwDA,mCCPA,aACA,MACA,yBAGA,gBAEA,uBACA,YACA,SACA,UACA,WACA,cACA,MAEA,QAAe,EAAU,IACzB,IAGA,aAEA,WAAe,EAAa,QAE5B,OAAmB,EAAU,IAC7B,SAGA,cAAmB,EAAU,QAC7B,OACA,OACA,SACA,IAAuB,EAAU,IACjC,YAEA,UACA,OAEA,KACA,QAAuB,EAAU,IACjC,cACA,QAIA,cACA,OAAuB,EAAa,IACpC,MACA,gBACA,QAGA,YACA,UACA,KAEA,SACA,EAEA,SACA,oBAA2B,EAAU,IACrC,aAGA,OAEA,MACA,UACA,mBACA,oBArEA,GAuEA,YACA,sBACA,gBACA,OACA,UAAuB,EAAS,IAChC,OACA,YAGA,SACA,QACA,mBACA,YACA,SACA,2BAEA,sDACA,UAAuB,EAAS,IAChC,OAEA,QACA,QACA,6BACA,gBACA,OACA,SACA,aACA,YAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,IACiB,QACjB,MAEA,EAIA,EACA,QACA,6BACA,gBACA,OACA,SACA,aACA,YAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,KAEA,QAIA,EACA,QACA,8BACA,yBACA,OACA,mBACA,OAEA,0BACA,OAEA,cACA,qBAEA,qCACA,6BAGA,iCACA,8CACA,OACA,YAEA,QAAmB,EAAa,IAChC,YAA2B,EAAa,IACxC,UAA2B,EAAW,IACtC,qBAIA,gBAA6B,EAAQ,SACrC,OAAuB,EAAW,IAClC,aAEA,cAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OACA,CACA,QAGA,yCC3KA,aACA,IACA,eACA,QACA,aAEA,MACA,MAIA,KAHA,aAEA,KAaA,MAEA,eACA,WACA,WAAmB,EAAU,QAC7B,MACA,mBAAuB,EAAa,IACpC,IAEA,SACA,CACA,4CCtBA,2BA2hDA,OACA,IAMA,gBAyNA,QACA,8CAEA,MACA,QAEA,gBAvvDA,yBACA,6BACA,OACA,KASA,0BACA,IACA,QACA,4BAEA,4DACA,aAA6B,EAAe,IAC5C,cAAoC,EAAqB,IACzD,gBAGA,QACA,QAOA,oBACA,wBACA,UAA2B,MAAoB,OAC/C,cAEA,MACA,QAOA,uBACA,6BACA,KAA2B,MAAoB,OAC/C,cAEA,MACA,QAQA,kBACA,WACA,UAQA,kBACA,6BACA,EAQA,iBACA,6BACA,EASA,mBACA,qBACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,cAGA,KACA,QAUA,wBACA,cACA,2BACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,IAAa,IAC5C,QACA,SAGA,WACA,QASA,kBACA,cACA,oBACA,aACA,cACA,aAA2B,EAAS,IACpC,MAEA,WACA,QASA,mBACA,SACA,oBACA,kBACA,eACA,gBACA,aAA2B,EAAS,IACpC,cAEA,MACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAOA,sBACA,2BACA,QAOA,mBACA,iBACA,kBAKA,WACA,uBACA,OAOA,SACA,IACA,yCAEA,8CACA,YACA,UAA2B,EAAQ,IACnC,cAA+B,EAAQ,IACvC,WAGA,gBACA,KAMA,YACA,sBACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,6BAGA,SACA,QAMA,YACA,sBACA,QAA2B,SAAe,SAC1C,iBACA,mBAA+B,SAAkB,QACjD,iBAEA,QACA,CACA,QAKA,cACA,OACA,cAKA,iBACA,OACA,iBAKA,WACA,uBACA,gBAKA,WACA,yBACA,OAKA,cACA,oBACA,WAA+B,SAAe,KAC9C,cAAmC,EAAQ,KAC3C,4BACA,SAIA,SACA,QACA,CACA,QAUA,MACA,iBACA,8BASA,MACA,iBACA,8BAYA,YACA,MACA,OACA,kEACA,aAA2B,EAAY,IACvC,cAA+B,EAAY,IAC3C,yCAGA,WACA,QAOA,QACA,WAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SAGA,iBACA,KAMA,MACA,mBACA,EAOA,UACA,KACA,6BACA,WAA2B,SAAkB,QAC7C,cAEA,SACA,QAOA,gBACA,wCACA,UAQA,YACA,KACA,cACA,kBAA2B,SAAkB,QAC7C,iBAEA,YACA,KAQA,cACA,KACA,YACA,kBAA2B,WAAkB,QAC7C,WACA,2BACA,eAEA,iBACA,KAOA,aACA,KACA,6BACA,QAA2B,SAAe,KAC1C,cAEA,SACA,QAOA,mBACA,2CACA,aAQA,eACA,KACA,cACA,kBAA2B,SAAe,KAC1C,iBAEA,YACA,KAQA,iBACA,KACA,YACA,kBAA2B,WAAe,KAC1C,WACA,2BACA,eAEA,iBACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAQA,YACA,KACA,kBAA2B,SAAkB,QAC7C,sBAEA,kBACA,KAQA,eACA,KACA,kBAA2B,SAAe,KAC1C,sBAEA,kBACA,KAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAOA,UACA,KACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,KACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,UACA,KACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,KACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,aACA,KACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,KACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAOA,aACA,KACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,KACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAMA,OACA,4BACA,WACA,WAA2B,EAAS,IACpC,cAEA,SACA,QAQA,OAEA,OACA,cACA,MACA,iBAEA,UAEA,KAMA,OACA,wBACA,IAMA,OACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YAGA,SACA,QAMA,gBACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YACA,cAGA,iBACA,KAOA,OACA,qBACA,wBACA,4BACA,4BAEA,+CACA,IAA2B,MAAoB,OAC/C,YAEA,KACA,QAOA,QACA,oBACA,gCAEA,mBAGA,oGACA,YACA,YAEA,sCAEA,gBACA,WAA2B,EAAO,QAClC,WAA+B,EAAO,IACtC,WAGA,mBAA+B,IAAO,QACtC,OACA,IAA+B,EAAO,IACtC,qBAGA,OACA,UACA,CACA,CACA,QAEA,eACA,8CACA,sBACA,aACA,gBACA,aACA,gBACA,aACA,gBACA,aAGA,YACA,QACA,YACA,UACA,QACA,OAcA,eAJA,EALA,aADA,cAOA,EALA,aAMA,EALA,aAMA,EAJA,aARA,OAeA,eACA,8CAEA,sBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBAEA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aAEA,YAEA,kBAEA,gBACA,QACA,gBACA,iBACA,cACA,kBAGA,gBACA,OACA,aACA,kBACA,gBACA,cACA,MA0BA,eATA,EAVA,IANA,aAiBA,GAnCA,gBAyBA,sBAWA,EAVA,OAjBA,gCA4BA,EAVA,KAzBA,mCAoCA,EAVA,QATA,aAoBA,EAVA,QATA,aAoBA,EAVA,SApBA,+BA+BA,EAVA,QAVA,aAqBA,EATA,QAVA,MA2BA,gBACA,kBAaA,SACA,SACA,kBACA,MAEA,iBACA,WAGA,4BAFA,IASA,oBAQA,YACA,gBAIA,gBACA,oBACA,eACiB,IACjB,gBACA,aACiB,MACjB,mBACA,aAGA,0BACA,wBAEA,2BACA,2BAEA,mCACA,mCAEA,gCACA,gCAEA,wCACA,wCAGA,oBACA,oBACA,wBACA,sBACA,oBACA,iCACA,+BAGA,kBACA,WACA,SACA,eACA,aACA,aACA,WACA,SAGA,kCACA,qCACA,6BACA,0BACA,qCACA,+BACA,EACA,YA9FA,YACA,SACA,YACA,SACA,QAEA,oBAA4C,gBAAQ,OAAU,SAAQ,OAKtE,2CAkBA,SACA,gBACA,WAGA,SA6DA,UAQA,eACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAe,KAC1C,mCAAoD,MACpD,UAEA,YACA,QAWA,kBACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAkB,QAC7C,qCACA,CACA,MAEA,UAEA,eACA,QASA,oBACA,oBAEA,8BACA,YACA,YACA,SAEA,mDACA,OAA2B,EAAO,IAClC,cAA+B,EAAO,IACtC,cAAmC,EAAO,IAC1C,cAAuC,EAAO,IAC9C,oCAKA,SACA,QAMA,YACA,kEACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,mBAGA,UACA,QAOA,YACA,cACA,eAA2B,SAAe,KAC1C,iCAEA,eACA,KAOA,eACA,cACA,eAA2B,SAAkB,QAC7C,uCAEA,eACA,KAUA,mBACA,KACA,uEACA,GAAkC,IAAa,KAC/C,WAAyC,KAAgB,KACzD,qBAGA,SACA,QASA,oBACA,mBACA,+BACA,2CACA,6BAGA,qFACA,KAA2B,MAAoB,OAC/C,WAAyC,KAAgB,SACzD,uBACA,qDAEA,2BACA,QAEA,CACA,QASA,uBACA,mBACA,4BACA,wCACA,0BAGA,gFACA,UAA2B,MAAoB,OAC/C,WAAsC,KAAa,SACnD,uBACA,2DAEA,6BACA,MAEA,CACA,QASA,oBACA,oBACA,8BACA,gBACA,MACA,wBAA2B,MAAiB,KAC5C,cAA+B,MAAoB,QACnD,qBAGA,eACA,KAQA,eACA,eACA,4DACA,UAA2B,YAAwB,WACnD,KACA,iBAA+B,eAA2B,OAC1D,QACA,uBAEA,QACA,CACA,QAMA,QACA,4BACA,WACA,IAA2B,EAAS,IACpC,YAEA,SACA,QAUA,gBACA,gBACA,KAOA,WACA,YACA,gBACA,OAOA,cACA,YACA,gBACA,OAMA,cACA,gBACA,KAMA,iBACA,gBACA,KAUA,uBACA,gBACA,aAWA,mBACA,gBACA,SASA,MACA,oBACA,WACA,KAEA,qCACA,gBACA,gBACA,gBAEA,OACiB,wBAEjB,SACA,gBACA,kCACA,kCACA,wCACA,gBACA,gBAEA,2BACA,KAEA,sBAGA,WACA,aAEA,0DAOA,iBACA,cACA,6BAEA,uBACA,wBACA,yBAEA,WAA2B,MAAc,OACzC,WACA,UAOA,iDACA,wBACA,iBAGA,oBAEA,oBASA,kBACA,sCACA,kBACA,mCACA,0CACA,qDAMA,UAOA;;;;;IAWA;;;;;;;;;IAgBA;;;;;;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAQA;;;;;IAUA;;;;;;;;;IAgBA;;;;;;;;;;;;;;IASA;;;;;EAgBA,8OAEA,KADA,iBAEA,cAAqE,eACrE,eAA4E,mBAC5E,eAA4E,mBAC5E,eAAmE,OACnE,YAAmB,MAAqB,OACxC,gBACA,yBACA,wBACA,SAEA,OAEA,IAIA,iBAIA,+NACA,SACA,aAEA,EAzsDA,gBA0sDA,cAAqE,mBACrE,eAAmE,OACnE,YAAmB,MAAmB,OACtC,gBACA,UAEA,OAEA,IAIA,yCACA,OACA,aAAmB,MAAsB,GACzC,OAA4B,SAE5B,eACA,aACA,QACA,YACA,GAEA,mBAAuF,UACvF,gBAAuB,MAA0B,OACjD,gBACA,UAEA,OAAS,KACT,OACA,QACA,GACA,gBAEA,QACA,YACA,YACA,YACA,cAAuB,MAA0B,OACjD,gBACA,yBACA,wBACA,SAEA,OACA,CAEA,CAQA,iHApwDA,mCCPA,aACA,MACA,yBAGA,gBAEA,uBACA,YACA,SACA,UACA,WACA,cACA,MAEA,QAAe,EAAU,IACzB,IAGA,aAEA,WAAe,EAAa,QAE5B,OAAmB,EAAU,IAC7B,SAGA,cAAmB,EAAU,QAC7B,OACA,OACA,SACA,IAAuB,EAAU,IACjC,YAEA,UACA,OAEA,KACA,QAAuB,EAAU,IACjC,cACA,QAIA,cACA,OAAuB,EAAa,IACpC,MACA,gBACA,QAGA,YACA,UACA,KAEA,SACA,EAEA,SACA,oBAA2B,EAAU,IACrC,aAGA,OAEA,MACA,UACA,mBACA,oBArEA,GAuEA,YACA,sBACA,gBACA,OACA,UAAuB,EAAS,IAChC,OACA,YAGA,SACA,QACA,mBACA,YACA,SACA,2BAEA,sDACA,UAAuB,EAAS,IAChC,OAEA,QACA,QACA,6BACA,gBACA,OACA,SACA,aACA,YAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,IACiB,QACjB,MAEA,EAIA,EACA,QACA,6BACA,gBACA,OACA,SACA,aACA,YAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,KAEA,QAIA,EACA,QACA,8BACA,yBACA,OACA,mBACA,OAEA,0BACA,OAEA,cACA,qBAEA,qCACA,6BAGA,iCACA,8CACA,OACA,YAEA,QAAmB,EAAa,IAChC,YAA2B,EAAa,IACxC,UAA2B,EAAW,IACtC,qBAIA,gBAA6B,EAAQ,SACrC,OAAuB,EAAW,IAClC,aAEA,cAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OACA,CACA,QAGA,yCC3KA,aACA,IACA,eACA,QACA,aAEA,MACA,MAIA,KAHA,aAEA,KAaA,MAEA,eACA,WACA,WAAmB,EAAU,QAC7B,MACA,mBAAuB,EAAa,IACpC,IAEA,SACA,CACA,wCCyBA,iBACA,WACA,aACA,IAEA,IACA,IAEA,YAAmB,EAAO,IAC1B,OACA,QACA,aACA,aAGA,iBACA,mBACA,gCACA,qCACA,gEA9E2D,IAE3D,mBACA,iBACA,CACA,QACA,qBACA,uBACA,2CAEA,aACA,YAEA,UAEA,SACA,OACA,MACA,oCACA,qBAEA,UAEA,YACA,0BACA,SAEA,YACA,+BACA,KAEA,YACA,OACA,4BACA,uBACA,oCACA,mBACA,gBACA,oCACA,OAA8B,KAAS,IAAG,aAC1C,EACA,CACA,uBAEA,aACA,QAEA,WACA,aACA,WAEA,eACA,IACA,sDAEA,yBACA,YACA,mDC7CA,2BA2hDA,OACA,IAMA,gBAyNA,QACA,8CAEA,MACA,QAEA,gBAvvDA,yBACA,6BACA,OACA,KASA,0BACA,IACA,QACA,4BAEA,4DACA,aAA6B,EAAe,IAC5C,cAAoC,EAAqB,IACzD,gBAGA,QACA,QAOA,oBACA,wBACA,UAA2B,MAAoB,OAC/C,cAEA,MACA,QAOA,uBACA,6BACA,KAA2B,MAAoB,OAC/C,cAEA,MACA,QAQA,kBACA,WACA,UAQA,kBACA,6BACA,EAQA,iBACA,6BACA,EASA,mBACA,qBACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,cAGA,KACA,QAUA,wBACA,cACA,2BACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,IAAa,IAC5C,QACA,SAGA,WACA,QASA,kBACA,cACA,oBACA,aACA,cACA,aAA2B,EAAS,IACpC,MAEA,WACA,QASA,mBACA,SACA,oBACA,kBACA,eACA,gBACA,aAA2B,EAAS,IACpC,cAEA,MACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAOA,sBACA,2BACA,QAOA,mBACA,iBACA,kBAKA,WACA,uBACA,OAOA,SACA,IACA,yCAEA,8CACA,YACA,UAA2B,EAAQ,IACnC,cAA+B,EAAQ,IACvC,WAGA,gBACA,KAMA,YACA,sBACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,6BAGA,SACA,QAMA,YACA,sBACA,QAA2B,SAAe,SAC1C,iBACA,mBAA+B,SAAkB,QACjD,iBAEA,QACA,CACA,QAKA,cACA,OACA,cAKA,iBACA,OACA,iBAKA,WACA,uBACA,gBAKA,WACA,yBACA,OAKA,cACA,oBACA,WAA+B,SAAe,KAC9C,cAAmC,EAAQ,KAC3C,4BACA,SAIA,SACA,QACA,CACA,QAUA,MACA,iBACA,8BASA,MACA,iBACA,8BAYA,YACA,MACA,OACA,kEACA,aAA2B,EAAY,IACvC,cAA+B,EAAY,IAC3C,yCAGA,WACA,QAOA,QACA,WAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SAGA,iBACA,KAMA,MACA,mBACA,EAOA,UACA,KACA,6BACA,WAA2B,SAAkB,QAC7C,cAEA,SACA,QAOA,gBACA,wCACA,UAQA,YACA,KACA,cACA,kBAA2B,SAAkB,QAC7C,iBAEA,YACA,KAQA,cACA,KACA,YACA,kBAA2B,WAAkB,QAC7C,WACA,2BACA,eAEA,iBACA,KAOA,aACA,KACA,6BACA,QAA2B,SAAe,KAC1C,cAEA,SACA,QAOA,mBACA,2CACA,aAQA,eACA,KACA,cACA,kBAA2B,SAAe,KAC1C,iBAEA,YACA,KAQA,iBACA,KACA,YACA,kBAA2B,WAAe,KAC1C,WACA,2BACA,eAEA,iBACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,OACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAQA,YACA,KACA,kBAA2B,SAAkB,QAC7C,sBAEA,kBACA,KAQA,eACA,KACA,kBAA2B,SAAe,KAC1C,sBAEA,kBACA,KAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAOA,UACA,KACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,KACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,UACA,KACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,KACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,aACA,KACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,KACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAOA,aACA,KACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,KACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAMA,OACA,4BACA,WACA,WAA2B,EAAS,IACpC,cAEA,SACA,QAQA,OAEA,OACA,cACA,MACA,iBAEA,UAEA,KAMA,OACA,wBACA,IAMA,OACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YAGA,SACA,QAMA,gBACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YACA,cAGA,iBACA,KAOA,OACA,qBACA,wBACA,4BACA,4BAEA,+CACA,IAA2B,MAAoB,OAC/C,YAEA,KACA,QAOA,QACA,oBACA,gCAEA,mBAGA,oGACA,YACA,YAEA,sCAEA,gBACA,WAA2B,EAAO,QAClC,WAA+B,EAAO,IACtC,WAGA,mBAA+B,IAAO,QACtC,OACA,IAA+B,EAAO,IACtC,qBAGA,OACA,UACA,CACA,CACA,QAEA,eACA,8CACA,sBACA,aACA,gBACA,aACA,gBACA,aACA,gBACA,aAGA,YACA,QACA,YACA,UACA,QACA,OAcA,eAJA,EALA,aADA,cAOA,EALA,aAMA,EALA,aAMA,EAJA,aARA,OAeA,eACA,8CAEA,sBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBAEA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aAEA,YAEA,kBAEA,gBACA,QACA,gBACA,iBACA,cACA,kBAGA,gBACA,OACA,aACA,kBACA,gBACA,cACA,MA0BA,eATA,EAVA,IANA,aAiBA,GAnCA,gBAyBA,sBAWA,EAVA,OAjBA,gCA4BA,EAVA,KAzBA,mCAoCA,EAVA,QATA,aAoBA,EAVA,QATA,aAoBA,EAVA,SApBA,+BA+BA,EAVA,QAVA,aAqBA,EATA,QAVA,MA2BA,gBACA,kBAaA,SACA,SACA,kBACA,MAEA,iBACA,WAGA,4BAFA,IASA,oBAQA,YACA,gBAIA,gBACA,oBACA,eACiB,IACjB,gBACA,aACiB,MACjB,mBACA,aAGA,0BACA,wBAEA,2BACA,2BAEA,mCACA,mCAEA,gCACA,gCAEA,wCACA,wCAGA,oBACA,oBACA,wBACA,sBACA,oBACA,iCACA,+BAGA,kBACA,WACA,SACA,eACA,aACA,aACA,WACA,SAGA,kCACA,qCACA,6BACA,0BACA,qCACA,+BACA,EACA,YA9FA,YACA,SACA,YACA,SACA,QAEA,oBAA4C,gBAAQ,OAAU,SAAQ,OAKtE,2CAkBA,SACA,gBACA,WAGA,SA6DA,UAQA,eACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAe,KAC1C,mCAAoD,MACpD,UAEA,YACA,QAWA,kBACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAkB,QAC7C,qCACA,CACA,MAEA,UAEA,eACA,QASA,oBACA,oBAEA,8BACA,YACA,YACA,SAEA,mDACA,OAA2B,EAAO,IAClC,cAA+B,EAAO,IACtC,cAAmC,EAAO,IAC1C,cAAuC,EAAO,IAC9C,oCAKA,SACA,QAMA,YACA,kEACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,mBAGA,UACA,QAOA,YACA,cACA,eAA2B,SAAe,KAC1C,iCAEA,eACA,KAOA,eACA,cACA,eAA2B,SAAkB,QAC7C,uCAEA,eACA,KAUA,mBACA,KACA,uEACA,GAAkC,IAAa,KAC/C,WAAyC,KAAgB,KACzD,qBAGA,SACA,QASA,oBACA,mBACA,+BACA,2CACA,6BAGA,qFACA,KAA2B,MAAoB,OAC/C,WAAyC,KAAgB,SACzD,uBACA,qDAEA,2BACA,QAEA,CACA,QASA,uBACA,mBACA,4BACA,wCACA,0BAGA,gFACA,UAA2B,MAAoB,OAC/C,WAAsC,KAAa,SACnD,uBACA,2DAEA,6BACA,MAEA,CACA,QASA,oBACA,oBACA,8BACA,gBACA,MACA,wBAA2B,MAAiB,KAC5C,cAA+B,MAAoB,QACnD,qBAGA,eACA,KAQA,eACA,eACA,4DACA,UAA2B,YAAwB,WACnD,KACA,iBAA+B,eAA2B,OAC1D,QACA,uBAEA,QACA,CACA,QAMA,QACA,4BACA,WACA,IAA2B,EAAS,IACpC,YAEA,SACA,QAUA,gBACA,gBACA,KAOA,WACA,YACA,gBACA,OAOA,cACA,YACA,gBACA,OAMA,cACA,gBACA,KAMA,iBACA,gBACA,KAUA,uBACA,gBACA,aAWA,mBACA,gBACA,SASA,MACA,oBACA,WACA,KAEA,qCACA,gBACA,gBACA,gBAEA,OACiB,wBAEjB,SACA,gBACA,kCACA,kCACA,wCACA,gBACA,gBAEA,2BACA,KAEA,sBAGA,WACA,aAEA,0DAOA,iBACA,cACA,6BAEA,uBACA,wBACA,yBAEA,WAA2B,MAAc,OACzC,WACA,UAOA,iDACA,wBACA,iBAGA,oBAEA,oBASA,kBACA,sCACA,kBACA,mCACA,0CACA,qDAMA,UAOA;;;;;IAWA;;;;;;;;;IAgBA;;;;;;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAQA;;;;;IAUA;;;;;;;;;IAgBA;;;;;;;;;;;;;;IASA;;;;;EAgBA,8OAEA,KADA,iBAEA,cAAqE,eACrE,eAA4E,mBAC5E,eAA4E,mBAC5E,eAAmE,OACnE,YAAmB,MAAqB,OACxC,gBACA,yBACA,wBACA,SAEA,OAEA,IAIA,iBAIA,+NACA,SACA,aAEA,EAzsDA,gBA0sDA,cAAqE,mBACrE,eAAmE,OACnE,YAAmB,MAAmB,OACtC,gBACA,UAEA,OAEA,IAIA,yCACA,OACA,aAAmB,MAAsB,GACzC,OAA4B,SAE5B,eACA,aACA,QACA,YACA,GAEA,mBAAuF,UACvF,gBAAuB,MAA0B,OACjD,gBACA,UAEA,OAAS,KACT,OACA,QACA,GACA,gBAEA,QACA,YACA,YACA,YACA,cAAuB,MAA0B,OACjD,gBACA,yBACA,wBACA,SAEA,OACA,CAEA,CAQA,iHApwDA,mCCPA,aACA,MACA,yBAGA,gBAEA,uBACA,YACA,SACA,UACA,WACA,cACA,MAEA,QAAe,EAAU,IACzB,IAGA,aAEA,WAAe,EAAa,QAE5B,OAAmB,EAAU,IAC7B,SAGA,cAAmB,EAAU,QAC7B,OACA,OACA,SACA,IAAuB,EAAU,IACjC,YAEA,UACA,OAEA,KACA,QAAuB,EAAU,IACjC,cACA,QAIA,cACA,OAAuB,EAAa,IACpC,MACA,gBACA,QAGA,YACA,UACA,KAEA,SACA,EAEA,SACA,oBAA2B,EAAU,IACrC,aAGA,OAEA,MACA,UACA,mBACA,oBArEA,GAuEA,YACA,sBACA,gBACA,OACA,UAAuB,EAAS,IAChC,OACA,YAGA,SACA,QACA,mBACA,YACA,SACA,2BAEA,sDACA,UAAuB,EAAS,IAChC,OAEA,QACA,QACA,6BACA,gBACA,OACA,SACA,aACA,YAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,IACiB,QACjB,MAEA,EAIA,EACA,QACA,6BACA,gBACA,OACA,SACA,aACA,YAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,KAEA,QAIA,EACA,QACA,8BACA,yBACA,OACA,mBACA,OAEA,0BACA,OAEA,cACA,qBAEA,qCACA,6BAGA,iCACA,8CACA,OACA,YAEA,QAAmB,EAAa,IAChC,YAA2B,EAAa,IACxC,UAA2B,EAAW,IACtC,qBAIA,gBAA6B,EAAQ,SACrC,OAAuB,EAAW,IAClC,aAEA,cAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OACA,CACA,QAGA,yCC3KA,aACA,IACA,eACA,QACA,aAEA,MACA,MAIA,KAHA,aAEA,KAaA,MAEA,eACA,WACA,WAAmB,EAAU,QAC7B,MACA,mBAAuB,EAAa,IACpC,IAEA,SACA,CACA,uBClCA,aA8EA,UA5EA,KACA,WACA,IACA,uBACA,WACA,kBAA2B,MAAc,OACzC,uBAEA,KAAS,gBACT,mBAEA,qCAEA,+BACA,QAEA,WACA,iBACA,2BAEA,QAEA,CAEA,WACA,OACA,EAEA,UACA,OACA,EAQA,kBACA,SACA,aACA,mBAAuB,EAAO,IAC9B,uBAEA,YACA,IACA,IACA,IACA,IACA,IACA,IAEA,YAAuB,EAAO,IAC9B,OACA,QACA,aACA,aACA,aACA,KACA,sCAEA,0BAGA,uCAEA,YACA,CACA,OACA,IACA,YAEA,MAEA,gBC5EA,6BACA,OAEA,KACA,aAGA,aACA,YACA,4BAGA,0BACA,sBAGA,aACA,YACA,4BAGA,4BAGA,mBACA,QAGA,YACA,QAGA,UACA,QAIA,MAIA,gBACA,iBCjCA,aAsBA,UArBA,aACA,WACA,yBAAoC,+BAGpC,sBAAmB,EAAY,IAC/B,cAAuB,EAAQ,KAC/B,mBAKA,gBAAmB,EAAY,IAC/B,gBAA2B,EAAY,IACvC,YAIA,QACA,2BC7BA,aAEA,kBACA,e,sBCHA,aAgSA,eACA,OACA,OAEA,eACA,cACA,OAEA,iBACA,gBACA,gBAEA,iBACA,gBACA,gBA5SA,UAEA,SACA,SACA,cAEA,eACA,IACA,IAEA,EAIA,OACA,aAA4B,KAC5B,IACA,eAYA,0BAXA,6BACA,2BACA,6BACA,mCACA,8BACA,4BACA,gCACA,uCACA,kDAfA,MAmBA,mBACA,yBAAiF,iDAGjF,uCAtBA,IAuBA,+CACA,sBACA,0BAA2D,2BAE3D,aACA,0BAA2D,2BAE3D,OACA,0BAAmD,mBAAsD,0CAGzG,QAIA,OACA,QACA,eAEA,kBACA,mBACA,kBAEA,QACA,mCACA,MAKA,kBACA,OAEA,gCACA,8BACA,cAEA,QACA,cACA,KAEA,WACA,aACA,QAEA,OACA,cACA,yBACA,OACA,SAEA,SACA,YACA,uBACA,IAKA,YAJA,OACA,mDAIA,mDACA,2BACA,eACA,QAEA,SACA,gBACA,oCACA,mBACA,gBAEA,8BACA,mDACA,oBACA,SAEA,CACA,QAEA,YACA,cACA,sBAEA,YACA,gBAEA,mBAGA,yBAEA,YACA,cACA,sBAEA,YACA,gBAEA,mBAGA,yBAEA,sBACA,oCACA,iDACA,oBACA,SACA,CAEA,eACA,OACA,sBAEA,cACA,cACA,aACA,mBAEA,SACA,mBACA,WACA,gBAEA,wBACA,WACA,WAGA,uBAEA,GAEA,iBACA,OACA,wBAEA,gBACA,cACA,cAEA,gBAAuB,MAAkB,OACzC,iBACA,SAIA,gBACA,CAEA,oBACA,cACA,aACA,UAGA,SACA,mBACA,WACA,gBAEA,aACA,UACA,WAGA,kBACA,MACA,+BACA,WACA,WAEA,iBACA,IAEA,OACA,aAIA,GAEA,kBACA,wBACA,SACA,UACA,SACA,CAEA,UACA,oBAEA,2CAEA,2BACA,aACA,cAEA,YACA,SACA,SAEA,8BACA,2CAEA,oBACA,aACA,cACA,gCAEA,mBAAuB,EAAiB,IACxC,gBACA,OACA,YACA,oBACA,YACA,KACA,MAEA,CAEA,cACA,WAAuB,eAAuB,OAC9C,YACA,gCAGA,SACA,QAEA,gBACA,WAAuB,eAAuB,OAC9C,YACA,iCAGA,SACA,QAEA,eACA,WAAuB,eAAuB,OAC9C,YACA,+CAGA,SACA,QACA,EAEA,6BC9RA,aAeA,eACA,SACA,OACA,2CAEA,gCAEA,GACA,cACA,aACA,gCACA,yBACA,MAEA,QAEA,YAGA,MACA,2BAAmB,EAAU,IAC7B,kBACA,eACA,oBACA,gBAEA,gBAKA,eACA,4BAAmB,EAAU,IAC7B,kBACA,KACA,YACA,gBAEA,QAKA,iCACA,wBACA,0BACA,kEAAmB,EAAU,IAC7B,kBACA,eACA,cACA,gBAEA,sBAEA,EAIA,YAAmB,EAAU,IAC7B,kBACA,KACA,eACA,gBAEA,MAIA,MACA,QAOA,CACA,eACA,SACA,cACA,6BACA,oCACA,iBACA,kCAMA,CAtGA,QAEA,MACA,MACA,QAQA,GAwGA,UAbA,aACA,MAEA,gBACA,kCACA,IAEA,OAGA,2BACA,6CCpHA,aAGA,aACA,wBACA,yBAEA,qBANA,aAQA,mBACA,OACA,MACA,KACA,KAEA,oBACA,OACA,MACA,KACA,sB9CZA,aAEA,WA6NA,UACA,CACA,UAzMA,WACA,IACA,mBACA,iBACA,iBACA,aAqMA,IAnMA,aACA,wBACA,yBACA,QACA,+BAEA,iBACA,iBAEA,QA2LA,SAzLA,aACA,wBACA,yBACA,QACA,+BACA,sBACA,iBACA,QAmLA,SAjLA,aACA,wBACA,yBACA,QACA,+BAEA,sBAEA,cACA,qBAEA,WAEA,mBACA,kBAIA,MAgKA,YA9JA,aACA,SACA,iBACA,QA4JA,UA1JA,aACA,SACA,iBACA,QAwJA,KAtJA,WACA,OACA,4BAEA,4BACA,iCACA,eACA,cACA,SACA,WACA,aAAuB,EAAU,IACjC,YAIA,qBACA,WACA,aAAuB,EAAU,IACjC,YAKA,QACA,aACA,aAAmB,EAAU,IAC7B,cAIA,mBACA,UACA,SACA,WAAuB,EAAO,IAC9B,SAIA,QACA,UAgHA,IA9GA,aACA,wBACA,yBACA,6BACA,UACA,aAAmB,EAAQ,IAC3B,cAAuB,EAAQ,IAC/B,oBACA,QAGA,QAIA,QACA,UA+FA,IA7FA,aACA,wBACA,yBACA,6BACA,UACA,aAAmB,EAAQ,IAC3B,cAAuB,EAAQ,IAC/B,oBACA,QAGA,QAIA,QACA,UA8EA,MArBA,aACA,UACA,UAoBA,IAlBA,WACA,OACA,mBACA,MACA,WAeA,KA9EA,WACA,IACA,yBACA,2BACA,UACA,aAAmB,EAAQ,IAC3B,cAAuB,EAAQ,IAC/B,cAIA,SACA,UAmEA,IAnDA,WACA,IACA,yBACA,2BACA,UACA,aAAmB,EAAQ,IAC3B,cAAuB,EAAQ,IAC/B,cAGA,SACA,UAyCA,OAvCA,aACA,IACA,sDAGA,UACA,aAAmB,EAAQ,IAC3B,cAAuB,EAAQ,IAC/B,cAGA,WACA,UA4BA,IAnEA,WACA,IACA,yBACA,2BACA,UACA,aAAmB,EAAQ,IAC3B,cAAuB,EAAQ,IAC/B,cAIA,SACA,UAwDA,OA5OA,aACA,OACA,aA2OA,KAzOA,aACA,UACA,WAwOA,MAlOA,aACA,UACA,YAiOA,OA/NA,aACA,UACA,WA8NA,IAxOA,aACA,UACA,wB+CrBA,uBACA,aACA,SACA,IACA,IACA,IAAmB,EAAS,IAC5B,YACA,aACA,0BAEA,gBACA,mBCXA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,cAEA,YACA,mBCPA,uBACA,aACA,SACA,IACA,IACA,IACA,IAAmB,EAAS,IAC5B,YACA,aACA,aACA,0BAEA,gBACA,qBCbA,uBACA,aACA,SACA,IACA,IAAmB,EAAS,IAC5B,cACA,gBAEA,YACA,mBCTA,uBACA,aACA,SACA,IACA,IAAmB,EAAS,IAC5B,cACA,cAEA,cACA,kBCTA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,oCAEA,OACA,uBCPA,uBACA,aACA,SACA,IACA,IACA,IAAmB,EAAS,IAC5B,YACA,aACA,aAEA,oBACA,oBCXA,aAEA,uBACA,WACA,IACA,IAAmB,MAAc,OACjC,cACA,cAEA,WACA,qBCVA,yBACA,MACA,WACA,IACA,IAAuB,MAAc,OACrC,aACA,cAEA,WACA,OACA,EACA,GAEA,aACA,SACA,IACA,IACA,IAAuB,EAAS,IAChC,OACA,QACA,eAEA,0BAEA,yBCxBA,aAEA,QAEA,WACA,cAEA,OAWA,eACA,kBACA,4BACA,iCACA,8BACA,0BACA,kCAEA,0BACA,2BAEA,sDACA,wDAEA,8CACA,cACA,WACA,6BACA,cACA,WAEA,IAEA,8BACA,0BAKA,uCACA,kCAEA,sCACA,iBACA,UAEA,GAOA,WACA,wCACA,GAGA,oBAFA,6BACA,SASA,qBACA,2BACA,kBAEA,kBACA,+DACA,UAKA,SACA,qCACA,8CACA,uCACA,SAMA,SACA,OACA,OACA,uBACA,0BACA,+BACA,4BACA,wBACA,kBACA,SAEA,EAOA,eACA,IACA,uCAEA,gDACA,SAEA,EAEA,yBzD1HA,aAEA,aACA,eACA,KAEA,eACA,oBACA,gBAyDA,WAFA,IAnCA,QACA,MACA,8BAGA,cACA,YACA,oBAEA,YACA,CACA,mCAEA,cACA,iBACA,0BAEA,aACA,sBACA,mCAEA,aACA,qBACA,wBAEA,YACA,qBACA,2BAEA,WACA,8BACA,iCAEA,YACA,+BAIA,yBACA,0CAEA,eACA,qBACA,6BAEA,yBACA,uBACA,4BAEA,qBACA,CACA,0CAEA,sBACA,CACA,WAzEA,aACA,OACA,aAEA,QACA,YAGA,UAmEA,SAjEA,aACA,OACA,aAEA,QAEA,QA6DA,6B0DvFA,aAEA,QAMA,GAgDA,UACA,CACA,YAlBA,WACA,QAAmB,MAAc,kBACjC,IAAmB,EAAO,OAC1B,aACA,UACA,aACA,KAIA,WACA,CACA,SAEA,YAKA,OAnCA,WACA,uBACA,WAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,aAGA,QACA,QAOA,EAqBA,OAnDA,WACA,0BACA,KAAmB,MAAiB,KACpC,cAAuB,MAAoB,QAC3C,aAGA,QACA,QAMA,oBCvBA,aAKA,aACA,QACA,WACA,sBACA,OACA,YARA,UACA,aASA,gBAEA,0CCVA,aACA,MACA,yBAEA,gBAEA,uBACA,YACA,SACA,UACA,eAEA,QAAe,EAAO,QACtB,OACA,MAAmB,IAAO,IAC1B,iBAEA,kBACA,KACA,cAEA,IAAuB,IAAO,IAC9B,IAEA,wBACA,MAA2B,EAAO,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,CACA,MACA,EAEA,MACA,UACA,uBA1CA,IA4CA,YACA,kBACA,OAEA,0BACA,OAEA,UACA,yBAEA,6CACA,6BAGA,oCACA,YACA,YACA,cAEA,QAAmB,EAAO,IAC1B,UAAuB,EAAW,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OAEA,SAAuB,EAAQ,SAC/B,OAAuB,EAAW,IAClC,kBAEA,eAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OAEA,8BACA,EACA,uBACA,mBACA,UAAuB,EAAa,IACpC,OACA,kBAGA,SACA,QACA,6BACA,YACA,OACA,aACA,YACA,QAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,YACA,IACiB,QACjB,WAEA,SAIA,EACA,QACA,wBACA,YACA,OACA,SACA,aACA,gBAEA,UAA6B,EAAQ,SACrC,OAAuB,EAAU,IACjC,YAEA,cACA,EAAuB,IAAa,IACpC,mBACA,OACA,EAA+B,IAAU,IACzC,eAGA,iBAEA,QAA+B,IAAU,IACzC,eAEA,OAEA,CACA,CACA,QAGA,uCCjJA,eACA,MACA,yBAEA,kBAEA,iBAEA,cACA,SACA,UAEA,YACA,yCACA,2CACA,mBAEA,cACA,KACA,OACA,SAiBA,gBAhBA,OAEA,qBACS,8FACT,KACA,gBACA,SACA,QACA,QACA,KACA,IACA,GAEA,iBAIA,qBACA,kBACA,KACA,WAEA,eACA,eAEA,0BACA,oBAEA,YAAyC,OAAS,QAClD,QACA,UACA,EAAuB,IAAO,IAC9B,uBAEA,qBACA,KACA,kBAEA,MAA2B,IAAO,IAClC,aAEA,cACA,CACA,OACA,IAEA,SAAuB,EAAO,QAC9B,kBACA,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,MACA,OAEA,OACA,QAAuB,IAAO,IAC9B,YAIA,eACA,UACA,MAA2B,EAAO,IAClC,uBAEA,kBACA,KACA,kBAEA,UAA+B,EAAO,IACtC,UAEA,aACA,CACA,UACA,qBACA,SAA+B,EAAO,IACtC,SAEA,UAA+B,EAAO,IACtC,YAAmC,EAAO,IAC1C,eAGA,gBAA+B,EAAO,IACtC,oBACA,OAAmC,EAAO,IAC1C,eAGA,IACA,CACA,aAA+B,EAAO,IACtC,YAGA,IACA,CAEA,YACA,GACA,WAEA,SACA,aAEA,KACA,kBAEA,WAEA,IACA,KAAqB,IAAQ,QAC7B,OAAuB,EAAO,IAC9B,YAEA,UACA,CACA,SAAyB,EAAQ,KACjC,gBACA,SAA+B,EAAQ,QACvC,OACA,EAA+B,IAAO,IACtC,eAEA,iBACA,QAA+B,IAAO,IACtC,eAEA,OACA,KAA2B,IAAO,IAClC,aAEA,sBACA,UAA2B,MAAW,EACtC,YAEA,CAAa,KACb,OAA2B,EAAO,IAClC,YAEA,UACA,CAEA,CAEA,CACA,aAAuB,EAAQ,SAC/B,SACA,iBAA+B,EAAO,QACtC,OACA,MAAmC,EAAO,IAC1C,eAEA,qBACA,UAAmC,EAAO,IAC1C,eAEA,OAEA,OAAuB,EAAO,IAC9B,YAEA,UACA,CAGA,aACA,IACA,EACA,6BACA,SAAuB,GAAS,OAIhC,MAHA,sCAIA,MACA,EACA,KAEA,UACA,IACS,MACT,SAA4B,EAAS,MAIrC,MAHA,oCAIA,0BACA,MACA,EACA,KAEA,CACA,QACa,QACb,IAEA,KACA,EAEA,IAEA,CAGA,OADA,cAEA,WACA,UACA,MAA+B,EAAQ,KACvC,IASA,cARA,UACA,SACA,IACA,OACA,iBACA,gBAEA,YACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,WACA,UACA,EAA2B,IAAO,IAClC,IAOA,cANA,UACA,SACA,IACA,YACA,YACA,aACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,0DACA,aACA,WACA,WACA,OACA,SACA,2BACA,SACA,OACA,UACA,aACA,OACA,QAEA,SAEA,eACA,SACA,IAA2B,QAAW,MACtC,CAWA,SAVA,YACA,MACA,IACA,YAEA,iBACA,mBACA,aACA,gBACA,WACmC,EAAO,IAC1C,yBACA,iCACA,GAGA,mBACA,YACA,MACA,IACA,sBACA,wBACA,WACA,gBACA,UACA,QAAmC,EAAO,IAC1C,yBACA,iCACA,GAGA,SACA,KAEA,SACA,KACA,QACA,IACA,4BAEA,WAAmC,EAAS,KAC5C,aAIA,aACA,iBAGA,WACA,cACA,OACA,YACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,oBACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,UAEA,MACA,EACA,IACA,KAGA,EAEA,MACA,IACA,KACA,IACA,GAEA,MACA,SACA,SACA,SACA,SACA,mBAhYA,IAkYA,YACA,gBACA,0CACA,EACA,aACA,eACA,EACA,YAEA,mCACA,2BACA,SACA,UAAsC,OAAQ,IAC9C,IACA,QAGA,IACA,QACA,gBACA,aACA,CAEA,iBACA,wDACA,EACA,2BACA,0BACA,yBAEA,SACA,CACA,4BACA,0BACA,yBAEA,SACA,CACA,sBACA,sBACA,EACA,mBAEA,CACA,WACA,mBACA,aACA,WAEA,QAAmB,EAAW,IAC9B,mBACA,SAEA,SAIA,gBACA,SAEA,yBACA,YACA,SACA,aACA,eAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,UACA,OACA,8BACA,uBACA,QACA,oBACA,YACA,SACA,cACA,cACA,0BACA,UAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,IAClC,mBACA,qBAEA,KAKA,aAEA,MACA,cACA,YACA,YAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,CACA,QAGA,0BC7fA,aAEA,UAQA,KA4FA,kBAhEA,iBACA,WAAmB,MAAiB,OACpC,mBAEA,qBACA,QASA,EAmDA,gBAlDA,eACA,cAGA,iBACA,WACA,WAAmB,EAAO,QAC1B,MACA,cACA,YAAuB,EAAU,IACjC,YAEA,CAGA,WAAmB,MAAiB,WACpC,GACA,kBAAyB,EAAY,IACrC,gBAEA,OAGA,WAAoB,EAAQ,IAC5B,cAAuB,EAAU,IACjC,aAGA,KACA,QAUA,EAYA,0BA7FA,aACA,mBACA,UAAmB,MAAiB,OACpC,WAAuB,SAAiB,WACxC,CACA,oBAEA,SACA,oBAEA,wBACA,MACA,UACA,SAEA,CACA,QAUA,EAoEA,YAZA,iBACA,WAAmB,MAAoB,OACvC,cACA,QAGA,SACA,2BCpGA,aAgBA,6BAiiDA,eACA,oBACA,6BAEA,oCAEA,gBACA,OACA,IAMA,gBAmNA,QACA,8CAEA,MACA,QAEA,gBA9vDA,yBACA,6BACA,OACA,KASA,0BACA,IACA,QACA,4BAEA,4DACA,aAA6B,EAAe,IAC5C,cAAoC,EAAqB,IACzD,gBAGA,QACA,QAOA,oBACA,wBACA,UAA2B,MAAoB,OAC/C,cAEA,MACA,QAOA,uBACA,6BACA,KAA2B,MAAoB,OAC/C,cAEA,MACA,QAQA,kBACA,WACA,UAQA,kBACA,6BACA,EAQA,iBACA,6BACA,EASA,mBACA,qBACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,cAGA,KACA,QAUA,wBACA,cACA,2BACA,uBACA,aAA2B,EAAU,IACrC,cAA+B,IAAa,IAC5C,QACA,SAGA,WACA,QASA,kBACA,cACA,oBACA,aACA,cACA,aAA2B,EAAS,IACpC,MAEA,WACA,QASA,mBACA,SACA,oBACA,kBACA,eACA,gBACA,aAA2B,EAAS,IACpC,cAEA,MACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAQA,gBACA,QACA,sBACA,2BACA,SACA,aACA,aAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,6BAGA,WACA,QAOA,sBACA,2BACA,QAOA,mBACA,iBACA,kBAKA,WACA,uBACA,OAOA,SACA,IACA,yCAEA,8CACA,YACA,UAA2B,EAAQ,IACnC,cAA+B,EAAQ,IACvC,WAGA,gBACA,KAMA,YACA,sBACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,6BAGA,SACA,QAMA,YACA,sBACA,QAA2B,SAAe,SAC1C,iBACA,mBAA+B,SAAkB,QACjD,iBAEA,QACA,CACA,QAKA,cACA,OACA,cAKA,iBACA,OACA,iBAKA,WACA,uBACA,gBAKA,WACA,yBACA,OAKA,cACA,oBACA,WAA+B,SAAe,KAC9C,cAAmC,EAAQ,KAC3C,4BACA,SAIA,SACA,QACA,CACA,QAUA,MACA,iBACA,8BASA,MACA,iBACA,8BAYA,YACA,MACA,OACA,kEACA,aAA2B,EAAY,IACvC,cAA+B,EAAY,IAC3C,yCAGA,WACA,QAOA,QACA,WAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SAGA,iBACA,KAMA,MACA,mBACA,EAOA,UACA,iBACA,6BACA,WAA2B,SAAkB,QAC7C,cAEA,SACA,QAOA,gBACA,wCACA,UAQA,YACA,iBACA,2BACA,kBAA2B,SAAkB,QAC7C,iBAEA,YACA,KAQA,cACA,iBACA,wBACA,kBAA2B,WAAkB,QAC7C,WACA,2BACA,eAEA,iBACA,KAOA,aACA,oBACA,6BACA,QAA2B,SAAe,KAC1C,cAEA,SACA,QAOA,mBACA,2CACA,aAQA,eACA,oBACA,8BACA,kBAA2B,SAAe,KAC1C,iBAEA,YACA,KAQA,iBACA,oBACA,2BACA,kBAA2B,WAAe,KAC1C,WACA,2BACA,eAEA,iBACA,KAOA,gBACA,oBACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,oBACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,oBACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,gBACA,oBACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,uBACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,uBACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,uBACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAOA,mBACA,uBACA,kBAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,+BAGA,YACA,KAQA,YACA,iBACA,kBAA2B,SAAkB,QAC7C,sBAEA,kBACA,KAQA,eACA,oBACA,kBAA2B,SAAe,KAC1C,sBAEA,kBACA,KAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBAIA,UACA,QAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,SACA,oBACA,WACA,OAIA,MACA,QAOA,UACA,iBACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,iBACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,UACA,iBACA,6BACA,KAA2B,SAAkB,QAC7C,SACA,oBAGA,UACA,QAOA,eACA,iBACA,6BACA,QACA,KAA2B,SAAkB,QAC7C,SACA,oBACA,WAGA,MACA,QAOA,aACA,oBACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,oBACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAOA,aACA,oBACA,2BACA,OAA2B,SAAe,KAC1C,SACA,oBAGA,UACA,QAOA,kBACA,oBACA,2BACA,QACA,OAA2B,SAAe,KAC1C,SACA,oBACA,WAGA,MACA,QAMA,OACA,4BACA,WACA,WAA2B,EAAS,IACpC,cAEA,SACA,QAQA,OAEA,OACA,qBACA,MACA,2BAEA,eAEA,KAMA,OACA,wBACA,IAMA,OACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YAGA,SACA,QAMA,gBACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,YACA,cAGA,iBACA,KAOA,OACA,qBACA,wBACA,4BACA,4BAEA,+CACA,IAA2B,MAAoB,OAC/C,YAEA,KACA,QAOA,QACA,oBACA,gCAEA,mBAGA,oGACA,YACA,YAEA,sCAEA,gBACA,WAA2B,EAAO,QAClC,WAA+B,EAAO,IACtC,WAGA,mBAA+B,IAAO,QACtC,OACA,IAA+B,EAAO,IACtC,qBAGA,OACA,UACA,CACA,CACA,QAEA,eACA,8CACA,sBACA,aACA,gBACA,aACA,gBACA,aACA,gBACA,aAGA,YACA,QACA,YACA,UACA,QACA,OAcA,eAJA,EALA,aADA,cAOA,EALA,aAMA,EALA,aAMA,EAJA,aARA,OAeA,eACA,8CAEA,sBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBACA,gBAEA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aACA,aAEA,YAEA,kBAEA,gBACA,QACA,gBACA,iBACA,cACA,kBAGA,gBACA,OACA,aACA,kBACA,gBACA,cACA,MA0BA,eATA,EAVA,IANA,aAiBA,GAnCA,gBAyBA,sBAWA,EAVA,OAjBA,gCA4BA,EAVA,KAzBA,mCAoCA,EAVA,QATA,aAoBA,EAVA,QATA,aAoBA,EAVA,SApBA,+BA+BA,EAVA,QAVA,aAqBA,EATA,QAVA,MA2BA,gBACA,kBAaA,SACA,SACA,kBACA,MAEA,iBACA,WAGA,4BAFA,IASA,oBAQA,YACA,gBAIA,gBACA,oBACA,eACiB,IACjB,gBACA,aACiB,MACjB,mBACA,aAGA,0BACA,wBAEA,2BACA,2BAEA,mCACA,mCAEA,gCACA,gCAEA,wCACA,wCAGA,oBACA,oBACA,wBACA,sBACA,oBACA,iCACA,+BAGA,kBACA,WACA,SACA,eACA,aACA,aACA,WACA,SAGA,kCACA,qCACA,6BACA,0BACA,qCACA,+BACA,EACA,YA9FA,YACA,SACA,YACA,SACA,QAEA,oBAA4C,gBAAQ,OAAU,SAAQ,OAKtE,2CAkBA,SACA,gBACA,WAGA,SA6DA,UAQA,eACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAe,KAC1C,8BAA+D,MAC/D,UAEA,YACA,QAWA,kBACA,iBACA,iBACA,IACA,0BAEA,2FACA,WAA2B,WAAkB,QAC7C,gCACA,CACA,MAEA,UAEA,eACA,QASA,oBACA,oBAEA,8BACA,YACA,YACA,SAEA,mDACA,OAA2B,EAAO,IAClC,cAA+B,EAAO,IACtC,cAAmC,EAAO,IAC1C,cAAuC,EAAO,IAC9C,oCAKA,SACA,QAMA,YACA,kEACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,mBAGA,UACA,QAOA,YACA,cACA,eAA2B,SAAe,KAC1C,iCAEA,eACA,KAOA,eACA,cACA,eAA2B,SAAkB,QAC7C,uCAEA,eACA,KAUA,mBACA,cACA,uEACA,GAAkC,IAAa,KAC/C,WAAyC,KAAgB,KACzD,qBAGA,SACA,QASA,oBACA,mBACA,+BACA,2CACA,6BAGA,qFACA,KAA2B,MAAoB,OAC/C,WAAyC,KAAgB,SACzD,uBACA,qDAEA,2BACA,QAEA,CACA,QASA,uBACA,mBACA,4BACA,wCACA,0BAGA,gFACA,UAA2B,MAAoB,OAC/C,WAAsC,KAAa,SACnD,uBACA,2DAEA,6BACA,MAEA,CACA,QASA,oBACA,oBACA,8BACA,gBACA,eACA,wBAA2B,MAAiB,KAC5C,cAA+B,MAAoB,QACnD,qBAGA,eACA,KAQA,eACA,0BACA,4DACA,UAA2B,YAAwB,WACnD,KACA,iBAA+B,eAA2B,OAC1D,QACA,uBAEA,QACA,CACA,QAMA,QACA,4BACA,WACA,IAA2B,EAAS,IACpC,YAEA,SACA,QAUA,gBACA,cACA,KAOA,WACA,wBACA,cACA,OAOA,cACA,2BACA,cACA,OAMA,cACA,cACA,KAMA,iBACA,cACA,KAUA,uBACA,cACA,aAWA,mBACA,cACA,SASA,MACA,oBACA,WACA,KAEA,qCACA,gBACA,gBACA,gBAEA,OACiB,wBAEjB,SACA,gBACA,kCACA,kCACA,wCACA,gBACA,gBAEA,2BACA,KAEA,oBAGA,WACA,aAEA,0DAOA,iBACA,cACA,2BAEA,uBACA,wBACA,yBAEA,WAA2B,MAAc,OACzC,WACA,UAOA,iDACA,wBACA,iBAGA,oBAQA,oBAgBA,kBACA,sCACA,kBACA,mCACA,0CACA,qDAMA,UAOA;;;;;IAWA;;;;;;;;;IAaA;;;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAOA;;;;;IAWA;;;;;;;;;IAQA;;;;;IAUA;;;;;;;;;IAaA;;;;;;;;;;;IAOA;;;;;EAEA,IAgBA,4OAEA,iBACA,iBAAoE,eACpE,kBAA2E,mBAC3E,kBAA2E,mBAC3E,kBAAkE,OAClE,YAAmB,MAAqB,OACxC,gBACA,yBACA,wBACA,SAEA,OAEA,IAIA,iBAIA,+NACA,SACA,aAEA,EAhtDA,gBAitDA,iBAAoE,mBACpE,kBAAkE,OAClE,YAAmB,MAAmB,OACtC,gBACA,UAEA,OAEA,IAIA,yCACA,OACA,aAAmB,MAAsB,GACzC,OAA4B,SAE5B,eACA,gBACA,QACA,YACA,GAEA,sBAAsF,UACtF,gBAAuB,MAA0B,OACjD,gBACA,UAEA,OAAS,KACT,OACA,QACA,GACA,gBAEA,WACA,eACA,eACA,eACA,cAAuB,MAA0B,OACjD,gBACA,yBACA,wBACA,SAEA,OACA,CAEA,CAQA,SAvxDA,YAEA,QACA,QACA,QACA,QACA,QACA,SACA,SACA,SACA,SACA,SACA,+BCdA,aAKA,aACA,MACA,yBAGA,qBAEA,uBACA,YACA,SACA,UACA,WACA,cACA,MAEA,QAAe,EAAU,IACzB,IAGA,aAEA,WAAe,EAAa,QAE5B,OAAmB,EAAU,IAC7B,SAGA,cAAmB,EAAU,QAC7B,OACA,OACA,SACA,IAAuB,EAAU,IACjC,YAEA,UACA,OAEA,KACA,QAAuB,EAAU,IACjC,cACA,QAIA,cACA,OAAuB,EAAa,IACpC,MACA,gBACA,QAGA,YACA,UACA,KAEA,SACA,EAEA,SACA,oBAA2B,EAAU,IACrC,aAGA,OAEA,MACA,UACA,mBACA,YAvEA,QAEA,GAuEA,YACA,sBACA,gBACA,OACA,UAAuB,EAAS,IAChC,OACA,YAGA,SACA,QACA,mBACA,YACA,SACA,2BAEA,sDACA,UAAuB,EAAS,IAChC,OAEA,QACA,QACA,6BACA,gBACA,OACA,SACA,gBACA,cAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,IACiB,QACjB,MAEA,EAIA,EACA,QACA,6BACA,gBACA,OACA,SACA,gBACA,cAAuB,EAAU,IACjC,cAA2B,EAAa,IACxC,YACA,KAEA,QAIA,EACA,QACA,8BACA,yBACA,OACA,mBACA,YAEA,0BACA,OAEA,cACA,qBAEA,qCACA,6BAGA,iCACA,8CACA,OACA,YAEA,QAAmB,EAAa,IAChC,YAA2B,EAAa,IACxC,UAA2B,EAAW,IACtC,qBAIA,gBAA6B,EAAQ,SACrC,OAAuB,EAAW,IAClC,aAEA,cAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OACA,CACA,QACA,GAEA,6BC7KA,aAQA,eACA,MACA,yBAEA,uBAEA,iBAEA,cACA,SACA,UAEA,YACA,yCACA,2CACA,mBAEA,cACA,KACA,OACA,SAiBA,gBAhBA,OAEA,qBACS,8FACT,KACA,gBACA,SACA,QACA,QACA,KACA,IACA,GAEA,iBAIA,cACA,WACA,KACA,WAEA,eACA,eAEA,0BACA,oBAEA,YAAyC,OAAS,QAClD,QACA,UACA,EAAuB,IAAO,IAC9B,gBAEA,qBACA,KACA,kBAEA,MAA2B,IAAO,IAClC,aAEA,cACA,CACA,OACA,IAEA,SAAuB,EAAO,QAC9B,kBACA,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,MACA,OAEA,OACA,QAAuB,IAAO,IAC9B,YAIA,eACA,UACA,MAA2B,EAAO,IAClC,gBAEA,kBACA,KACA,kBAEA,UAA+B,EAAO,IACtC,UAEA,aACA,CACA,UACA,qBACA,SAA+B,EAAO,IACtC,SAEA,UAA+B,EAAO,IACtC,YAAmC,EAAO,IAC1C,eAGA,gBAA+B,EAAO,IACtC,oBACA,OAAmC,EAAO,IAC1C,eAGA,IACA,CACA,aAA+B,EAAO,IACtC,YAGA,IACA,CAEA,YACA,GACA,WAEA,SACA,aAEA,KACA,kBAEA,WAEA,IACA,KAAqB,IAAQ,QAC7B,OAAuB,EAAO,IAC9B,YAEA,UACA,CACA,SAAyB,EAAQ,KACjC,gBACA,SAA+B,EAAQ,QACvC,OACA,EAA+B,IAAO,IACtC,eAEA,iBACA,QAA+B,IAAO,IACtC,eAEA,OACA,KAA2B,IAAO,IAClC,aAEA,sBACA,UAA2B,MAAW,EACtC,YAEA,CAAa,KACb,OAA2B,EAAO,IAClC,YAEA,UACA,CAEA,CAEA,CACA,aAAuB,EAAQ,SAC/B,SACA,iBAA+B,EAAO,QACtC,OACA,MAAmC,EAAO,IAC1C,eAEA,qBACA,UAAmC,EAAO,IAC1C,eAEA,OAEA,OAAuB,EAAO,IAC9B,YAEA,UACA,CAGA,aACA,IACA,EACA,6BACA,SAAuB,GAAS,OAIhC,MAHA,sCAIA,MACA,EACA,KAEA,UACA,IACS,MACT,SAA4B,EAAS,MAIrC,MAHA,oCAIA,0BACA,MACA,EACA,KAEA,CACA,QACa,QACb,IAEA,KACA,EAEA,IAEA,CAGA,OADA,cAEA,WACA,UACA,MAA+B,EAAQ,KACvC,IASA,OARA,UACA,SACA,IACA,OACA,iBACA,gBAEA,YACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,WACA,UACA,EAA2B,IAAO,IAClC,IAOA,OANA,UACA,SACA,IACA,YACA,YACA,aACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,0DACA,aACA,WACA,WACA,OACA,SACA,2BACA,SACA,OACA,UACA,aACA,OACA,QAEA,SAEA,eACA,SACA,IAA2B,QAAW,MACtC,CAWA,KAVA,SACA,MACA,IACA,YAEA,iBACA,mBACA,aACA,gBACA,WACmC,EAAO,IAC1C,yBACA,iCACA,GAGA,eACA,SACA,MACA,IACA,sBACA,wBACA,WACA,gBACA,UACA,QAAmC,EAAO,IAC1C,yBACA,iCACA,GAGA,SACA,KAEA,SACA,KACA,QACA,IACA,4BAEA,WAAmC,EAAS,KAC5C,aAIA,aACA,iBAGA,WACA,cACA,OACA,YACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,oBACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,UAEA,MACA,EACA,IACA,KAGA,EAEA,MACA,IACA,KACA,IACA,GAEA,MACA,SACA,SACA,SACA,SACA,IArYA,QACA,OACA,QACA,eAEA,iBAkYA,YACA,gBACA,0CACA,EACA,aACA,eACA,EACA,YAEA,mCACA,2BACA,SACA,UAAsC,OAAQ,IAC9C,IACA,QAGA,IACA,QACA,gBACA,aACA,CAEA,iBACA,wDACA,EACA,2BACA,+BACA,8BAEA,SACA,CACA,4BACA,+BACA,8BAEA,SACA,CACA,sBACA,2BACA,EACA,mBAEA,CACA,WACA,mBACA,kBACA,WAEA,QAAmB,EAAW,IAC9B,mBACA,SAEA,SAIA,gBACA,SAEA,yBACA,YACA,SACA,kBACA,eAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,UACA,OACA,8BACA,4BACA,QACA,oBACA,YACA,SACA,cACA,cACA,+BACA,UAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,IAClC,mBACA,qBAEA,KAKA,aAEA,MACA,cACA,eACA,cAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,CACA,QACA,GAEA,6BCjgBA,aAeA,eAEA,kBACA,oCAEA,uBAWA,CA0DA,iBACA,WACA,KAGA,IAAkB,QAAoB,WACtC,QACA,aAAsB,mBAA8B,EACpD,6CAGA,MACA,KACA,MACA,IAEA,IAEA,CACA,QAKA,CA6BA,mBACA,OACA,iBACA,OAOA,CACA,eACA,aAEA,UACA,UACA,OAAmB,MAAc,OACjC,eACA,gBACA,EAEA,OAEA,cACA,WACA,eAAc,EAAa,IAC3B,eACA,aAEA,QAAc,MAAY,KAC1B,6BACA,aAEA,QACA,SA9KA,QACA,UAEA,uBACA,UAQA,kBAkBA,+BACA,gBACA,yBAGA,QAFA,oBAGA,4BAEA,gFACA,iBACA,2BACA,kBAAkB,MAA6B,WAC/C,qBACA,mCAEA,wBACA,0BAEA,QACA,eAAsB,eAAsB,EAC5C,UACA,qBAGA,YACA,UAEA,MACA,wBAOA,EACA,+BACA,iDACA,4BAEA,iFAEA,UAAkB,MAAwB,OAC1C,gCAGA,wBACA,QASA,EA0BA,6BACA,OACA,WACA,wBACA,kCAEA,uBAMA,EACA,kBACA,IACA,gDAEA,qCACA,YASA,gCCzIA,aACA,MACA,yBAEA,gBAEA,uBACA,YACA,SACA,UACA,eAEA,QAAe,EAAO,QACtB,OACA,MAAmB,IAAO,IAC1B,iBAEA,kBACA,KACA,cAEA,IAAuB,IAAO,IAC9B,IAEA,wBACA,MAA2B,EAAO,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,CACA,MACA,EAEA,MACA,UACA,uBA1CA,IA4CA,YACA,kBACA,OAEA,0BACA,OAEA,UACA,yBAEA,6CACA,6BAGA,oCACA,YACA,YACA,cAEA,QAAmB,EAAO,IAC1B,UAAuB,EAAW,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OAEA,SAAuB,EAAQ,SAC/B,OAAuB,EAAW,IAClC,kBAEA,eAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OAEA,8BACA,EACA,uBACA,mBACA,UAAuB,EAAa,IACpC,OACA,kBAGA,SACA,QACA,6BACA,YACA,OACA,aACA,YACA,QAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,YACA,IACiB,QACjB,WAEA,SAIA,EACA,QACA,wBACA,YACA,OACA,SACA,aACA,gBAEA,UAA6B,EAAQ,SACrC,OAAuB,EAAU,IACjC,YAEA,cACA,EAAuB,IAAa,IACpC,mBACA,OACA,EAA+B,IAAU,IACzC,eAGA,iBAEA,QAA+B,IAAU,IACzC,eAEA,OAEA,CACA,CACA,QAGA,uCCjJA,eACA,MACA,yBAEA,kBAEA,iBAEA,cACA,SACA,UAEA,YACA,yCACA,2CACA,mBAEA,cACA,KACA,OACA,SAiBA,gBAhBA,OAEA,qBACS,8FACT,KACA,gBACA,SACA,QACA,QACA,KACA,IACA,GAEA,iBAIA,qBACA,kBACA,KACA,WAEA,eACA,eAEA,0BACA,oBAEA,YAAyC,OAAS,QAClD,QACA,UACA,EAAuB,IAAO,IAC9B,uBAEA,qBACA,KACA,kBAEA,MAA2B,IAAO,IAClC,aAEA,cACA,CACA,OACA,IAEA,SAAuB,EAAO,QAC9B,kBACA,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,MACA,OAEA,OACA,QAAuB,IAAO,IAC9B,YAIA,eACA,UACA,MAA2B,EAAO,IAClC,uBAEA,kBACA,KACA,kBAEA,UAA+B,EAAO,IACtC,UAEA,aACA,CACA,UACA,qBACA,SAA+B,EAAO,IACtC,SAEA,UAA+B,EAAO,IACtC,YAAmC,EAAO,IAC1C,eAGA,gBAA+B,EAAO,IACtC,oBACA,OAAmC,EAAO,IAC1C,eAGA,IACA,CACA,aAA+B,EAAO,IACtC,YAGA,IACA,CAEA,YACA,GACA,WAEA,SACA,aAEA,KACA,kBAEA,WAEA,IACA,KAAqB,IAAQ,QAC7B,OAAuB,EAAO,IAC9B,YAEA,UACA,CACA,SAAyB,EAAQ,KACjC,gBACA,SAA+B,EAAQ,QACvC,OACA,EAA+B,IAAO,IACtC,eAEA,iBACA,QAA+B,IAAO,IACtC,eAEA,OACA,KAA2B,IAAO,IAClC,aAEA,sBACA,UAA2B,MAAW,EACtC,YAEA,CAAa,KACb,OAA2B,EAAO,IAClC,YAEA,UACA,CAEA,CAEA,CACA,aAAuB,EAAQ,SAC/B,SACA,iBAA+B,EAAO,QACtC,OACA,MAAmC,EAAO,IAC1C,eAEA,qBACA,UAAmC,EAAO,IAC1C,eAEA,OAEA,OAAuB,EAAO,IAC9B,YAEA,UACA,CAGA,aACA,IACA,EACA,6BACA,SAAuB,GAAS,OAIhC,MAHA,sCAIA,MACA,EACA,KAEA,UACA,IACS,MACT,SAA4B,EAAS,MAIrC,MAHA,oCAIA,0BACA,MACA,EACA,KAEA,CACA,QACa,QACb,IAEA,KACA,EAEA,IAEA,CAGA,OADA,cAEA,WACA,UACA,MAA+B,EAAQ,KACvC,IASA,cARA,UACA,SACA,IACA,OACA,iBACA,gBAEA,YACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,WACA,UACA,EAA2B,IAAO,IAClC,IAOA,cANA,UACA,SACA,IACA,YACA,YACA,aACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,0DACA,aACA,WACA,WACA,OACA,SACA,2BACA,SACA,OACA,UACA,aACA,OACA,QAEA,SAEA,eACA,SACA,IAA2B,QAAW,MACtC,CAWA,SAVA,YACA,MACA,IACA,YAEA,iBACA,mBACA,aACA,gBACA,WACmC,EAAO,IAC1C,yBACA,iCACA,GAGA,mBACA,YACA,MACA,IACA,sBACA,wBACA,WACA,gBACA,UACA,QAAmC,EAAO,IAC1C,yBACA,iCACA,GAGA,SACA,KAEA,SACA,KACA,QACA,IACA,4BAEA,WAAmC,EAAS,KAC5C,aAIA,aACA,iBAGA,WACA,cACA,OACA,YACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,oBACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,UAEA,MACA,EACA,IACA,KAGA,EAEA,MACA,IACA,KACA,IACA,GAEA,MACA,SACA,SACA,SACA,SACA,mBAhYA,IAkYA,YACA,gBACA,0CACA,EACA,aACA,eACA,EACA,YAEA,mCACA,2BACA,SACA,UAAsC,OAAQ,IAC9C,IACA,QAGA,IACA,QACA,gBACA,aACA,CAEA,iBACA,wDACA,EACA,2BACA,0BACA,yBAEA,SACA,CACA,4BACA,0BACA,yBAEA,SACA,CACA,sBACA,sBACA,EACA,mBAEA,CACA,WACA,mBACA,aACA,WAEA,QAAmB,EAAW,IAC9B,mBACA,SAEA,SAIA,gBACA,SAEA,yBACA,YACA,SACA,aACA,eAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,UACA,OACA,8BACA,uBACA,QACA,oBACA,YACA,SACA,cACA,cACA,0BACA,UAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,IAClC,mBACA,qBAEA,KAKA,aAEA,MACA,cACA,YACA,YAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,CACA,QAGA,uCCpaA,mBACA,WACA,UACA,YACA,WACA,QACK,WACL,CACA,MACA,mBAAuB,EAAY,IACnC,IAEA,MACA,YACA,oBACA,eAAmB,EAAY,IAC/B,cAAuB,EAAO,IAC9B,YACA,SAEA,SAKA,gBACA,oBACA,mBAEA,4BACA,IACA,sCACA,6EAxHsB,KAEtB,mBACA,mBACA,CACA,QACA,sBACA,qBACA,2BAEA,mBACA,YAEA,YAEA,YACA,OACA,YAAuB,gBAAwB,OAC/C,qCAEA,WACA,QAEA,SACA,OACA,MACA,mCACA,mBACA,yBAEA,aAEA,YACA,aACA,gBAEA,WACA,aACA,gBAEA,gBACA,OACA,MACA,KAEA,YACA,OACA,MAGA,UACA,KACA,aAAuB,sBAA8B,OACrD,MACA,GACA,6BACA,iCAEA,mBACA,sDAEA,kDAIA,iEACA,IACiB,qCACjB,MAGA,UAEA,UACA,8BAGA,IACA,WAEA,eACA,IACA,oDAEA,2CACA,YACA,+CCnFA,aACA,MACA,yBAEA,gBAEA,uBACA,YACA,SACA,UACA,eAEA,QAAe,EAAO,QACtB,OACA,MAAmB,IAAO,IAC1B,iBAEA,kBACA,KACA,cAEA,IAAuB,IAAO,IAC9B,IAEA,wBACA,MAA2B,EAAO,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,CACA,MACA,EAEA,MACA,UACA,uBA1CA,IA4CA,YACA,kBACA,OAEA,0BACA,OAEA,UACA,yBAEA,6CACA,6BAGA,oCACA,YACA,YACA,cAEA,QAAmB,EAAO,IAC1B,UAAuB,EAAW,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OAEA,SAAuB,EAAQ,SAC/B,OAAuB,EAAW,IAClC,kBAEA,eAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OAEA,8BACA,EACA,uBACA,mBACA,UAAuB,EAAa,IACpC,OACA,kBAGA,SACA,QACA,6BACA,YACA,OACA,aACA,YACA,QAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,YACA,IACiB,QACjB,WAEA,SAIA,EACA,QACA,wBACA,YACA,OACA,SACA,aACA,gBAEA,UAA6B,EAAQ,SACrC,OAAuB,EAAU,IACjC,YAEA,cACA,EAAuB,IAAa,IACpC,mBACA,OACA,EAA+B,IAAU,IACzC,eAGA,iBAEA,QAA+B,IAAU,IACzC,eAEA,OAEA,CACA,CACA,QAGA,uCCjJA,eACA,MACA,yBAEA,kBAEA,iBAEA,cACA,SACA,UAEA,YACA,yCACA,2CACA,mBAEA,cACA,KACA,OACA,SAiBA,gBAhBA,OAEA,qBACS,8FACT,KACA,gBACA,SACA,QACA,QACA,KACA,IACA,GAEA,iBAIA,qBACA,kBACA,KACA,WAEA,eACA,eAEA,0BACA,oBAEA,YAAyC,OAAS,QAClD,QACA,UACA,EAAuB,IAAO,IAC9B,uBAEA,qBACA,KACA,kBAEA,MAA2B,IAAO,IAClC,aAEA,cACA,CACA,OACA,IAEA,SAAuB,EAAO,QAC9B,kBACA,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,MACA,OAEA,OACA,QAAuB,IAAO,IAC9B,YAIA,eACA,UACA,MAA2B,EAAO,IAClC,uBAEA,kBACA,KACA,kBAEA,UAA+B,EAAO,IACtC,UAEA,aACA,CACA,UACA,qBACA,SAA+B,EAAO,IACtC,SAEA,UAA+B,EAAO,IACtC,YAAmC,EAAO,IAC1C,eAGA,gBAA+B,EAAO,IACtC,oBACA,OAAmC,EAAO,IAC1C,eAGA,IACA,CACA,aAA+B,EAAO,IACtC,YAGA,IACA,CAEA,YACA,GACA,WAEA,SACA,aAEA,KACA,kBAEA,WAEA,IACA,KAAqB,IAAQ,QAC7B,OAAuB,EAAO,IAC9B,YAEA,UACA,CACA,SAAyB,EAAQ,KACjC,gBACA,SAA+B,EAAQ,QACvC,OACA,EAA+B,IAAO,IACtC,eAEA,iBACA,QAA+B,IAAO,IACtC,eAEA,OACA,KAA2B,IAAO,IAClC,aAEA,sBACA,UAA2B,MAAW,EACtC,YAEA,CAAa,KACb,OAA2B,EAAO,IAClC,YAEA,UACA,CAEA,CAEA,CACA,aAAuB,EAAQ,SAC/B,SACA,iBAA+B,EAAO,QACtC,OACA,MAAmC,EAAO,IAC1C,eAEA,qBACA,UAAmC,EAAO,IAC1C,eAEA,OAEA,OAAuB,EAAO,IAC9B,YAEA,UACA,CAGA,aACA,IACA,EACA,6BACA,SAAuB,GAAS,OAIhC,MAHA,sCAIA,MACA,EACA,KAEA,UACA,IACS,MACT,SAA4B,EAAS,MAIrC,MAHA,oCAIA,0BACA,MACA,EACA,KAEA,CACA,QACa,QACb,IAEA,KACA,EAEA,IAEA,CAGA,OADA,cAEA,WACA,UACA,MAA+B,EAAQ,KACvC,IASA,cARA,UACA,SACA,IACA,OACA,iBACA,gBAEA,YACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,WACA,UACA,EAA2B,IAAO,IAClC,IAOA,cANA,UACA,SACA,IACA,YACA,YACA,aACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,0DACA,aACA,WACA,WACA,OACA,SACA,2BACA,SACA,OACA,UACA,aACA,OACA,QAEA,SAEA,eACA,SACA,IAA2B,QAAW,MACtC,CAWA,SAVA,YACA,MACA,IACA,YAEA,iBACA,mBACA,aACA,gBACA,WACmC,EAAO,IAC1C,yBACA,iCACA,GAGA,mBACA,YACA,MACA,IACA,sBACA,wBACA,WACA,gBACA,UACA,QAAmC,EAAO,IAC1C,yBACA,iCACA,GAGA,SACA,KAEA,SACA,KACA,QACA,IACA,4BAEA,WAAmC,EAAS,KAC5C,aAIA,aACA,iBAGA,WACA,cACA,OACA,YACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,oBACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,UAEA,MACA,EACA,IACA,KAGA,EAEA,MACA,IACA,KACA,IACA,GAEA,MACA,SACA,SACA,SACA,SACA,mBAhYA,IAkYA,YACA,gBACA,0CACA,EACA,aACA,eACA,EACA,YAEA,mCACA,2BACA,SACA,UAAsC,OAAQ,IAC9C,IACA,QAGA,IACA,QACA,gBACA,aACA,CAEA,iBACA,wDACA,EACA,2BACA,0BACA,yBAEA,SACA,CACA,4BACA,0BACA,yBAEA,SACA,CACA,sBACA,sBACA,EACA,mBAEA,CACA,WACA,mBACA,aACA,WAEA,QAAmB,EAAW,IAC9B,mBACA,SAEA,SAIA,gBACA,SAEA,yBACA,YACA,SACA,aACA,eAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,UACA,OACA,8BACA,uBACA,QACA,oBACA,YACA,SACA,cACA,cACA,0BACA,UAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,IAClC,mBACA,qBAEA,KAKA,aAEA,MACA,cACA,YACA,YAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,CACA,QAGA,uCCzfA,aACA,MACA,yBAEA,gBAEA,uBACA,YACA,SACA,UACA,eAEA,QAAe,EAAO,QACtB,OACA,MAAmB,IAAO,IAC1B,iBAEA,kBACA,KACA,cAEA,IAAuB,IAAO,IAC9B,IAEA,wBACA,MAA2B,EAAO,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,CACA,MACA,EAEA,MACA,UACA,uBA1CA,IA4CA,YACA,kBACA,OAEA,0BACA,OAEA,UACA,yBAEA,6CACA,6BAGA,oCACA,YACA,YACA,cAEA,QAAmB,EAAO,IAC1B,UAAuB,EAAW,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OAEA,SAAuB,EAAQ,SAC/B,OAAuB,EAAW,IAClC,kBAEA,eAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OAEA,8BACA,EACA,uBACA,mBACA,UAAuB,EAAa,IACpC,OACA,kBAGA,SACA,QACA,6BACA,YACA,OACA,aACA,YACA,QAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,YACA,IACiB,QACjB,WAEA,SAIA,EACA,QACA,wBACA,YACA,OACA,SACA,aACA,gBAEA,UAA6B,EAAQ,SACrC,OAAuB,EAAU,IACjC,YAEA,cACA,EAAuB,IAAa,IACpC,mBACA,OACA,EAA+B,IAAU,IACzC,eAGA,iBAEA,QAA+B,IAAU,IACzC,eAEA,OAEA,CACA,CACA,QAGA,uCCjJA,eACA,MACA,yBAEA,kBAEA,iBAEA,cACA,SACA,UAEA,YACA,yCACA,2CACA,mBAEA,cACA,KACA,OACA,SAiBA,gBAhBA,OAEA,qBACS,8FACT,KACA,gBACA,SACA,QACA,QACA,KACA,IACA,GAEA,iBAIA,qBACA,kBACA,KACA,WAEA,eACA,eAEA,0BACA,oBAEA,YAAyC,OAAS,QAClD,QACA,UACA,EAAuB,IAAO,IAC9B,uBAEA,qBACA,KACA,kBAEA,MAA2B,IAAO,IAClC,aAEA,cACA,CACA,OACA,IAEA,SAAuB,EAAO,QAC9B,kBACA,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,MACA,OAEA,OACA,QAAuB,IAAO,IAC9B,YAIA,eACA,UACA,MAA2B,EAAO,IAClC,uBAEA,kBACA,KACA,kBAEA,UAA+B,EAAO,IACtC,UAEA,aACA,CACA,UACA,qBACA,SAA+B,EAAO,IACtC,SAEA,UAA+B,EAAO,IACtC,YAAmC,EAAO,IAC1C,eAGA,gBAA+B,EAAO,IACtC,oBACA,OAAmC,EAAO,IAC1C,eAGA,IACA,CACA,aAA+B,EAAO,IACtC,YAGA,IACA,CAEA,YACA,GACA,WAEA,SACA,aAEA,KACA,kBAEA,WAEA,IACA,KAAqB,IAAQ,QAC7B,OAAuB,EAAO,IAC9B,YAEA,UACA,CACA,SAAyB,EAAQ,KACjC,gBACA,SAA+B,EAAQ,QACvC,OACA,EAA+B,IAAO,IACtC,eAEA,iBACA,QAA+B,IAAO,IACtC,eAEA,OACA,KAA2B,IAAO,IAClC,aAEA,sBACA,UAA2B,MAAW,EACtC,YAEA,CAAa,KACb,OAA2B,EAAO,IAClC,YAEA,UACA,CAEA,CAEA,CACA,aAAuB,EAAQ,SAC/B,SACA,iBAA+B,EAAO,QACtC,OACA,MAAmC,EAAO,IAC1C,eAEA,qBACA,UAAmC,EAAO,IAC1C,eAEA,OAEA,OAAuB,EAAO,IAC9B,YAEA,UACA,CAGA,aACA,IACA,EACA,6BACA,SAAuB,GAAS,OAIhC,MAHA,sCAIA,MACA,EACA,KAEA,UACA,IACS,MACT,SAA4B,EAAS,MAIrC,MAHA,oCAIA,0BACA,MACA,EACA,KAEA,CACA,QACa,QACb,IAEA,KACA,EAEA,IAEA,CAGA,OADA,cAEA,WACA,UACA,MAA+B,EAAQ,KACvC,IASA,cARA,UACA,SACA,IACA,OACA,iBACA,gBAEA,YACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,WACA,UACA,EAA2B,IAAO,IAClC,IAOA,cANA,UACA,SACA,IACA,YACA,YACA,aACmC,EAAO,IAC1C,yBACA,iCACA,GAIA,UACA,KACA,QACA,0DACA,aACA,WACA,WACA,OACA,SACA,2BACA,SACA,OACA,UACA,aACA,OACA,QAEA,SAEA,eACA,SACA,IAA2B,QAAW,MACtC,CAWA,SAVA,YACA,MACA,IACA,YAEA,iBACA,mBACA,aACA,gBACA,WACmC,EAAO,IAC1C,yBACA,iCACA,GAGA,mBACA,YACA,MACA,IACA,sBACA,wBACA,WACA,gBACA,UACA,QAAmC,EAAO,IAC1C,yBACA,iCACA,GAGA,SACA,KAEA,SACA,KACA,QACA,IACA,4BAEA,WAAmC,EAAS,KAC5C,aAIA,aACA,iBAGA,WACA,cACA,OACA,YACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,oBACA,QAAmC,EAAO,IAC1C,aACA,aACA,QAGA,UAEA,MACA,EACA,IACA,KAGA,EAEA,MACA,IACA,KACA,IACA,GAEA,MACA,SACA,SACA,SACA,SACA,mBAhYA,IAkYA,YACA,gBACA,0CACA,EACA,aACA,eACA,EACA,YAEA,mCACA,2BACA,SACA,UAAsC,OAAQ,IAC9C,IACA,QAGA,IACA,QACA,gBACA,aACA,CAEA,iBACA,wDACA,EACA,2BACA,0BACA,yBAEA,SACA,CACA,4BACA,0BACA,yBAEA,SACA,CACA,sBACA,sBACA,EACA,mBAEA,CACA,WACA,mBACA,aACA,WAEA,QAAmB,EAAW,IAC9B,mBACA,SAEA,SAIA,gBACA,SAEA,yBACA,YACA,SACA,aACA,eAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,UACA,OACA,8BACA,uBACA,QACA,oBACA,YACA,SACA,cACA,cACA,0BACA,UAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,IAClC,mBACA,qBAEA,KAKA,aAEA,MACA,cACA,YACA,YAEA,QAAmB,EAAW,IAC9B,UAAuB,EAAW,QAClC,OACA,IAA2B,EAAW,IACtC,eAEA,QACA,SAGA,CACA,QAGA,8zBCrfkD,kBCRlD,aAEA,eACA,OACA,IAMA,CACA,iBACA,WACA,IAAmB,MAAmB,OACtC,OAEA,KACA,QAMA,EACA,iBACA,YACA,aACA,SAAmB,EAAO,IAC1B,eAEA,MACA,QAMA,EACA,iBACA,WACA,aACA,SAAmB,EAAO,IAC1B,eAEA,MACA,QAMA,EACA,oBACA,WACA,YACA,aACA,SAAmB,EAAO,IAC1B,eACA,iBAEA,YACA,CACA,MAEA,MAMA,EACA,4BACA,WACA,MACA,SAAmB,EAAO,IAC1B,OAEA,WACA,IAIA,EACA,SAMA,eACA,2BACA,WACA,MACA,SAAmB,EAAO,IAC1B,OAEA,gBACA,IAQA,EACA,qBACA,WACA,MACA,SAAmB,EAAO,IAC1B,SAEA,YACA,IAOA,EACA,yBACA,WACA,IACA,MACA,SAAmB,EAAO,IAC1B,YACA,QAEA,WACA,IAQA,EACA,+BACA,cAEA,sBAEA,qBACA,WACA,OACA,EAAmB,MAAa,IAChC,OAEA,iBACA,IAMA,EACA,0BACA,WACA,MACA,SAAmB,EAAO,QAC1B,IACA,kDAEA,gBACA,IACA,OACA,IAMA,EACA,gCACA,WACA,IACA,MACA,SAAmB,EAAO,IAC1B,YACA,QAEA,QACA,yBAEA,mCACA,IAOA,EACA,sBACA,cAEA,sBAEA,iBACA,aACA,SACA,QAEA,kBAEA,IAOA,EACA,wBACA,cACA,kBACA,UACA,MAEA,SAAmB,IAAO,IAC1B,MACA,UAIA,kBAEA,GAEA,GAOA,EACA,iCACA,YACA,gBAEA,2BACA,mCACA,SAEA,yBACA,yBAEA,cACA,UAGA,wBACA,WACA,OACA,wBAEA,UAAY,UACZ,OAEA,uCACA,YACA,sBAEA,8BACA,yBACA,gBACA,UACA,SAAmB,EAAO,QAC1B,OACA,SAEA,yBAGA,mBAEA,IACA,MACA,OACA,MAEA,kBACA,SACA,SACA,SACA,QAAe,EAAO,IACtB,SAEA,QACA,WAEA,QAAe,EAAO,QACtB,iBACA,MACA,KAEA,aACA,UACA,EAEA,IAEA,WACA,QAAe,EAAW,IAC1B,IACA,WACA,KAIA,WACA,OAEA,4BACA,yBACA,cACA,YAEA,wBACA,YAEA,0DACA,SAAmB,EAAO,QAC1B,OACA,SACA,UACA,GAGA,eAEA,GACA,KAEA,wBACA,yBACA,kBAEA,oBACA,SAAmB,IAAO,IAC1B,MACA,UACA,OAEA,YACA,MAEA,YACA,UACA,cACA,UAEA,MADA,IAGA,CAEA,UAEA,wBACA,yBACA,kBACA,yBAEA,IAAmB,IAAO,IAC1B,MACA,UACA,OAEA,cACA,MAEA,SACA,YACA,QAEA,oCADA,MAIA,yBADA,IAGA,gBAEA,GAEA,uBACA,2BACA,mBACA,SAAmB,EAAO,IAC1B,cACA,cACA,IAEA,4BACA,iBACA,SAAmB,EAAO,IAC1B,YACA,KACA,UAEA,yCACA,YACA,wBAEA,gCACA,aACA,0BACA,aAEA,IAAmB,EAAO,QAC1B,OACA,SAEA,WACA,KACA,QACA,GAEA,cACA,SAEA,sBACA,yBAEA,SAEA,aAEA,iCACA,SAAmB,EAAO,IAC1B,IACA,SAEA,6BACA,6BACA,8CACA,kBACA,aACA,WAAmB,EAAO,IAC1B,SACA,OACA,UAEA,2BACA,SACA,SACA,gBACA,aAAmB,EAAO,IAC1B,gBACA,KACA,uBCpcA,mBACA,MACA,SACA,SACA,eACA,WACA,aAEA,yCACA,4BAA6C,OAAQ,IACrD,oCAEA,aAEA,mCACA,mCACA,KAEA,wCACA,kBACA,gBACA,2DACA,OAEA,oCACA,uBACA,MAGA,qBACA,MACA,oBACS,WACT,8BAEA,yBACA,OACA,EACA,SACA,WAEA,WACA,EAEA,mCACA,WAGA,IACA,+BACA,YACS,WACT,UAEA,GACA,wBACA,SACA,WAEA,WACA,EAEA,mCAEA,YACA,aACA,cAEA,gCACA,YACA,2BACA,SACA,EACA,QACA,OAgBA,KAEA,eAjBA,gBACA,oBACA,SACA,SACA,MAEA,QACA,KAEA,EACA,UACA,MAGA,mBAIA,mBACA,oBAEA,YADA,WAGA,mCACA,OACA,aACA,mBAEA,SAEA,E,yBCzGA,aAEA,eACA,OACA,IAMA,CACA,iBACA,WACA,IAAmB,MAAmB,OACtC,OAEA,KACA,QAMA,EACA,iBACA,aACA,OACA,SAAmB,EAAO,IAC1B,eAEA,MACA,QAMA,EACA,iBACA,aACA,OACA,SAAmB,EAAO,IAC1B,eAEA,MACA,QAMA,EACA,oBACA,aACA,OACA,OACA,SAAmB,EAAO,IAC1B,eACA,iBAEA,YACA,CACA,MAEA,MAMA,EACA,4BACA,WACA,MACA,SAAmB,EAAO,IAC1B,OAEA,WACA,IAIA,EACA,SAMA,eACA,2BACA,WACA,MACA,SAAmB,EAAO,IAC1B,OAEA,gBACA,IAQA,EACA,qBACA,WACA,MACA,SAAmB,EAAO,IAC1B,SAEA,YACA,IAOA,EACA,yBACA,WACA,IACA,MACA,SAAmB,EAAO,IAC1B,YACA,QAEA,WACA,IAQA,EACA,+BACA,cAEA,yBAEA,qBACA,WACA,OACA,EAAmB,MAAa,IAChC,OAEA,iBACA,IAMA,EACA,0BACA,WACA,MACA,SAAmB,EAAO,QAC1B,IACA,kDAEA,gBACA,IACA,OACA,IAMA,EACA,gCACA,WACA,IACA,MACA,SAAmB,EAAO,IAC1B,YACA,QAEA,QACA,yBAEA,mCACA,IAOA,EACA,sBACA,cAEA,yBAEA,iBACA,aACA,SACA,QAEA,kBAEA,IAOA,EACA,wBACA,cACA,kBACA,UACA,MAEA,SAAmB,IAAO,IAC1B,MACA,UAIA,kBAEA,GAEA,GAOA,EACA,iCACA,YACA,gBAEA,2BACA,mCACA,OAOA,EACA,gCACA,WACA,eACA,QAAe,EAAY,IAC3B,OAEA,KACA,WACA,eAAe,EAAY,IAC3B,WACA,iBACA,UACA,kBAEA,6BAGA,OACA,CACA,OAEA,UAEA,yBACA,yBAEA,yBAGA,wBACA,WACA,OACA,wBAEA,UAAY,UACZ,OAEA,uCACA,YACA,sBAEA,8BACA,yBACA,gBACA,UACA,SAAmB,EAAO,QAC1B,OACA,SAEA,yBAGA,mBAEA,IACA,MACA,OACA,MAEA,kBACA,SACA,SACA,SACA,QAAe,EAAO,IACtB,SAEA,QACA,WAEA,QAAe,EAAO,QACtB,iBACA,MACA,KAEA,aACA,UACA,EAEA,IAEA,WACA,QAAe,EAAW,IAC1B,IACA,WACA,KAIA,WACA,OAEA,4BACA,yBACA,cACA,YAEA,wBACA,YAEA,0DACA,SAAmB,EAAO,QAC1B,OACA,SACA,UACA,GAGA,eAEA,GACA,KAEA,wBACA,yBACA,kBAEA,oBACA,SAAmB,IAAO,IAC1B,MACA,UACA,OAEA,YACA,MAEA,YACA,UACA,cACA,UAEA,MADA,IAEA,CAEA,UAEA,wBACA,yBACA,kBACA,yBAEA,IAAmB,IAAO,IAC1B,MACA,UACA,OAEA,cACA,MAEA,SACA,YACA,QAEA,oCADA,MAIA,yBADA,IAEA,gBAEA,GAEA,uBACA,2BACA,mBACA,SAAmB,EAAO,IAC1B,cACA,cACA,IAEA,4BACA,iBACA,SAAmB,EAAO,IAC1B,YACA,KACA,UAEA,yCACA,YACA,wBAEA,gCACA,aACA,0BACA,aAEA,IAAmB,EAAO,QAC1B,OACA,SAEA,WACA,KACA,QACA,GAEA,cACA,SAEA,sBACA,yBAEA,SAEA,cAEA,mCACA,SAAmB,EAAO,IAC1B,IACA,SAEA,6BACA,6BACA,8CACA,kBACA,aACA,WAAmB,EAAO,IAC1B,SACA,OACA,UAEA,2BACA,SACA,SACA,gBACA,aAAmB,EAAO,IAC1B,gBACA,KACA,2BC9dA,aAsGA,aACA,WACA,KAAmB,QAAgB,OACnC,0BACA,kDAEA,UACA,QAMA,CAjHA,QAMA,KAmKA,UACA,CACA,MApKA,WACA,WACA,IAAmB,MAAgB,OACnC,oDAEA,cACA,QAOA,EAwJA,IAvJA,aACA,mBACA,UAAmB,MAAiB,OACpC,cACA,KACA,QAOA,EA4IA,GA3IA,aACA,mBACA,UAAmB,MAAiB,OACpC,cACA,KACA,QAOA,EAgIA,IA/HA,aACA,mBACA,UAAmB,MAAiB,OACpC,cACA,KACA,QAMA,EAqHA,IApHA,WACA,mBACA,UAAmB,MAAgB,OACnC,UACA,KACA,QAOA,EAyGA,OAxGA,aACA,UAGA,KAFA,WACA,GASA,EA6FA,OA5FA,eACA,UACA,YAEA,GAIA,gBAFA,QACA,MAOA,EA+EA,iBACA,kBAjEA,WACA,oBACA,KACA,WAAmB,EAAS,IAC5B,SAEA,gCACA,QAMA,EAqDA,YApDA,WACA,WACA,KAAmB,QAAgB,OACnC,0BACA,2BAEA,UACA,QAMA,EAwCA,eAvCA,WACA,oBACA,IACA,WAAmB,EAAS,IAC5B,SAEA,+BACA,QAMA,EA2BA,QA1BA,WACA,WACA,OACA,KAAmB,MAAgB,WACnC,kEACA,cAAuB,EAAQ,QAC/B,yBAEA,qBACA,KACA,CACA,4BCzKA,aA4GA,eACA,iBACA,uBAEA,mDAEA,eACA,+CACA,IAEA,aACA,UACA,eAAmB,MAAgB,OACnC,UAEA,mBACA,QAEA,2BACA,wBACA,OACA,KACA,sBACA,OACA,KACA,sBACA,OACA,KACA,sBACA,OACA,KAEA,KACA,WACA,uBACA,aAAmB,MAA4B,OAC/C,iCAEA,SAhJA,UAEA,KACA,SAWA,KACA,+BACA,4BACA,EAcA,EACA,+BACA,CACA,eACA,oBACA,gBACA,SACA,SACA,iBAAe,EAAO,IACtB,IAEA,wBACA,SAEA,uBAAoC,EAAQ,KAC5C,kBAGA,GACA,kBAEA,OACA,WAYA,EACA,2BACA,CACA,eACA,oBACA,oBACA,SACA,WAAmB,EAAO,IAC1B,IAGA,mBAEA,KACA,KACA,eACA,yBACA,eACA,iBACA,KACA,eACA,QAEA,KACA,iBACA,kBAGA,OAAe,MAAkB,WACjC,WACA,KACA,OAAuB,MAAkB,OACzC,uBAGA,OACA,kBAEA,OACA,aA0CA,6BCpJA,aAEA,UAEA,OACA,QACA,SACA,YAEA,OAcA,eACA,MACA,cAEA,qBACA,+BACA,+BACA,mCACA,4BACA,wBACA,kCACA,0CAEA,kBAA2B,sBAA2B,EACtD,2BAEA,6EACA,GAEA,uDACA,wDAEA,4DAEA,kEAEA,8DACA,+DACA,0CACA,0BAGA,OAOA,kBACA,mCACA,cAGA,6BACA,CACA,yCACA,mBACA,gCACA,oCACA,4BAIA,yBAAuB,sBAA8B,OACrD,wBACA,+BACA,mBACA,gCACA,gCACA,oCACA,4BAKA,qCACA,sDACA,GACA,6BACA,gCACA,oCACA,4BAEA,cAOA,WACA,KACA,4BAEA,uBACA,yCAEA,YAEA,4BAAuB,WAAqB,WAC5C,WACA,kBAEA,sBAOA,aACA,QACA,OAAuB,eAAuB,OAE9C,oBAIA,sCACA,UASA,uBACA,WAAuB,MAA0B,OACjD,mCAIA,KACA,6BAAuC,EAAQ,SAC/C,2BACA,oBACA,oBAEA,OAAmB,eAAuB,OAC1C,kBAEA,QAOA,WACA,KACA,iCACA,aACA,eAAuB,MAAmB,KAC1C,6CAGA,IACA,QAMA,SACA,WACA,OACA,wBACA,6BACA,6BACA,iCACA,+BACA,gCACA,2BACA,8BAGA,WAAuB,eAAuB,OAC9C,8BAGA,SACA,QAOA,eACA,IACA,qCAGA,yDACA,SACA,EAEA,6BCrNA,aAEA,eACA,UAGA,sBlFNA,aA0BA,uBACA,6BACA,0BACA,4DACA,kCACA,iBAUA,CACA,qBACA,QACA,QACA,EACA,UACA,6BACA,aACA,0BACA,cAEA,SAkBA,CApEA,UACA,QACA,SACA,YAEA,UACA,eACA,cACA,KACA,iCACA,cAaA,oBA8FA,UAhDA,eACA,aAEA,kCACA,qBAGA,sEACA,uBACA,yBAOA,oBACA,aACA,YACA,UACA,gEACA,mBACA,MACA,4EAKA,+BAlBA,2BAEA,iEAGA,eAcA,uDAIA,aACA,qBAEA,qBACA,QACA,EACA,UACA,6BACA,SACA,cAEA,mBAEA,wCmFrHA,aAEA,Y,sBCFA,aAEA,UACA,SAEA,OACA,CACA,eACA,uBACA,mCACA,IAcA,qBAyDA,UAxDA,eAEA,oBACA,iCAIA,8DAGA,gCACA,yBAEA,kBAAuB,MAAkC,OACzD,uBAEA,CAGA,aACA,sBACK,sFACL,uCACA,iCAGA,sFACA,kBACA,4BAIA,qEAGA,gBACA,gBAEA,iBAA2B,qBAAmD,GAE9E,wBAGA,wBACA,gBAKA,qBACA,CACA,kBACA,iBAEA,gCC/EA,aAEA,6BACA,yDCHA,aAcA,eACA,sBACA,wBAEA,mBAAY,IACZ,0BACA,YACA,SAAgB,IAChB,kCAGA,MACA,QA4BA,CACA,eACA,+BACA,OACA,sBACA,aAAgB,IAChB,gDAEA,IACA,QAQA,CACA,eACA,2BACA,MACA,sBACA,aAAgB,IAChB,uDAEA,OACA,QAMA,CACA,iBACA,GACA,8BAEA,gBACA,kBAGA,cACA,OACA,OACA,OAEA,cAEA,2BAGA,wEACA,gCACA,gCACA,0CACA,8BAEA,iBAGA,0CACA,sBAEA,GAMA,CACA,iBACA,GACA,8BAEA,gBACA,kBAGA,cACA,OACA,OAEA,OAIA,cAEA,2BAGA,wEACA,gCAEA,0DACA,mCACA,0CACA,8BAIA,iBACA,0CACA,sBACA,GAIA,CAqNA,eACA,SACA,SACA,kBACA,EAEA,UAEA,YAIA,YACA,WACA,aACA,OACA,GACA,8BAAoB,IACpB,SACA,UACA,KACA,WAKA,cACA,8BAAwB,IACxB,cACA,aACA,QACA,cAOA,GACA,KAEA,IAIA,WACA,WACA,WAAmB,EAAc,IACjC,cACA,aACA,GACA,WAGA,KACA,OAAe,EAAc,IAC7B,IAEA,QACA,aAA4B,EAAO,KACnC,IACA,oBACA,cAIA,UACA,+CACA,eACA,IAIA,CA9bA,QACA,gBACA,YASA,GAqbA,qCACA,gCAvMA,eACA,OAEA,kBACA,kBAGA,cACA,OACA,OACA,0BAGA,yBAGA,mDACA,mBACA,eACA,eACA,eACA,oBACA,IAVA,UAUa,IACb,iBACA,YACA,mBAEA,mBACA,cACA,yBAEA,eACA,cACA,gBAEA,qBACA,kBACA,iBAGA,6BACA,YACA,mCAEA,QACA,iBAAa,IACb,iCAGA,MAEA,QAOA,EA8IA,mCACA,8BA9IA,eACA,OAEA,kBACA,kBAGA,cACA,OACA,OACA,sBAGA,gBACA,QAFA,UAEY,IACZ,SAIA,yBAIA,mDACA,mBACA,eACA,eACA,eACA,oBACA,YAAa,IACb,iBACA,iBACA,qBAEA,mBACA,cACA,oCAEA,eACA,cACA,yBAEA,qBACA,kBACA,iBAGA,eACA,mCAEA,QACA,iBAAa,IACb,iCAGA,MAEA,QAMA,EAgFA,2BACA,6BACA,gCA5PA,eACA,OAEA,kBACA,kBAGA,kBACA,OACA,OACA,KACA,MACA,cAGgB,EAFhB,MACA,EACA,aAAgC,IAChC,cAEA,8BACA,cACA,eACA,KACA,cACA,iBACA,gBACA,MAGA,cAEA,kBAAyB,kCAGzB,iBAAyB,mCAEzB,QAEA,CACA,QASA,EA8MA,U,wBAtSA,eACA,OAEA,kBACA,kBAGA,kBACA,OACA,OACA,KACA,MACA,cAGgB,EAFhB,MACA,EACA,aAAgC,IAChC,cAEA,8BACA,cACA,eACA,KACA,cACA,iBACA,gBACA,MAGA,cAEA,kBAAyB,kCAGzB,iBAAyB,mCAEzB,QAEA,CAEA,2BC1MA,aAEA,UACA,UACA,WACA,WACA,WACA,SAEA,oBACA,CACA,sBACA,UAUA,UACA,OACA,iBACA,WACA,MACA,KAOA,qBANA,oBACA,mBACA,oBACA,8BACA,iBACA,EAGA,aAEA,oBACA,eACA,oBACA,iBAEA,OACA,mBAIA,iBAHA,mCAIA,QACA,0CAEA,kCAGA,SACA,QACA,0DACA,QACA,+BAAS,KACT,QACA,2BACA,CACA,8BACA,+BAGA,4BAEA,+BACA,mBACA,kBAA2B,MAA2B,OACtD,6BAEA,QACA,GACA,CAOA,eACA,IACA,wDACA,YACA,YAOA,WACA,UAEA,cACA,6BACA,YACA,2BAIA,qBACA,EAMA,uBACA,WACA,IAAuB,WAAmB,OAC1C,YAEA,4BACA,IAMA,wBACA,gBACA,yBAAuB,MAAsB,OAC7C,cAEA,GACA,QAMA,kBACA,aACA,CAMA,iBACA,aACA,CAMA,wBACA,wBACA,KAMA,cACA,eACA,WAMA,SACA,OACA,MACA,kBACA,kBACA,iBACA,kBACA,cACA,SAEA,EAEA,aACA,oBACA,sBAEA,QAEA,qBACA,SACA,4BACA,aACA,UACA,2BACA,WAA+B,MAAmB,OAClD,OACA,8BAGA,yEACA,WACA,eACA,CAEA,CACA,QAEA,gCACA,kBACA,8BACA,4BAAuB,WAAmB,OAC1C,cAEA,mCACA,SACA,EAEA,6BxFtNA,aAEA,eAEA,OAUA,mBACA,MACA,8CACA,uBAEA,8DACA,cACA,YAEA,IAEA,UACA,cAA2B,EAAU,IACrC,cAA+B,EAAa,IAC5C,WACA,MACA,aAIS,cACT,SACA,sBAEA,0GAA2B,MAAc,EACzC,gBAAmC,EAAa,IAChD,WACA,MACA,aAIA,SAGA,0BAEA,6BAGA,0CAEA,cAEA,iBACA,IAEA,SACA,OACA,IACA,IAAuB,MAAkB,OACzC,SACA,aACA,UACA,UACA,eAEA,WACA,MACA,IAEA,MACA,IAGA,OACA,UACA,UAEA,kBACA,iBACA,mBACA,yBACA,yBAEA,mBAAuB,EAAO,IAC9B,WACA,YAEA,eACA,eAGA,UACA,YACA,qBACA,GAkBA,cACA,IACA,mCAEA,4BACA,qBAAsD,2BAEtD,gCACA,KAKA,UACA,sBACA,SACA,WACA,mBAAuB,EAAO,IAC9B,yBACA,0BAEA,WACA,QAAmB,EAAO,IAC1B,mCAEA,IACA,QAKA,UACA,sBACA,SACA,WACA,mBAAuB,EAAO,IAC9B,yBACA,0BAEA,WACA,QAAmB,EAAO,IAC1B,mCAEA,IACA,QAEA,mBACA,GACA,6BACA,0CACA,qCACA,mCAEA,OACA,KACA,KACA,KACA,KAEA,sBACA,mBAEA,UAAiD,EAAc,UAC/D,WACA,cAEA,MAEA,uBACA,iBAEA,MACA,KAEA,OACA,UAEA,mBACA,mCACA,uBAEA,OACA,CACA,UACA,cACA,cACA,kBAEA,kBACA,EAEA,QACA,KACA,eACA,iBACA,0BACA,yBACA,0BACA,yBACA,gCACA,mCACA,wCACA,mCACA,iBACA,mCACA,yCACA,aAEA,6ByFlOA,mBACA,cACA,+BCFA,aAEA,qCACA,6BACA,+BACA,yBAEA,4BACA,uBACA,MACA,gCAEA,KACA,wBAEA,KACA,4BACA,oDCjBA,CA4EA,mBACA,WACA,IACA,QAA0B,MAC1B,qBACA,cACA,KAGA,cACA,OAEA,mBACA,OACA,EAcA,SAbA,qCACA,2DAGA,WACA,KAGA,EAIA,IAGA,eACA,OACA,KACA,qBAAwB,KACxB,IAGA,KACA,SAEA,qBACA,WACA,MAAgB,KAEhB,oDAEA,WACA,QAOA,CACA,iBACA,WACA,eACA,QAAkB,KAAM,IACxB,QACA,sBAAsB,KACtB,gBAEA,YACA,CACA,QAyBA,CArKA,QACA,QAEA,OACA,YACA,aACA,aACA,GA+JA,UA5JA,eACA,MAEA,kDACA,iCAGA,uFACA,6FACA,gCACA,iCACA,mEACA,iCACA,2CACA,yBAGA,wKAEA,iBACA,OACA,SACA,8BACA,cACA,EACA,KACA,qDAGA,aAIA,wBAAgB,IAAO,IACvB,iBACA,WACA,SACA,IAAuB,EAAgB,IACvC,YACA,qBAGA,eACA,aAGA,sBACA,qBACA,oBACA,qBAEA,IAEA,WACA,WAAyB,MAAO,IAChC,GACA,YAAuB,EAAgB,IACvC,cAEA,2BACA,sBACA,GACA,CACA,2BC1EA,aAEA,QACA,OACA,QAEA,MACA,YACA,aACA,aACA,MACA,gBASA,aA2DA,UA1DA,eACA,MACA,kDACA,iCACA,6FACA,iCACA,mEACA,iCAEA,gEAGA,KAFA,EAGA,uBAA+B,eAG/B,iCAEA,+DACA,kBACA,kBACA,kBAGA,KACA,mBAGA,OACA,4CACA,uBACA,IAAuB,MAAc,OACrC,cAA2B,SAAiB,OAC5C,aACA,mBAGA,gBACA,4BACA,cACA,cACA,cACA,CACA,mBACA,YAAsB,UAA0B,aAChD,GACA,YAAuB,MAAc,OACrC,cACA,WACA,MAEA,CAKA,MAJA,wBAA6B,eAG7B,gCC5EA,aAgBA,mBAEA,QAMA,WALA,SAEA,MACA,WACA,+BAEA,kBAEA,KAIA,QACA,kEACK,kDACL,qCACA,4BACA,yBACA,yBACA,OACA,sBAGA,gCACA,oCACA,wBACA,CACA,IAEK,SACL,MACA,iCACA,gBACA,CACA,WACA,eAEA,GAEA,4BACA,wDAEA,yCAEA,+CAEA,YACA,OAGA,iBAFA,mBAGA,qBAGA,uCACA,SACA,SAGA,gCAEA,+BACA,+BAEA,iEAEA,qCAEA,qCAEA,YAEA,kBACA,QA4QA,aACA,aACA,SACA,WACA,WAAmB,EAAO,IAC1B,gBACA,mBAEA,aACA,sBACA,WACA,WAA2B,EAAO,IAClC,qBAEA,OACA,QACA,qBACA,QACA,QAA2B,EAAO,IAClC,sBAEA,MACA,QAEA,GAEA,aACA,mBACA,wBACA,GACA,EAEA,aACA,mBACA,uBACA,GACA,EAEA,eACA,WACA,UAAkC,OAAQ,IAC1C,yBAEA,MACA,SAEA,eACA,kBACA,SAEA,eACA,WACA,WACA,WAAmB,EAAgB,IACnC,SACA,OAEA,QACA,QAhaA,QACA,QAEA,OACA,QACA,kBACA,OACA,sBACA,gBACA,aACA,OACA,gBACA,UAgFA,oBACA,mBACA,cACA,mBAEA,mBACS,qBACT,0DAEA,wBACA,oBACA,mBAAuB,EAAO,QAC9B,YACA,mBAA2B,EAAO,IAClC,uCAEA,aACA,CACA,QACA,iBAEA,0BAEA,8BACA,UACA,qBAEA,oCACA,MAEA,cACA,qBACA,6BACA,4BAEA,uBACA,MAAmB,SAAY,MAC/B,sBACA,aAAuB,SAAY,EACnC,kCAEA,OAEA,CAGA,4CADA,eAGA,iCACA,YACA,UACA,4BACA,KAAe,SAAY,EAC3B,iCACA,KAAmB,SAAY,MAC/B,kBACA,kBAAuB,SAAqB,WAC5C,cAEA,sDACA,KAEA,2BACA,SAEA,mCACA,SACA,4BAEA,gDACA,MACA,QACA,iBACA,gBACA,WAAmB,EAAO,IAC1B,wBAGA,8BAEA,+BACA,0DAEA,oBAEA,gBACA,0CACA,SAEA,+BACA,SAEA,KAEK,mCAEL,IACA,GACA,EAEA,EAmBA,MAlBA,8EACA,wCACA,iBACA,kFAEA,2DACA,kCACA,sEACA,aACA,aACA,wIAIA,gBAEA,mBAIA,CAIA,YAHA,YAKA,iCACA,YACA,aAIA,gCACA,YAHA,sBAKA,UACA,SACA,QACA,QACA,QAEA,QAAkB,IAAW,SAC7B,IACA,SACA,YACS,UACT,YAEA,GAAsB,IAAW,SACjC,IACA,KACA,YACa,UACb,YAGA,iCAEA,aACA,cACA,4CAGA,gBACA,CAEA,yBAEA,SAEA,6BACA,UACA,cACA,oBAGA,eAEA,wCACA,sBACA,KAAmB,SAAY,MAC/B,iBACA,aAAuB,WAAY,EACnC,WACA,2DAEA,OACA,CACA,UAEA,6CAEA,WAEA,WAEmB,EAHnB,EAGA,SAA+B,EAC/B,cAAuB,SAAY,EACnC,qCACA,WACA,MACA,WAKA,aAEA,UAEA,iCACA,IACA,sBACA,MAGA,iBAEA,4EACA,OACA,6BACA,UACA,aACA,EACA,aAEA,eAEA,kCACA,OACA,oBAEA,yBACA,kCAEA,GAGA,kBADA,iBAGA,EACA,2CACA,gBACA,aACA,SACA,IAAmB,EAAO,IAC1B,OAEA,WACA,MAEA,8BAEA,YAEA,yBACA,SAEA,WAAmB,EADnB,EAC0B,IAC1B,iCACA,kCAEA,UACA,UA8DA,E,2BCtIA,eACA,QACA,8CAEA,MACA,SAnSA,cAEA,OACA,iBAA2C,KAC3C,mBACA,MACA,KAEA,6DADA,UAGA,qBACA,MACA,SACA,SACA,aACA,iCACA,qBAA2B,EAAU,IACrC,cAA+B,IAAa,IAC5C,MACA,gDACA,GACA,+BAIA,QACA,gCAEA,UAEA,eACA,MACA,YACA,eACA,6BACA,CAEA,oBACA,SACA,oBACA,8BAAuB,EAAS,IAChC,cAEA,GACA,QAEA,QACA,cACA,KAEA,YACA,oBACA,gBAAuB,SAAe,SACtC,iBACA,mBAA2B,SAAkB,QAC7C,iBAEA,QACA,CACA,QAEA,WACA,yBACA,OAEA,cACA,qBAEA,YACA,MAQA,oCAPA,aACA,gBAIA,QACA,IAGA,kBACA,sBACA,IAEA,WACA,uBACA,OAEA,SACA,iCACA,UAEA,WACA,gDACA,GACA,kCAEA,oCAEA,aACA,IAEA,QACA,kBACA,mBAEA,kGACA,SAEA,UACA,WAUA,oCATA,CAOA,iCANA,CAIA,MAHA,6BAEA,MAEA,IAEA,IAGA,oBACA,cACA,YACA,YACA,SAEA,wBACA,oCAEA,cAQA,oCAPA,CAKA,iCAJA,CAEA,yBADA,MAEA,IAEA,IAGA,kBACA,yCACA,SACA,0BACA,cACA,eACA,iDACA,GACA,QACA,oBAEA,2BAIA,aACA,iBACA,sBACA,IAEA,cACA,cACA,cACA,WACA,WACA,eACA,sCACA,CAKA,MAJA,QACA,OACA,OACA,KAEA,IAAgB,iBAChB,SAEA,gBACA,wBACA,iBACA,gCAEA,aACA,IACA,EAEA,2BAEA,iBACA,uDAEA,EAIA,gBASA;;;;;CAPA,GAcA;;;;;IAUA;;;;;;;;IAOA;;;;;IAOA;;;;;IAOA;;;;;EAcA,4OAEA,OACA,kBAAmB,MAAqB,OACxC,gCAA0F,eAC1F,sCAAsG,mBACtG,sCAAsG,mBAEtG,wBAA+E,KAE/E,QAEA,GAEA,iBAMA,+NACA,SACA,aAAC,GAED,OACA,kBAAmB,MAAmB,OACtC,gCAAsF,mBACtF,wBAA2E,KAE3E,yBC5RA,aA4BA,aACA,qBAEA,kEACA,sBACA,CAMA,CAtCA,UACA,iBAEA,MACA,GACA,MACA,eACA,GACA,yBACA,kBACA,iBACA,OAeA,cAaA,+BACA,iBACA,uBAEA,sDACA,2BAEA,sDACA,iBACA,oBACA,mBACA,8BACA,mBACA,aAAuB,SAAY,EACnC,yBAEA,0BAEA,aAAuB,WAAY,MACnC,kBACA,KAAuB,SAAY,EACnC,SAEA,6BACA,YAAuB,SAAY,EACnC,iFAEA,IACA,CACA,WAEA,SACA,WACA,OAEA,wCACA,OACA,uBACA,QACA,mBAAmB,EAAO,IAC1B,SAEA,YACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IAEA,4DACA,OACA,IAAmB,EAAO,IAC1B,yCACA,oFACA,KACA,4BACA,iDACA,OACA,OACA,YACA,6BACA,sBAEA,aACA,qCAEA,oBAEA,gCACA,aACA,0BACA,UACA,IACA,IACA,MACA,iBACA,SACA,wBACA,oDACA,uDACA,qBACA,qCACA,wCACA,QACA,CAEA,CACA,IACA,QAEA,IACA,CACA,qBACA,8BAGA,kCAGA,4CACA,mBACA,aAAuB,SAAY,MACnC,WACA,YAA2B,EAAO,IAClC,8BACA,OACA,CAMA,IACA,MACA,KACA,cACA,uBAAe,SAAY,EAC3B,gCACA,uBACA,aACA,kBACA,kCAIA,cACA,SACA,aACA,YAIA,cACA,WAOA,EACA,kCACA,YACA,2BACA,CAOA,EACA,+BACA,kDACA,4FACA,+BAEA,YAEA,aAOA,EACA,mCAEA,yBACA,YAEA,iCACA,0CAEA,QAAmB,WAAmB,OACtC,iBAGA,gBAAmB,SAAY,EAC/B,wEAGA,GACA,QAUA,EACA,+CACA,cACA,QAAe,SAAY,EAC3B,gCAEA,QACA,QAQA,EACA,8BACA,cACA,qCAEA,YAEA,YAMA,EACA,qCACA,kDACA,+HACA,0GACA,iBAMA,EACA,kBACA,MACA,gBACA,0BACA,SAeA,MAdA,qCACA,gBAEA,iBACA,gBACA,0BACA,gBACA,kBAEA,mBACA,aACA,IACA,aACA,aAMA,EACA,6BACA,kDACA,qDACA,MAYA,wBAZoC,eACpC,kBACA,gBACA,OACA,uCAGA,oBACA,mBACA,6BAEA,YAGA,uCACA,iCACA,+CACA,UAAmB,MAAqB,OACxC,sEAEA,KACA,UAEA,2BC1UA,aAQA,eAAiD,MAA0C,oCAA4D,oCAEvJ,CAGA,eACA,MACA,OACA,QACA,UACA,0BACA,CAEA,CA2DA,aACA,iDACA,4BACA,cACA,cACA,cAEA,IAKA,aACA,eACA,MACA,QACA,iBACA,yBACA,sBACA,sBACA,WACA,KAnGA,qCACA,CACC,WAED,gBAAiC,gBAA2C,WAAgB,QAAkB,OAAO,MAA2B,oBAAwD,iBAAgC,gCAAuD,uCAA6D,MAAE,uBAAyD,CAAsJ,cAAjF,gBAA6D,QAAuB,CAAE,MAKljB,cAWA,aACA,uEAEA,KAEA,mCACA,QACA,OAEA,CA6CA,YA5CA,KACA,wBACA,YACA,mBACA,gBACA,gBACA,YAA2B,EAAU,IACrC,oFAEA,IACA,gBAA2B,EAAU,IACrC,MAEA,KAKK,GACL,KACA,4BACA,UACA,oCACA,CAKK,GACL,KACA,2BACA,2BACA,eACK,GACL,KACA,uBACA,aACA,0CAEA,YACA,OAGA,MACC,IAED,eAWA,MACA,KACA,QAWA,oCCtGA,WACA,CASA,0BAgBA,QACA,QAAgB,MAAc,OAC9B,WAEA,MACA,QAGA,IArBA,8BAEA,UAMA,aAIA,uCAoBA,MACA,wBACA,oBAEA,qBACA,CAGA,eAlBA,CACA,kEAGA,gEACA,kDACA,EAGA,EASC,+BCnDD,aACA,EAAQ,WAAa,EAAQ,GAAK,EAAQ,IAC1C,EAAQ,SAAW,EAAQ,IAC3B,EAAQ,UAAY,EAAQ,IAC5B,EAAQ,OAAS,EAAQ,GACzB,EAAQ,SAAW,EAAQ,IAC3B,EAAQ,WAAa,EAAQ,IAC7B,EAAQ,aAAe,EAAQ,IAC/B,EAAQ,QAAU,EAGlB,IACA,GAAI,GAAO,EAEX,QAAI,EAAW,EAAQ,IACvB,EAAK,SAAW,EAAS,SACzB,EAAK,WAAa,EAAS,WAC3B,EAAK,eAAiB,EAAQ,IAC9B,EAAK,GAAK,EAAQ,IAClB,EAAK,IAAM,EAAQ,IACnB,EAAK,OAAS,EAAQ,OACtB,EAAK,aAAe,EAAQ,IAC5B,EAAK,OAAS,EAGd,IACA,GAAI,GAAO,EAAe,QAE1B,EAAK,MAAQ,EAAQ,GAAW,MAChC,EAAK,OAAS,EAAQ,GAAW,OACjC,EAAK,IAAM,EAAQ,IACnB,EAAK,YAAc,EAEnB,IACA,GAAI,GAAe,EAAuB,gBAE1C,EAAa,cAAgB,EAAQ,IACrC,EAAa,mBAAqB,EAElC,IACA,GAAI,GAAM,EAAc,OACxB,EAAI,MAAQ,EAGZ,IACA,GAAI,GAAK,EAAa,MAEtB,EAAG,GAAK,EAAQ,IAChB,EAAG,gBAAkB,EAAO,GAC5B,EAAG,IAAM,EAAQ,IACjB,EAAG,IAAM,EAAQ,IACjB,EAAG,WAAa,EAAQ,IACxB,EAAG,IAAM,EAGT,IACA,GAAI,GAAQ,EAAgB,SAE5B,EAAM,OAAS,EAAQ,IACvB,EAAM,OAAS,EAGf,IACA,GAAI,GAAK,EAAQ,GAAK,EAAa,MAEnC,EAAG,IAAM,EAAQ,IACjB,EAAG,IAAM,EAAQ,qBCpEjB,+BCAA,UACA,WACA,iCAEA,MAOA,mBACA,OACA,MAEA,EACA,IAEA,EACA,CAYA,uBACA,IACA,MACA,YAEA,GACA,UAEA,KACA,oBAEA,+BACA,cAEA,QACA,eACA,GACA,YAEA,QAGA,kCACA,YAOA,mBACA,OACA,WAEA,OACA,uBACA,IAOA,iBACA,OACA,EAYA,MAXA,WAEA,SACA,QACA,YACA,KACA,SAEA,MAEA,KAeA,mBACA,IACA,GAOA,MANA,WAEA,SACA,KACA,SACA,MAQA,mBACA,IACA,GAQA,MAPA,WAEA,eACA,uCACA,OAEA,OAQA,iBACA,eACA,MACA,UAEA,iBACA,CACA,8BAAsD,YAAmC,aAA0B,MACnH,QACA,QAAK,cACL,UACA,cAAqC,QAAW,IAChD,MACA,YAEA,UACA,QAQA,mBACA,IACA,MACA,UAEA,SACA,YAGA,iBACA,OACA,QAOA,mBACA,aACA,KACA,UAEA,eACA,QACA,OAEA,aACA,WACA,kBAAoC,QAAW,IAC/C,MACA,KAEA,0BACA,SAOA,mBACA,uBACA,KACA,UAEA,oBACA,mBACA,WACA,OAEA,0BACA,OACA,kBAAsC,QAAW,IACjD,MACA,KACA,mBACA,UACA,mBAGA,IACA,QACA,KACA,OACA,oBAAkD,kBAAsC,eACxF,WAEA,QACA,QAEA,qBACA,SACA,MACA,UAEA,OACA,UACA,WACA,IACA,cACA,CACA,OACA,IACA,QACA,CACA,KACA,OACA,OAEA,mBACA,aACA,MACA,UAEA,SACA,OACA,MACA,WACA,EACA,SACA,SACA,kBAEA,UACA,KACA,UAEA,QACA,QACA,UAEA,cACA,cAiBA,UACA,iBACA,QAEA,CAmEA,SAtFA,SAEA,QAEA,YAEA,YAEA,YAEA,eAEA,aAEA,wCAMA,4BACA,IAEA,4BACA,0BACA,IAEA,6BACA,mBACA,EAEA,kCACA,QACA,yBAEA,iCACA,4BACA,IAEA,iCACA,4BACA,IAEA,gCACA,0BACA,IAEA,oCACA,4BACA,IAEA,8BACA,aACA,QAEA,8BACA,OACA,sBAEA,6BACA,mBACA,MAEA,8BACA,IACA,GAGA,SAFA,+BACA,IAGA,gCACA,yBACA,EAEA,iCAEA,iCAEA,mCAEA,iCAEA,sCAEA,OAIA,iBAEA,wEAMA,WAAG,iBACH,CACA,QAEA,EAAC,+BCtXD,aAoGA,aACA,sBACA,UAAkB,MAAyB,OAC3C,iBAGA,cAAe,MAAmB,OAClC,cAAsB,SAAsB,OAC5C,YAIA,QACA,QASA,CAxHA,aAUA,MA0MA,UACA,CACA,mBA3MA,aACA,IACA,mCAGA,gFACA,WAEA,WACA,IAAkB,QAAkB,YACpC,GACA,mBAAsB,EAAgB,IACtC,WAGA,KACA,OACA,GAEA,CACA,QAcA,EA0KA,wBAzKA,aACA,IACA,mCAGA,8EACA,aACA,WAAmB,MAA6B,OAChD,SAGA,eAAc,MAAkB,OAChC,eAAsB,IAAgB,IACtC,QACA,eAIA,KACA,QAWA,EA4IA,wBA3IA,WACA,+BACA,UACA,IAAkB,SAA2B,OAC7C,cAAsB,MAAwB,OAC9C,SACA,QAIA,IACA,QASA,EAwHA,sBACA,mBAjGA,WACA,+BACA,UACA,IAAkB,MAAmB,OACrC,cAAsB,SAAsB,OAC5C,SACA,QAIA,IACA,QAUA,EA6EA,sBACA,gBA7EA,aACA,OACA,cACA,QACA,IAEA,MACA,IAGA,iCACA,IAEA,WAAmB,IAAgB,QACnC,GACA,YAAuB,MAA2B,OAClD,cAEA,KACA,MAEA,CACA,QAQA,EAgDA,MA/CA,aACA,IACA,KAIA,kBAEA,kBACA,QACA,OACA,uBACA,+BACA,2BACA,SAAwB,WACxB,iBAIA,0BACA,SACA,QAAwB,WACxB,SAKA,gBACA,+BACA,SACA,QAAwB,WACxB,SAIA,OACA,0BC5LA,aAqDA,qBACA,oBA8BA,cACA,IAEA,SA/BA,kBACA,KAGA,IADA,IAGA,kBACA,8BAGA,GACA,MAEA,IACA,MACA,MACA,OAEA,IACA,IACA,IACA,IACA,IAEA,IACA,IAEA,cAKA,cAEA,WACA,cAEA,UACA,OAEA,IACA,WAEA,MACA,IACA,KACA,GAEA,OACA,aACA,WAGA,QAEA,WACA,IAEA,IACA,OACA,OACA,KACS,KACT,QACA,OAGA,KACA,aACA,MAEA,CACA,QAWA,CACA,qBACA,SAEA,kBACA,8BAGA,KACA,IAHA,IAMA,SACA,MAEA,MACA,KACA,MACA,OACA,KACA,EAEA,OAGA,IAEA,IACA,IAEA,cACA,yBACA,6CAGA,QACA,IAGA,kBACA,IAEA,IACA,WAEA,MACA,IACA,OACA,IACA,CAEA,CACA,MACA,KAGA,aACA,MAEA,IACA,IAEA,IACA,OACA,OACA,KAEA,MACA,OACA,EAEA,IAEA,CACA,QAUA,CACA,mBACA,iCACA,KAEA,uBAnOA,eACA,oBACA,iBACA,sBAGA,mBACA,gBACA,4BAEA,gEAEA,mCACA,mBACA,iCAEA,uEACA,iBACA,iCAGA,uCACA,SACA,IACA,KACA,IACA,GAEA,uCACA,6BACA,iCAEA,kDACA,yBAEA,6EAEA,kCAEA,wBACA,WAWA,EAiLA,E,4BC7PA,aAEA,MASA,WACA,aACA,YACA,yBACA,UAAmB,MAAiB,OACpC,UAEA,UACA,UAhBA,WAOA,kBCRA,CACA,uBAAe,EAAS,UACxB,QACA,OAEA,UACA,EAEA,IACA,OAEA,E,uBCbA,aACA,QACA,MACA,SAEA,0BACA,aA4BA,SACA,QACA,EACA,SACA,kBACA,SAA2B,EAAS,MACpC,UACA,OACA,MACA,OACA,MACA,CAAS,KACT,CACA,aACA,GACA,EACA,WACA,gBACA,EACA,IACA,kBACA,MACA,cACA,YACA,MACA,MACA,QACa,MACb,UACA,SAEA,QACA,YACA,OACA,MACA,MAEA,CACA,CACA,OACA,EAEA,UArEA,yBACA,WACA,WACA,mBACA,KAGmB,MAAnB,EAA0B,IAC1B,IACA,kBACA,EAIA,QAAe,EAAO,IACtB,SAIA,YAAe,MAAc,OAC7B,iBACA,SACA,OACA,OAGA,KA4CA,6BACA,QACA,UACA,aAEK,gBACL,4BACA,QACA,UACA,OACA,UAGA,6BAEA,8BCxFA,aACA,OAMA,iBACA,oBACA,uBAEA,mDACA,uBAEA,gEACA,cAEA,QAMA,eACA,eACA,IAAuB,gBAAwB,OAC/C,cAA2B,gBAAwB,OACnD,kBACA,qBAIA,uBACA,IAMA,kBACA,WACA,IAAuB,gBAAwB,OAC/C,cAA2B,gBAAwB,OACnD,YAGA,aACA,QACA,EAEA,4BCpDA,CACA,QACA,OAwDA,IA0cA,E,QAxcA,uCAEA,OAKA,KACA,kCAAwB,WACxB,UAKA,SAEA,WACA,WACA,mBACA,eACA,KACA,SACA,WAGA,aAVA,wBAWA,aAEA,yEACA,sBACA,aAEA,EAEA,MAEA,6BACA,mBACA,8BACA,0BACA,UAGA,6CAEA,WACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,OAOA,MAzDA,yBA0DA,WACA,aAAwB,IACxB,SACA,IACA,GAGA,IACA,cAAgB,WAChB,IACA,cAIA,gBACA,OAEA,OAEA,8BAIA,gCACA,QACA,gBAGA,UAMA,4CACA,2DAIA,IACA,sBACA,yEACA,uBAKA,MACA,MAGA,uBACA,YAGA,GAGA,cACA,eAIA,OAGA,mDAKA,gDAWA,0BACA,gBAAoB,WACpB,WAEA,cAEA,iBAAoB,WACpB,sCAIA,uBAIA,wCAEA,0BAGA,oBACA,0FAEA,SACA,2BAA4B,WAC5B,WAGA,UACA,mBAEA,2BAGA,0CACA,iBAGA,uEAEA,cAEA,UACA,IACA,IACA,IACA,IAEA,2BACA,6DAIA,EACA,eAEA,eACA,uBAEA,YACA,6CACA,WAKA,YACA,IACA,qCACA,6DAKA,GACA,eAEA,cACA,sBAEA,MACA,eACA,QAIA,WAKA,2DAEA,yBACA,iBACA,OAEA,2BACA,2DA+BA,EAAgB,KAChB,KAEA,+BAyBA,SACA,WAEA,gCAEA,qBAEA,uBAEA,aAA6B,QAE7B,wBACA,mBAGA,MACA,cAEA,SAIA,iDACA,UAAgC,IAChC,iBAIA,OACA,iBAEA,qDACA,UAAgC,IAChC,iBAGA,EAGA,MAEA,IAEA,CAEA,QAGA,kCAYA,SAGA,kBACA,aAOA,eAHA,2DACA,qBAIA,2CAoCA,SACA,WAEA,SAMA,cAGA,uBAEA,SAIA,0BAIA,gCAIA,4CAEA,sBAIA,gEAGA,yBAGA,yBAAgB,gCAEhB,IAIA,oBCpgBA,aAEA,iBACA,sBACA,gDCJA,aAEA,2BACA,aACA,uBACA,kBACA,mBACA,eACA,qBACA,aACA,oBACA,iBACA,kBACA,eACA,sBACA,mBACA,sBACA,qBACA,gBACA,kBACA,0BACA,uBACA,qBACA,mBACA,yBACA,yBACA,sBACA,oBACA,mBACA,kBACA,mBACA,eACA,gBACA,iBACA,gCACA,iBACA,iBACA,kBACA,iBACA,qBACA,gCACA,gBACA,kBACA,gBACA,cACA,iCC7CA,uBACA,CAGU,UAFV,MACA,SACA,EAAkB,IAClB,iDAEA,YACA,mBCRA,uBACA,aACA,SACA,IACA,IACA,IAAmB,EAAS,IAC5B,aACA,MACA,KACA,MAGA,iBACA,gBCbA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,cAEA,aACA,mBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,0BAEA,MACA,uBCPA,uBACA,aACA,SACA,IACA,IAAmB,EAAS,IAC5B,aACA,MACA,MAGA,KACA,uBCXA,uBACA,CAGU,UAFV,MACA,SACA,EAAkB,IAClB,oDAEA,cACA,uBCRA,aAEA,cAEA,uBACA,UACA,qBCNA,uBACA,CAGU,UAFV,MACA,SACA,EAAkB,IAClB,kDAEA,aACA,mBCRA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,cAEA,MACA,uBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,cAEA,YACA,mBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,uBAEA,YACA,mBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,cAEA,iBACA,mBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,YAEA,KACA,uBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,0BAEA,MACA,uBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,iEAEA,GACA,uBCPA,uBACA,aACA,SACA,IACA,IAAmB,EAAS,IAC5B,2BACA,8BAEA,mBACA,gBCTA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,2BAEA,OACA,uBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,mBAEA,MACA,uBCPA,uBACA,aACA,SACA,IACA,IACA,IAAmB,EAAS,IAC5B,YACA,aACA,aAEA,eACA,qBCXA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,+CAEA,MACA,uBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,sBAEA,GACA,uBCPA,uBACA,CAGU,UAFV,MACA,SACA,EAAkB,IAClB,cAEA,MACA,uBCRA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,cAEA,iBACA,mBCPA,yBACA,CAGU,UAFV,MACA,SACA,EAAkB,IAClB,gBAEA,oBACA,mBCRA,uBACA,CAGU,UAFV,MACA,SACA,EAAkB,IAClB,+BAEA,KACA,uBCRA,uBACA,CAGU,UAFV,MACA,SACA,EAAkB,IAClB,+BAEA,KACA,uBCRA,uBACA,CAGU,UAFV,MACA,SACA,EAAkB,IAClB,qCAEA,YACA,mBCRA,uBACA,aACA,SACA,IACA,IAAmB,EAAS,IAC5B,cACA,gBAEA,YACA,mBCTA,uBACA,aACA,SACA,IACA,IAAmB,EAAS,IAC5B,cACA,gBAEA,YACA,mBCTA,uBACA,aACA,SACA,IACA,IAAmB,EAAS,IAC5B,cACA,cAEA,WACA,mBCTA,uBACA,CAGU,UAFV,MACA,SACA,EAAkB,IAClB,qCAEA,MACA,uBCRA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,6CAEA,QACA,2BCPA,YAEA,yBACA,CACA,cAEA,qBACA,SACA,IACA,IACA,IAAuB,EAAS,IAChC,OACA,QACA,eAEA,uBAEA,qBCjBA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,sDAEA,OACA,uBCPA,uBACA,aACA,SACA,IAAmB,EAAS,IAC5B,6BAEA,MACA,2BCPA,aAEA,eACA,oBACA,cACA,sBACA,iBACA,oBACA,gBACA,iBACA,sBACA,kCCXA,YAEA,uBACA,UACA,yBCJA,YAEA,uBACA,UACA,yBCJA,YAEA,uBACA,UACA,yBCJA,YAEA,uBACA,UACA,yBCJA,YAEA,uBACA,UACA,yBCJA,aAEA,WACA,cAEA,uBACA,aACA,YAEA,kBACA,kBACA,UAAiB,MAAe,OAChC,SACA,YAGA,aACA,0BCjBA,YAEA,uBACA,UACA,yBCJA,aAEA,YAEA,iBACA,eACA,CAEA,8CACA,cACA,WACA,CAEA,eACA,IACA,uCAGA,gDACA,SACA,EAEA,6BCtBA,UACA,YAEA,MAEA,aAKA,qEACA,wEACA,wCAGA,gFACA,iFACA,UAGA,oFACA,yEACA,WAGA,sFACA,yEAGA,iFACA,4EACA,oBAGA,kFACA,iFAGA,+EACA,gFACA,UAGA,kFACA,0EACA,8BAGA,kFACA,6EACA,oBAGA,+EACA,iFACA,UAGA,6EACA,yEACA,8BAGA,4BACA,kDACA,0EACA,8BAGA,+DACA,6DACA,0DACA,YAEA,UAUA,YARA,WACA,OACA,eACA,SAEA,IACA,MAGA,kCCrFA,aAcA,iBACA,QACA,WAAmB,MAAqB,OACxC,cAAuB,QAAqB,OAC5C,cACA,QAGA,OACA,QAQA,CACA,iBACA,YACA,IAAmB,MAAqB,OACxC,cAAuB,QAAqB,OAC5C,cACA,QAGA,OACA,QAQA,CACA,iBACA,WACA,IAAmB,MAAqB,OACxC,cAAuB,MAAqB,OAC5C,eAGA,2BACA,OAQA,CACA,iBACA,4BACA,UAAmB,MAAqB,OACxC,cAAuB,MAAqB,OAC5C,4BAGA,YACA,KAQA,CACA,iBACA,OACA,wCACA,QAEA,eACA,OACA,KAEA,eACA,cAEA,yBAEA,iBACA,aACA,SACA,QAEA,kBAEA,KAvGA,UACA,OACA,QACA,QAQA,IA8FA,MACA,CACA,eACA,SAUA,qBA0HA,UAzHA,aACA,UACA,uBACA,OACA,SACA,2BAKA,UACA,iCACA,UACA,WACA,OACA,UACA,aACA,OACA,UACA,YACA,OACA,UACA,aACA,OACA,UACA,SACA,OACA,MACA,6BAEK,uCACL,8CAGA,0CACA,WAAmB,MAAqB,OACxC,SAEA,gBACA,OACA,OAEA,cAEA,CACA,KACA,gBAAuB,MAAiB,OACxC,gBAA+B,MAAiB,WAChD,OACA,KACA,yBACiB,WACjB,oBACA,kBAAmC,MAAsB,OACzD,uBAEA,KACA,IACA,yBACiB,WACjB,oBACA,kBAAmC,MAAsB,OACzD,uBAEA,KACA,yBACA,GACA,uBAEA,mBAEA,SACA,MAGA,uBACA,cACA,UAEA,EADA,cAEA,KACA,kBAA2B,QAAiB,OAC5C,gCAEA,QACA,gBACA,cACA,8BAEA,QACA,gBACA,OACA,uBACA,EAEA,GACA,MACA,GAEA,mBAAwB,QAAuB,WAC/C,GACA,sBACA,WACA,mBACA,mBACA,IAA4B,SAA2B,OACvD,IACA,iCAEA,0BACA,sCAEA,oCAEA,WACA,WACA,OACA,CACA,UACA,qBChPA,aAaA,iBACA,QACA,WAAmB,MAAqB,OACxC,WAAuB,WAAqB,OAC5C,aACA,QAGA,OACA,QAQA,CACA,iBACA,YACA,IAAmB,MAAqB,OACxC,WAAuB,WAAqB,OAC5C,aACA,QAGA,OACA,QAQA,CACA,iBACA,WACA,IAAmB,MAAqB,OACxC,cAAuB,MAAqB,OAC5C,cAGA,2BACA,OAQA,CACA,iBACA,WACA,IACA,IACA,IACA,IAAmB,MAAqB,OACxC,YACA,WAEA,aAAmB,MAAqB,OACxC,YACA,WAEA,eACA,YACA,YACA,YACA,eACA,MAQA,CACA,iBACA,WACA,IACA,IACA,IACA,IAAmB,MAAqB,OACxC,YACA,WAEA,aAAmB,MAAqB,OACxC,YACA,WAEA,eACA,YACA,YACA,YACA,oDACA,OASA,CACA,iBACA,WACA,GACA,IAGA,gBACA,UAAmB,SAAyB,OAC5C,aAEA,4BACA,UAAmB,SAAyB,OAC5C,aAGA,iBACmB,IAAnB,MAAkC,WAClC,GACA,YAAuB,MAAe,OACtC,IACA,kBAGA,mBACA,IACA,YAAuB,MAAe,OACtC,cAEA,WACA,aACA,QACA,MAEA,IACA,CACA,SAeA,iBACA,WACA,IACA,IAAmB,MAAkB,OACrC,WAAuB,SAAkB,OACzC,8BACA,QAGA,UACA,IAOA,CA1LA,UACA,OACA,QAQA,IAkJA,MACA,CACA,YAUA,UAuIA,UApHA,aACA,aACA,eACA,iCACA,UACA,WACA,OACA,UACA,aACA,OACA,UACA,YACA,OACA,UACA,aACA,OACA,UACA,SACA,OACA,MACA,6BAEK,uCACL,8CAEA,sCACA,yBACA,wBACA,kBAAqB,MAAmB,OACxC,kBACA,oBAGA,kCACA,gBAGA,QAFA,IACA,cAEA,GACA,IACA,YAAuB,MAAiB,WACxC,GACA,YAA2B,SAAoB,OAC/C,gBAAqC,SAAoB,OACzD,sDAGA,WACA,MACA,IAEA,IACA,MACA,EACA,8DACA,gEACS,sCACT,uDACA,UACA,+CACA,sDAEA,mCACA,CAAS,KACT,WACA,QACA,0BACA,cAA6B,SAA2B,OACxD,MAEA,kBAA4B,SAA0B,WACtD,GACA,YAAgC,SAA0B,OAC1D,IACA,qEAGA,wBACA,EACA,MACA,IAEA,IACA,UACA,kBACA,aACA,MACA,wBACA,oBACA,aAEA,uBACA,2BACA,kBAA2B,MAAkB,OAC7C,+BACA,+BACA,kCAEA,wBACA,2BACA,kBAA2B,MAAkB,OAC7C,+BACA,+BACA,kCAEA,gCACA,+BACA,QACA,UACA,sBACA,KACA,YACA,EACA,CACA,2BC/SA,aAEA,aAEA,UACA,OACA,GAeA,UAbA,KACA,eACA,UACA,4BACA,+BACA,KAEA,aACA,SACA,wBACA,QACA,gBCnBA,aAEA,QACA,QACA,WACA,QACA,GAoBA,UAlBA,KACA,eACA,UAEA,6BACA,uBACA,sBACA,KAEA,aACA,WACA,IAAuB,MAAc,OACrC,YAEA,8CACA,OACA,gBCxBA,aAEA,QACA,OACA,oBACA,GAkBA,UAhBA,KACA,eACA,UACA,4BACA,sBACA,QAEA,aACA,WACA,IAAuB,MAAc,OACrC,YAEA,gCACA,SACA,iCClBA,aACA,MACA,yBAEA,mBACA,kBACA,8BAGA,8BACA,SACA,UACA,UACA,SAEA,QAAe,EAAe,QAC9B,OACA,OACA,QAAmB,EAAO,QAC1B,OACA,OACA,QAAuB,EAAO,IAC9B,YAEA,wBACA,WACA,GAEA,OAEA,aACA,kBACA,QAAuB,EAAe,IACtC,YAEA,CAEA,IACA,mBAGA,wCACA,YA3CA,GA6CA,YACA,4BACA,aACA,CACA,mBACA,OAEA,0BACA,MAEA,UACA,yBAGA,0CACA,YACA,YAEA,QAAmB,EAAe,IAClC,UAAuB,EAAW,QAClC,OAA2B,EAAO,IAClC,qBAEA,iBACA,OAGA,SAA+B,EAAQ,KACvC,UAAuB,EAAW,QAClC,SAA+B,EAAe,IAC9C,qBAEA,iBACA,OAGA,CACA,QAGA,uCC/EA,eACA,aACA,iBACA,yBAEA,qBACA,kBACA,2BAGA,yCACA,uBACA,KACA,WACA,SACA,IAGA,OADA,WAIA,mBAGA,gBACA,OAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,UAAK,KACL,oBACA,KACA,eAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,YAEA,MACA,SACA,SACA,SACA,IAoCA,mBAEA,eACA,IAEA,QAAe,EAAO,IACtB,aAGA,cAAmB,EAAO,QAC1B,OACA,IACA,IAAmB,EAAO,IAC1B,SAGA,SACA,mBACA,KAAuB,EAAO,IAC9B,aACA,cACA,UAES,MACT,OAAuB,EAAO,IAC9B,IACA,gBAGA,eACA,KACA,KACA,QAGA,SACA,OACA,WACA,MAAuB,EAAO,IAC9B,SAGA,QAAuB,EAAO,QAC9B,OACA,KACA,iBACA,cAA+B,OAAY,EAC3C,eACA,WAEA,UACA,MAEA,OACA,IAAuB,EAAO,IAC9B,IACA,gBAGA,cACA,OAAuB,EAAO,IAC9B,YAGA,WAAuB,EAAO,QAC9B,OACA,OACA,KAA2B,SAAY,EACvC,sBAEA,cACA,cACA,CACA,CACA,CACA,MAEA,OAAe,MAAW,MAC1B,cACA,gBACA,QACA,SACA,OAAuB,EAAQ,KAC/B,gBAGA,WAAuB,EAAQ,SAC/B,OACA,IAA2B,EAAQ,KACnC,iBAEA,cAA2B,EAAQ,KACnC,eAEA,IACA,CAEA,OAAmB,EAAQ,KAC3B,cAEA,CAEA,OAAe,EAAO,IACtB,aACA,gBAGA,cACA,OACA,EAEA,mBAEA,qBACA,cACA,EAEA,QAAe,EAAO,IACtB,WAGA,YAEA,QACA,IACA,EAEA,8BAAe,EAAO,QACtB,qBACA,OACA,IACA,gBAGA,MAGA,WACA,GACA,IAGA,WACA,qBACA,mBACA,GACA,QAGA,eACA,kBACA,WACA,OACA,SAA+B,EAAO,IACtC,IAKA,mBACA,OACA,EACA,IACA,UACA,KACA,IACA,MAA+B,EAAQ,KACvC,QACA,IACA,IACA,QACA,OACA,iBACA,aACA,MACA,SACA,aACA,sBAEA,QAA+B,EAAO,IACtC,aACA,uBACA,sBAIA,eACA,YACA,SAEA,GACA,eACA,IACA,CACA,aACA,CAEA,OAAe,MAAW,MAC1B,KACA,MACA,SAAuB,EAAO,IAC9B,IACA,SACA,MAIA,SACA,eACA,KACA,SAAuB,EAAO,IAC9B,MACA,gBACA,QAGA,SACA,EAEA,mBAEA,OACA,MACA,YACA,EAEA,UAAqB,OAAe,MACpC,OACA,EAAmB,IAAW,KAC9B,gBAGA,aACA,OACA,EAA0B,IAAQ,KAClC,gBACA,aAGA,WACA,KACA,WAGA,OACA,OAEA,QAAuB,IAAO,QAC9B,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,OAAuB,EAAW,SAClC,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,QACA,eACA,GACA,CAEA,OAAe,EAAO,IACtB,UAAmB,EAAO,IAC1B,oBAIA,UAAsB,OAAc,EACpC,qBACA,SAA2B,EAAW,KACtC,gBAGA,OAAuB,IAAW,SAClC,OACA,EAA2B,IAAW,KACtC,YAGA,4BACA,GAA2B,IAAW,KACtC,eAEA,IACA,CAEA,EAEA,qBACA,SACA,IACA,MACA,EACA,0BACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,kBACA,QACA,IAEA,QAAe,EAAQ,IACvB,cACA,YACA,aAGA,WAAoC,GAAQ,IAC5C,SAIA,oBACA,KACA,IACA,yBACA,SACA,QAEA,oBAGA,OAGA,OACA,MACA,gBACA,aACA,EACA,MACS,kBACT,oBACA,8BACA,IACA,UACA,MACA,gCACA,OAEA,aACA,gBACA,WACA,aACA,GACA,eAEA,YACA,OACA,WACA,UACA,OACA,MACA,YAIA,mBAA+B,EAAQ,IACvC,UACA,sBACA,0BAGA,UAA2B,EAAQ,KACnC,aACA,mBACA,0BAGA,QAA6B,IAAW,KACxC,aACA,mBACA,0BAEA,GACA,aACA,SACA,QACA,UAGA,MACA,IACA,CAAS,KACT,MACA,UACA,IACA,EACA,iBACA,mBAGA,aACA,KACA,KAA6B,IAAQ,KACrC,IAEA,qCACA,QACA,UACA,UAEA,IACA,gBACA,IACA,WACA,OACA,KACA,QAEA,iBACA,KAAiC,IAAQ,KACzC,IAEA,WACA,WACA,KAKA,aACA,EACA,SACA,UACA,MACA,+BACA,cACA,oBACA,eAIA,oBAGA,2EAGA,QAGA,YAA2B,EAAQ,KACnC,cACA,MACA,cAIA,OAAuB,SAAY,YAEnC,EACA,iBACA,cACA,mBACA,cACA,KAOA,yBAIA,OAjBA,mBAkBA,KACA,QAGA,UACA,KACA,MAEA,0BAIA,cALqB,YAMrB,MACA,MAIA,cAA+B,IAAQ,IACvC,oBAEA,mBACA,0BAGA,cACA,wBAGA,UAA+B,WAAyB,GACxD,yBAEA,mBACA,uBAGA,KACA,+BAGA,QAAiC,IAAW,KAC5C,yBAEA,mBACA,uBAGA,KACA,+BAEA,GAEA,CACA,CAEA,IAIA,eAAoB,EAAQ,KAC5B,SACA,OAEA,KACA,UACA,YACA,MAA2B,EAAQ,SACnC,OACA,YACA,EAA2B,IAAQ,KACnC,eAGA,WACA,OACA,IAEA,YACA,IACA,2BAEA,oBACA,SACA,+BACA,YACA,OACA,6CAGA,YACA,SACA,YAAmC,IAAQ,KAC3C,IAIA,UACS,SACT,YAEA,qBACA,6BACA,iCAEA,+BACA,sBACA,eAGA,cACA,UACA,MAA2B,EAAQ,SACnC,OACA,IACA,EAA2B,IAAQ,KACnC,sBACA,cAGA,aAEA,UACA,OACA,IACA,IAEA,YACA,IACA,iBACA,oBACA,aAEA,cACA,SACA,oCACA,MACA,oBACA,mCAEA,+BACA,qBACA,aACA,aACA,oCACA,4CAEA,gCACA,2BACA,eAIA,wBACA,UACA,YAAmC,IAAQ,KAC3C,qBACA,KAIA,UAIA,OAAe,EAAQ,IACvB,YACA,QAAuB,IAAQ,IAC/B,YAKA,gBAAoB,EAAU,KAC9B,QAAqB,IAAW,SAChC,OACA,EAAyB,OAAwB,OACjD,eAEA,QACA,SAEA,GAEA,mBACA,OACA,cACA,QACA,QACA,kBAEA,YACA,QACA,gBAEA,UAEA,gBAtwBqC,IAErC,QACA,CAGA,oBAmDA,YACA,sBACA,aACA,CACA,4BACA,aACA,CACA,yBACA,0BACA,yBAEA,SACA,CACA,sBACA,YACA,SACA,SACA,OACA,YACA,QAAmB,EAAO,QAC1B,OAAuB,EAAO,IAC9B,YAEA,UACA,KACA,iBACa,KACb,mBAEA,KACA,CACA,QACA,uCChFA,eACA,cACA,qBACA,2DACA,aATA,WACA,cACA,6BACA,qCALA,yzBCKkD,cCRlD,QACA,oCACA,oDCFA,GAEA,mBACA,iBACA,gBACA,QACA,QAEA,WACA,+BACA,UACA,IAEA,OACA,+BACA,OACA,8CChBA,GAEA,mBACA,eACA,kBACA,QAEA,WACA,yCACA,KACA,IAEA,SACA,yCACA,EACA,8CCfA,GAEA,mBACA,eACA,kBACA,QAEA,WACA,oCACA,OACA,IAEA,SACA,oCACA,IACA,8CCfA,GAEA,mBACA,iBACA,aACA,cACA,KAEA,WACA,6BACA,SACA,IAEA,SACA,6BACA,MACA,qDCfqB,IAErB,mBACA,mBACA,WACA,0CACA,0BACA,yBACA,MAEA,WACA,gDACA,oBACA,IAEA,SACA,gDACA,iBACA,qDClBmB,IAEnB,mBACA,uBACA,KACA,kCACA,QACA,gBACA,aAEA,WACA,6CACA,iBACA,IAEA,SACA,6CACA,cACA,8CCnBA,GAEA,mBACA,eACA,qBACA,KAEA,WACA,oBACA,WACA,IAEA,SACA,oBACA,QACA,qBCfA,aAEA,QACA,OACA,SACA,GAoBA,UAlBA,KACA,eACA,UACA,4BACA,oBACA,MAEA,aACA,WACA,iBACA,UAAuB,EAAU,KACjC,+BACA,2BAEA,QACA,QACA,oBCvBA,aAEA,aAEA,UACA,OACA,GAaA,UAXA,KACA,eACA,UACA,4BACA,KAEA,aACA,qCACA,OACA,oBCjBA,aAEA,UAEA,KACA,OACA,GAeA,UAbA,KACA,eACA,UACA,4BACA,+BACA,KAEA,aACA,SACA,wBACA,QACA,gBCnBA,aAcA,UAZA,KACA,aACA,wBACA,UACA,IAAuB,EAAS,IAChC,cAGA,MACA,QACA,oBCZA,aAEA,UAEA,KACA,OACA,GAcA,UAZA,KACA,eACA,UACA,4BACA,KAEA,aACA,SACA,wBACA,MACA,oBClBA,aAEA,aAEA,UACA,UACA,GAaA,UAXA,KACA,eACA,UACA,+BACA,QAEA,aACA,oCACA,SACA,oBCjBA,aAEA,aAEA,UACA,UACA,GAcA,UAZA,KACA,eACA,UACA,+BACA,QAEA,aACA,SACA,0BACA,SACA,oBClBA,aAcA,qBACA,MACA,gBACA,iBACA,iBACA,aACA,SAMA,CAxBA,UACA,aAUA,YAcA,+BACA,eACA,wCACA,UACA,QACA,kCACA,QAOA,EACA,0CACA,yCACA,OACA,CACA,iBACA,OAEA,EAEA,KAAmB,MAAiB,OACpC,gEACA,kCAGA,iBAAmB,mBAA2B,OAC9C,qBAGA,iEACA,UAEA,6BC9DA,aAEA,cAQA,OAkEA,SAjEA,aACA,SACA,mBAEA,WAAmB,EAAO,IAC1B,WAEA,OACA,QASA,EAiDA,cAhDA,eACA,OAGA,mCAEA,YAEA,YAAuB,eACvB,KAAuB,MAAiB,OACxC,iBACA,kBACA,SAGA,mBAEA,MAEA,cAA2B,IAAO,QAClC,IAA8B,eAC9B,aAA+B,QAAiB,WAGhD,IAAuC,cACvC,aAAmC,EAAO,IAC1C,qBACA,qBACA,MACA,QAKA,+BACA,gBAEA,aAEA,QACA,KAEA,CAEA,mBACA,sBC1EA,aAWA;;;;;;;;;EAGA,iBACA,MACA,gBACA,gBACA,UACA,cACA,YAEA,iBAEA,kBAGA,WACA,OACA,EAEA,QACA,cAEA,KACA,qBAGA,6BACA,kBACA,KAEA,gBACA,WACA,kCACA,8BAGA,OAGA,OAzBA,sCAkDA,iBAvBA,cAGA,GACA,cACA,aAGA,SACA,gBACA,aAEA,OAEA,GAZA,WAaA,KAGA,CACA,+BAKA,YACA,oCACA,MAGA,kCAFA,oCACA,SAGA,yBACA,gBAEA,IACA,SAGA,mBACA,yBACA,WAEA,YAEA,QAEA,mBACA,MACA,EAEA,QACA,mCAIA,wCACA,gBAEA,kBACA,SAEA,SAEA,QAEA,yBACA,cAGA,IACA,eAGA,WACA,QAGA,mBAEA,yBACA,WAEA,YAEA,QAEA,cACA,gBAKA,IACA,GACA,EACA,EACA,EAEA,QACA,UAGA,QAEA,OACA,eACA,oBAKA,aACA,aACA,cACA,SAEA,gBACA,WAEA,0BACA,SAGA,OAEA,IArCA,GACA,EAEA,wBAmCA,eACA,4BAIA,oBAEA,kCACA,qBAEA,oBAQA,YACA,6BAMA,eACA,IACA,eACA,YACA,OAGA,sBAZA,eACA,IACA,OAEA,OAUA,IA5FA,OA8FA,MAEA,UACA,IAEA,8BACA,cASA,gBASA,QACA,SACA,YAEA,KAEA,WAbA,mBACA,KACA,KAHA,EAIA,EACA,EAEA,QAOuB,MAAuB,UAC9C,gBACA,YAEA,YAIA,qBAEA,qBACA,2CACA,KAKA,eACA,iBACa,KACb,gBAEA,aACA,SAEA,OAIA,MAEA,6BACA,KAGA,kCACA,cACA,OAEA,QAEA,KACA,UAGA,MAEA,IAtEA,GACA,EAEA,EAoEA,KAnEA,iBAA0B,UAAc,EAGxC,WAgEuB,EAAc,OACrC,UAIA,eACA,UAEA,MAEA,OAAmB,kBAAkD,WACrE,eACA,6CAGA,KACA,QAEA,+BACA,cACA,OACA,UAEA,0BACA,CAEA,cACA,OACA,UAEA,uBACA,CAEA,yBACA,0BACA,CAGA,CAEA,aACA,MACA,gBACA,gBAEA,YACA,iBAEA,cAEA,0CACA,EAEA,gBAEA,oBAEA,kBAGA,MAKA,MAJA,sCACA,mBAEA,KAGA,iBACA,qBACA,EAEA,oBACA,wBAGA,SAAuB,EAAS,IAChC,0BAGA,oBACA,MAQA,iBAPA,SACA,wCACA,sBAEA,iBAEA,aAGA,iBACA,kBAEA,iBACA,qBACA,MAEA,sBAEA,gBAEA,gBAEA,kBACA,SAEA,yCACA,sBACA,kBAEA,aAIA,QAEA,MACA,CAEA,sBAEA,wBACA,cACA,kBAEA,mBAEA,mBAGA,IAEA,YAEA,YACA,kBAEA,iBACA,MACA,IAEA,QACA,YACA,kBACA,oBACA,eAEA,IAGA,IACA,6BACA,gBACA,aAIA,QAEA,MACA,CACA,GAEA,cAEA,WACA,gCC3cA,aAcA,eAEA,mBACA,gBACA,iBAEA,QAWA,CA7BA,YAEA,aACA,WAQA,IAmBA,iCACA,cACA,kDACA,0CAEA,aACA,IACA,aACA,IAAkB,MAA2B,OAC7C,KACA,sBACA,SACA,KAKA,mBACA,cAAc,MAAmB,OACjC,cAGA,+BACA,SAAc,MAA2B,OACzC,cAGA,uBACA,cAAc,MAAuB,OACrC,IAGA,6BACA,qBACA,OACA,SAOA,EACA,+BACA,mBACA,UAAkB,MAAoB,OACtC,kCAGA,MACA,QAMA,EACA,2CACA,sCACA,gBACA,YACA,KACA,mBAEA,IAAkB,MAA2B,OAC7C,SAGA,QAAc,MAA0B,WACxC,YACA,UACA,KACA,MACA,IAEA,IAEA,CACA,QAMA,EACA,kBACA,IACA,yCAEA,qCACA,YAIA,EACA,6BACA,OACA,WACA,kBACA,cACA,eAEA,Q,eC7HA,aAYA,UAXA,eACA,OACA,YAEA,gBAAmB,QAAmB,OACtC,oBAGA,OACA,2BCnBA,aAaA,mBACA,WACA,aAEA,aACA,mBAEA,gBAAuB,EAAW,QAClC,MAEA,iBACA,SACA,oBAEA,QAA2B,EAAW,IACtC,0BAEA,KAEA,OACA,SASA,CACA,iBACA,aAEA,aACA,mBAEA,gBAAuB,EAAW,IAClC,oBAGA,mBACA,IAWA,CA/DA,UAUA,GAoEA,UAdA,mBACA,eACA,YACA,SACA,sBACA,oBAEA,gCACA,8BACA,6BAEA,mBACA,8BC9EA,aAKA,aACA,MACA,yBAEA,iBACA,kBACA,8BAGA,8BACA,SACA,OACA,WACA,SAEA,QAAe,EAAe,QAC9B,OACA,OACA,QAAmB,EAAO,QAC1B,OACA,OACA,QAAuB,EAAO,IAC9B,YAEA,wBACA,WACA,GAEA,OAEA,aACA,kBACA,QAAuB,EAAe,IACtC,YAEA,CAEA,IACA,mBAGA,wCACA,IA7CA,WAEA,OA6CA,YACA,4BACA,aACA,CACA,mBACA,KAEA,0BACA,MAEA,UACA,yBAGA,0CACA,YACA,YAEA,QAAmB,EAAe,IAClC,UAAuB,EAAW,QAClC,OAA2B,EAAO,IAClC,qBAEA,iBACA,OAGA,SAA+B,EAAQ,KACvC,UAAuB,EAAW,QAClC,SAA+B,EAAe,IAC9C,qBAEA,iBACA,OAGA,CACA,QACA,GAEA,6BCzFA,aAYA,eACA,aACA,iBACA,yBAEA,mBACA,kBACA,2BAGA,yCACA,gBACA,KACA,WACA,SACA,IAGA,OADA,WAIA,mBAGA,gBACA,OAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,UAAK,KACL,aACA,KACA,eAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,YAEA,MACA,SACA,SACA,SACA,IAoCA,mBAEA,eACA,IAEA,QAAe,EAAO,IACtB,aAGA,cAAmB,EAAO,QAC1B,OACA,IACA,IAAmB,EAAO,IAC1B,SAGA,SACA,mBACA,KAAuB,EAAO,IAC9B,aACA,cACA,UAES,MACT,OAAuB,EAAO,IAC9B,IACA,gBAGA,eACA,KACA,KACA,QAGA,SACA,OACA,WACA,MAAuB,EAAO,IAC9B,SAGA,QAAuB,EAAO,QAC9B,OACA,KACA,iBACA,cAA+B,OAAY,EAC3C,eACA,WAEA,UACA,MAEA,OACA,IAAuB,EAAO,IAC9B,IACA,gBAGA,cACA,OAAuB,EAAO,IAC9B,YAGA,WAAuB,EAAO,QAC9B,OACA,OACA,KAA2B,SAAY,EACvC,sBAEA,cACA,cACA,CACA,CACA,CACA,MAEA,OAAe,MAAW,MAC1B,cACA,gBACA,QACA,SACA,OAAuB,EAAQ,KAC/B,gBAGA,WAAuB,EAAQ,SAC/B,OACA,IAA2B,EAAQ,KACnC,iBAEA,cAA2B,EAAQ,KACnC,eAEA,IACA,CAEA,OAAmB,EAAQ,KAC3B,cAEA,CAEA,OAAe,EAAO,IACtB,aACA,gBAGA,cACA,OACA,EAEA,mBAEA,qBACA,cACA,EAEA,QAAe,EAAO,IACtB,WAGA,YAEA,QACA,IACA,EAEA,8BAAe,EAAO,QACtB,qBACA,OACA,IACA,gBAGA,MAGA,WACA,GACA,IAGA,WACA,qBACA,YACA,GACA,QAGA,eACA,kBACA,WACA,OACA,SAA+B,EAAO,IACtC,IAKA,mBACA,OACA,EACA,IACA,UACA,KACA,IACA,MAA+B,EAAQ,KACvC,QACA,IACA,IACA,QACA,OACA,UACA,aACA,MACA,SACA,aACA,sBAEA,QAA+B,EAAO,IACtC,aACA,uBACA,sBAIA,eACA,YACA,SAEA,GACA,eACA,IACA,CACA,aACA,CAEA,OAAe,MAAW,MAC1B,KACA,MACA,SAAuB,EAAO,IAC9B,IACA,SACA,MAIA,SACA,eACA,KACA,SAAuB,EAAO,IAC9B,MACA,gBACA,QAGA,SACA,EAEA,mBAEA,OACA,MACA,YACA,EAEA,UAAqB,OAAe,MACpC,OACA,EAAmB,IAAW,KAC9B,gBAGA,aACA,OACA,EAA0B,IAAQ,KAClC,gBACA,aAGA,WACA,KACA,WAGA,OACA,OAEA,QAAuB,IAAO,QAC9B,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,OAAuB,EAAW,SAClC,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,QACA,eACA,GACA,CAEA,OAAe,EAAO,IACtB,UAAmB,EAAO,IAC1B,oBAIA,UAAsB,OAAc,EACpC,qBACA,SAA2B,EAAW,KACtC,gBAGA,OAAuB,IAAW,SAClC,OACA,EAA2B,IAAW,KACtC,YAGA,4BACA,GAA2B,IAAW,KACtC,eAEA,IACA,CAEA,EAEA,qBACA,SACA,IACA,MACA,EACA,0BACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,kBACA,QACA,IAEA,QAAe,EAAQ,IACvB,cACA,YACA,aAGA,WAAoC,GAAQ,IAC5C,SAIA,oBACA,KACA,IACA,yBACA,SACA,QAEA,oBAGA,OAGA,OACA,MACA,gBACA,aACA,EACA,MACS,kBACT,oBACA,8BACA,IACA,UACA,MACA,gCACA,OAEA,aACA,gBACA,WACA,aACA,GACA,eAEA,YACA,OACA,WACA,UACA,OACA,MACA,YAIA,mBAA+B,EAAQ,IACvC,UACA,sBACA,0BAGA,UAA2B,EAAQ,KACnC,aACA,mBACA,0BAGA,QAA6B,IAAW,KACxC,aACA,mBACA,0BAEA,GACA,aACA,SACA,QACA,UAGA,MACA,IACA,CAAS,KACT,MACA,UACA,IACA,EACA,iBACA,mBAGA,aACA,KACA,KAA6B,IAAQ,KACrC,IAEA,qCACA,QACA,UACA,UAEA,IACA,gBACA,IACA,WACA,OACA,KACA,QAEA,iBACA,KAAiC,IAAQ,KACzC,IAEA,WACA,WACA,KAKA,aACA,EACA,SACA,UACA,MACA,+BACA,cACA,oBACA,eAIA,oBAGA,2EAGA,QAGA,YAA2B,EAAQ,KACnC,cACA,MACA,cAIA,OAAuB,SAAY,YAEnC,EACA,iBACA,cACA,mBACA,cACA,KAOA,yBAIA,OAjBA,mBAkBA,KACA,QAGA,UACA,KACA,MAEA,0BAIA,cALqB,YAMrB,MACA,MAIA,cAA+B,IAAQ,IACvC,oBAEA,mBACA,0BAGA,cACA,wBAGA,UAA+B,WAAyB,GACxD,yBAEA,mBACA,uBAGA,KACA,+BAGA,QAAiC,IAAW,KAC5C,yBAEA,mBACA,uBAGA,KACA,+BAEA,GAEA,CACA,CAEA,IAIA,eAAoB,EAAQ,KAC5B,SACA,OAEA,KACA,UACA,YACA,MAA2B,EAAQ,SACnC,OACA,YACA,EAA2B,IAAQ,KACnC,eAGA,WACA,OACA,IAEA,YACA,IACA,2BAEA,oBACA,SACA,+BACA,YACA,OACA,6CAGA,YACA,SACA,YAAmC,IAAQ,KAC3C,IAIA,UACS,SACT,YAEA,qBACA,6BACA,iCAEA,+BACA,sBACA,eAGA,cACA,UACA,MAA2B,EAAQ,SACnC,OACA,IACA,EAA2B,IAAQ,KACnC,sBACA,cAGA,aAEA,UACA,OACA,IACA,IAEA,YACA,IACA,iBACA,oBACA,aAEA,cACA,SACA,oCACA,MACA,oBACA,mCAEA,+BACA,qBACA,aACA,aACA,oCACA,4CAEA,gCACA,2BACA,eAIA,wBACA,UACA,YAAmC,IAAQ,KAC3C,qBACA,KAIA,UAIA,OAAe,EAAQ,IACvB,YACA,QAAuB,IAAQ,IAC/B,YAKA,gBAAoB,EAAU,KAC9B,QAAqB,IAAW,SAChC,OACA,EAAyB,OAAwB,OACjD,eAEA,QACA,SAEA,GAEA,mBACA,OACA,cACA,QACA,QACA,kBAEA,YACA,QACA,gBAEA,WAvwBA,aACA,WACA,QACA,eAEA,mBACA,CAGA,oBAmDA,YACA,sBACA,aACA,CACA,4BACA,aACA,CACA,yBACA,wBACA,uBAEA,SACA,CACA,sBACA,YACA,SACA,SACA,IACA,aACA,QAAmB,EAAO,QAC1B,OAAuB,EAAO,IAC9B,YAEA,UACA,KACA,iBACa,KACb,mBAEA,KACA,CACA,QACA,GA6qBA,6BC3wBA,aAMA,aACA,MACA,yBAEA,cAEA,uBACA,YACA,SACA,UACA,eAEA,QAAe,EAAO,QACtB,OACA,MAAmB,IAAO,IAC1B,UAEA,kBACA,KACA,cAEA,IAAuB,IAAO,IAC9B,IAEA,wBACA,MAA2B,EAAO,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OACA,CACA,MACA,EAEA,MACA,UACA,QA7CA,WACA,eAEA,WA4CA,YACA,kBACA,KAEA,0BACA,OAEA,UACA,yBAEA,6CACA,6BAGA,oCACA,YACA,YACA,cAEA,QAAmB,EAAO,IAC1B,UAAuB,EAAW,QAClC,OACA,EAA2B,IAAO,IAClC,eAEA,iBACA,QAA2B,IAAO,IAClC,eAEA,OAEA,SAAuB,EAAQ,SAC/B,OAAuB,EAAW,IAClC,kBAEA,eAAuB,EAAO,IAC9B,UAA2B,EAAW,IACtC,qBAGA,OAEA,8BACA,EACA,uBACA,mBACA,UAAuB,EAAa,IACpC,OACA,kBAGA,SACA,QACA,6BACA,YACA,OACA,UACA,aACA,QAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,YACA,IACiB,QACjB,WAEA,SAIA,EACA,QACA,wBACA,YACA,OACA,SACA,UACA,iBAEA,UAA6B,EAAQ,SACrC,OAAuB,EAAU,IACjC,YAEA,cACA,EAAuB,IAAa,IACpC,mBACA,OACA,EAA+B,IAAU,IACzC,eAGA,iBAEA,QAA+B,IAAU,IACzC,eAEA,OAEA,CACA,CACA,QACA,GAEA,6BCvJA,aAUA,aACA,YACA,2BACA,MASA,CAeA,eACA,YACA,mBACA,uDACA,SAvCA,WAEA,WACA,QACA,SACA,QACA,cAeA,YASA,MACA,8CACA,UACA,OAQA,UACA,6BACA,UACA,SAEA,UACA,CACA,6BACA,MACA,0BACA,MACA,kBACA,KACA,kBACA,KACA,wBACA,MACA,UACA,qBC3DA,oBACA,oCACA,+BCJA,aAEA,WAkBA,UAhBA,eACA,iBACA,gBACA,QACA,QAEA,WACA,+BACA,UACA,IAEA,OACA,+BACA,OACA,oBClBA,aAEA,WAiBA,UAfA,eACA,eACA,kBACA,QAEA,WACA,yCACA,KACA,IAEA,SACA,yCACA,EACA,oBCjBA,aAEA,WAiBA,UAfA,eACA,eACA,kBACA,QAEA,WACA,oCACA,OACA,IAEA,SACA,oCACA,IACA,oBCjBA,aAEA,WAkBA,UAhBA,eACA,iBACA,aACA,cACA,KAEA,WACA,6BACA,SACA,IAEA,SACA,6BACA,MACA,oBClBA,aAEA,QACA,WAoBA,UAlBA,eACA,mBACA,SACA,kDACA,0BACA,yBACA,MAEA,WACA,gDACA,oBACA,IAEA,SACA,gDACA,iBACA,oBCrBA,aAEA,QACA,WAoBA,UAlBA,eACA,uBACA,GACA,wCACA,QACA,gBACA,aAEA,WACA,6CACA,iBACA,IAEA,SACA,6CACA,cACA,oBCrBA,aAEA,WAiBA,UAfA,eACA,eACA,qBACA,KAEA,WACA,oBACA,WACA,IAEA,SACA,oBACA,QACA,oBCjBA,aAEA,aAEA,UACA,CACA,mBACA,sBAYA,iBAyCA,UAxCA,eACA,GACA,mCACA,2CACA,uCAEA,oBACA,KAGA,4BACA,OAAuB,QAAwB,OAC/C,UACA,MACA,MACA,IAGK,aAGL,4BACA,OAAuB,QAAwB,OAC/C,UACA,MACA,MACA,IAIA,0BAIA,6DAIA,uBCxDA,aACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,8BAEA,GACA,QAEA,EACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,4BAEA,GACA,QAEA,EACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,mBAEA,KACA,QAEA,EACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,mBAEA,KACA,QAEA,EACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,mBAEA,KACA,QAEA,EACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,mBAEA,KACA,QAEA,EACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,6BAEA,4BACA,QAEA,EACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,6BAEA,4BACA,QAEA,EACA,cACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,6BAEA,8BACA,QAEA,EACA,cACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,6BAEA,8BACA,QAEA,EACA,YACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,2BAEA,4CACA,QAEA,EACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,yBAEA,SACA,QAEA,EACA,WACA,mBACA,SACA,mBAAmB,EAAO,IAC1B,yBAEA,SACA,QAEA,EACA,iBACA,mBACA,QAEA,cADA,uBCxIA,aAOA,iBACA,OACA,WAEA,iCACA,+BAEA,eACA,SAEA,2BACA,sBACA,gBAEA,mBACA,WACA,WACA,WAAmB,EAAe,QAClC,SAEA,wBACA,mCACA,OAEA,kCACA,8BACA,6BACA,cAEA,iBAEA,wBACA,mCACA,WAEA,sBACA,+BACA,oBACA,oBACA,EAEA,MAEA,8CACA,iBAEA,SACA,SACA,SACA,SACA,YAvDA,QACA,WAEA,YAsDA,sCACA,WAEA,4BACA,QAAmB,SAAoB,cACvC,cACA,4BAEA,uBACA,gBACA,QACA,wBAEA,YAGA,CACA,aAEA,YAJA,I,mBC1EA,aAwMA,eACA,WACA,IAAmB,MAAiB,KACpC,OAEA,QACA,QAOA,CACA,aACA,WACA,KACA,WAAkB,QAAkB,QACpC,MACA,OACA,MACA,IAGA,KACA,SA/NA,QACA,WAEA,OACA,iBACA,WACA,MACA,kBACA,qBACA,qBACA,qBACA,iCACA,gBACA,GAAS,KACT,iBACA,4BAEA,wEACA,6BACA,oBACA,qBAEA,cACA,6BACA,oBACA,qBACA,GACA,CAeA,SACA,cAEA,cACA,cACA,2CAGA,iBACA,UACA,eAGA,qBACA,SAEA,MACA,SACA,YACA,SAEA,2BACA,yBAEA,MACA,QACA,eACA,eACA,eACA,eACA,eACA,UAEA,oBACA,aACA,gBAEA,0BACA,uBAEA,aACA,uBACA,+BAEA,+BACA,SACA,gBACA,SACA,QACA,gBACA,gBACA,aACA,OAEA,CACA,YACA,mCACA,OACA,WACA,UACA,SACA,SAEA,uBACA,mCACA,qBACA,kBACA,4CAEA,gBACA,iBACA,iBACA,iBACA,iBAEA,eACA,UACA,GAEA,CACA,6BACA,8BACA,8BACA,8BACA,8BACA,uBAKA,UACA,eACA,SACA,SACA,SACA,SACA,SACA,SACA,SACA,8BACA,kFACA,EAOA,WACA,SACA,8DACA,2BACA,KAEA,wDADA,QAOA,uBACA,aACA,GAEA,SACA,OACA,MACA,eACA,eACA,mBACA,mBACA,mBACA,iBAEA,IAOA,eACA,IACA,wDACA,YACA,YACA,EAEA,EAOA,0CCvMA,aACA,8BACA,+BAEA,0CACA,4BAEA,6ECPA,aACA,OACA,QACA,IACA,0BAEA,sBAGA,YACA,qBAEA,iBAGA,0CCiCA,iBACA,WACA,SACA,mBAAmB,EAAO,IAC1B,WAGA,oBACA,sBACA,cACA,4EAzDA,IAEA,mBACA,iBACA,CACA,QACA,iBACA,WAEA,QACA,YAEA,UAEA,YACA,wBACA,EAEA,SACA,OACA,MACA,+BACA,SAEA,EAEA,YACA,gEACA,OAEA,WACA,OACA,wCAAyE,yBAEzE,KAAkC,oCAAgD,4BAGlF,KAEA,eACA,IACA,qDAEA,4CACA,YACA,+CC3CA,aACA,MACA,yBAEA,mBACA,kBACA,8BAGA,8BACA,SACA,UACA,UACA,SAEA,QAAe,EAAe,QAC9B,OACA,OACA,QAAmB,EAAO,QAC1B,OACA,OACA,QAAuB,EAAO,IAC9B,YAEA,wBACA,WACA,GAEA,OAEA,aACA,kBACA,QAAuB,EAAe,IACtC,YAEA,CAEA,IACA,mBAGA,wCACA,YA3CA,GA6CA,YACA,4BACA,aACA,CACA,mBACA,OAEA,0BACA,MAEA,UACA,yBAGA,0CACA,YACA,YAEA,QAAmB,EAAe,IAClC,UAAuB,EAAW,QAClC,OAA2B,EAAO,IAClC,qBAEA,iBACA,OAGA,SAA+B,EAAQ,KACvC,UAAuB,EAAW,QAClC,SAA+B,EAAe,IAC9C,qBAEA,iBACA,OAGA,CACA,QAGA,iCC/EA,eACA,aACA,iBACA,yBAEA,qBACA,kBACA,2BAGA,yCACA,uBACA,KACA,WACA,SACA,IAGA,OADA,WAIA,mBAGA,gBACA,OAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,UAAK,KACL,oBACA,KACA,eAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,YAEA,MACA,SACA,SACA,SACA,IAoCA,mBAEA,eACA,IAEA,QAAe,EAAO,IACtB,aAGA,cAAmB,EAAO,QAC1B,OACA,IACA,IAAmB,EAAO,IAC1B,SAGA,SACA,mBACA,KAAuB,EAAO,IAC9B,aACA,cACA,UAES,MACT,OAAuB,EAAO,IAC9B,IACA,gBAGA,eACA,KACA,KACA,QAGA,SACA,OACA,WACA,MAAuB,EAAO,IAC9B,SAGA,QAAuB,EAAO,QAC9B,OACA,KACA,iBACA,cAA+B,OAAY,EAC3C,eACA,WAEA,UACA,MAEA,OACA,IAAuB,EAAO,IAC9B,IACA,gBAGA,cACA,OAAuB,EAAO,IAC9B,YAGA,WAAuB,EAAO,QAC9B,OACA,OACA,KAA2B,SAAY,EACvC,sBAEA,cACA,cACA,CACA,CACA,CACA,MAEA,OAAe,MAAW,MAC1B,cACA,gBACA,QACA,SACA,OAAuB,EAAQ,KAC/B,gBAGA,WAAuB,EAAQ,SAC/B,OACA,IAA2B,EAAQ,KACnC,iBAEA,cAA2B,EAAQ,KACnC,eAEA,IACA,CAEA,OAAmB,EAAQ,KAC3B,cAEA,CAEA,OAAe,EAAO,IACtB,aACA,gBAGA,cACA,OACA,EAEA,mBAEA,qBACA,cACA,EAEA,QAAe,EAAO,IACtB,WAGA,YAEA,QACA,IACA,EAEA,8BAAe,EAAO,QACtB,qBACA,OACA,IACA,gBAGA,MAGA,WACA,GACA,IAGA,WACA,qBACA,mBACA,GACA,QAGA,eACA,kBACA,WACA,OACA,SAA+B,EAAO,IACtC,IAKA,mBACA,OACA,EACA,IACA,UACA,KACA,IACA,MAA+B,EAAQ,KACvC,QACA,IACA,IACA,QACA,OACA,iBACA,aACA,MACA,SACA,aACA,sBAEA,QAA+B,EAAO,IACtC,aACA,uBACA,sBAIA,eACA,YACA,SAEA,GACA,eACA,IACA,CACA,aACA,CAEA,OAAe,MAAW,MAC1B,KACA,MACA,SAAuB,EAAO,IAC9B,IACA,SACA,MAIA,SACA,eACA,KACA,SAAuB,EAAO,IAC9B,MACA,gBACA,QAGA,SACA,EAEA,mBAEA,OACA,MACA,YACA,EAEA,UAAqB,OAAe,MACpC,OACA,EAAmB,IAAW,KAC9B,gBAGA,aACA,OACA,EAA0B,IAAQ,KAClC,gBACA,aAGA,WACA,KACA,WAGA,OACA,OAEA,QAAuB,IAAO,QAC9B,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,OAAuB,EAAW,SAClC,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,QACA,eACA,GACA,CAEA,OAAe,EAAO,IACtB,UAAmB,EAAO,IAC1B,oBAIA,UAAsB,OAAc,EACpC,qBACA,SAA2B,EAAW,KACtC,gBAGA,OAAuB,IAAW,SAClC,OACA,EAA2B,IAAW,KACtC,YAGA,4BACA,GAA2B,IAAW,KACtC,eAEA,IACA,CAEA,EAEA,qBACA,SACA,IACA,MACA,EACA,0BACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,kBACA,QACA,IAEA,QAAe,EAAQ,IACvB,cACA,YACA,aAGA,WAAoC,GAAQ,IAC5C,SAIA,oBACA,KACA,IACA,yBACA,SACA,QAEA,oBAGA,OAGA,OACA,MACA,gBACA,aACA,EACA,MACS,kBACT,oBACA,8BACA,IACA,UACA,MACA,gCACA,OAEA,aACA,gBACA,WACA,aACA,GACA,eAEA,YACA,OACA,WACA,UACA,OACA,MACA,YAIA,mBAA+B,EAAQ,IACvC,UACA,sBACA,0BAGA,UAA2B,EAAQ,KACnC,aACA,mBACA,0BAGA,QAA6B,IAAW,KACxC,aACA,mBACA,0BAEA,GACA,aACA,SACA,QACA,UAGA,MACA,IACA,CAAS,KACT,MACA,UACA,IACA,EACA,iBACA,mBAGA,aACA,KACA,KAA6B,IAAQ,KACrC,IAEA,qCACA,QACA,UACA,UAEA,IACA,gBACA,IACA,WACA,OACA,KACA,QAEA,iBACA,KAAiC,IAAQ,KACzC,IAEA,WACA,WACA,KAKA,aACA,EACA,SACA,UACA,MACA,+BACA,cACA,oBACA,eAIA,oBAGA,2EAGA,QAGA,YAA2B,EAAQ,KACnC,cACA,MACA,cAIA,OAAuB,SAAY,YAEnC,EACA,iBACA,cACA,mBACA,cACA,KAOA,yBAIA,OAjBA,mBAkBA,KACA,QAGA,UACA,KACA,MAEA,0BAIA,cALqB,YAMrB,MACA,MAIA,cAA+B,IAAQ,IACvC,oBAEA,mBACA,0BAGA,cACA,wBAGA,UAA+B,WAAyB,GACxD,yBAEA,mBACA,uBAGA,KACA,+BAGA,QAAiC,IAAW,KAC5C,yBAEA,mBACA,uBAGA,KACA,+BAEA,GAEA,CACA,CAEA,IAIA,eAAoB,EAAQ,KAC5B,SACA,OAEA,KACA,UACA,YACA,MAA2B,EAAQ,SACnC,OACA,YACA,EAA2B,IAAQ,KACnC,eAGA,WACA,OACA,IAEA,YACA,IACA,2BAEA,oBACA,SACA,+BACA,YACA,OACA,6CAGA,YACA,SACA,YAAmC,IAAQ,KAC3C,IAIA,UACS,SACT,YAEA,qBACA,6BACA,iCAEA,+BACA,sBACA,eAGA,cACA,UACA,MAA2B,EAAQ,SACnC,OACA,IACA,EAA2B,IAAQ,KACnC,sBACA,cAGA,aAEA,UACA,OACA,IACA,IAEA,YACA,IACA,iBACA,oBACA,aAEA,cACA,SACA,oCACA,MACA,oBACA,mCAEA,+BACA,qBACA,aACA,aACA,oCACA,4CAEA,gCACA,2BACA,eAIA,wBACA,UACA,YAAmC,IAAQ,KAC3C,qBACA,KAIA,UAIA,OAAe,EAAQ,IACvB,YACA,QAAuB,IAAQ,IAC/B,YAKA,gBAAoB,EAAU,KAC9B,QAAqB,IAAW,SAChC,OACA,EAAyB,OAAwB,OACjD,eAEA,QACA,SAEA,GAEA,mBACA,OACA,cACA,QACA,QACA,kBAEA,YACA,QACA,gBAEA,UAEA,gBAtwBqC,IAErC,QACA,CAGA,oBAmDA,YACA,sBACA,aACA,CACA,4BACA,aACA,CACA,yBACA,0BACA,yBAEA,SACA,CACA,sBACA,YACA,SACA,SACA,OACA,YACA,QAAmB,EAAO,QAC1B,OAAuB,EAAO,IAC9B,YAEA,UACA,KACA,iBACa,KACb,mBAEA,KACA,CACA,QACA,qCChFA,aACA,cACA,qBACA,2DACA,iCANA,gLCAkD,eCRlD,QACA,oCACA,oDCFA,IAEA,mBACA,iBACA,gBACA,QACA,QAEA,WACA,+BACA,UACA,IAEA,OACA,+BACA,OACA,8CChBA,IAEA,mBACA,eACA,kBACA,QAEA,WACA,yCACA,KACA,IAEA,SACA,yCACA,EACA,8CCfA,IAEA,mBACA,eACA,kBACA,QAEA,WACA,oCACA,OACA,IAEA,SACA,oCACA,IACA,8CCfA,IAEA,mBACA,iBACA,aACA,cACA,KAEA,WACA,6BACA,SACA,IAEA,SACA,6BACA,MACA,sDCfqB,IAErB,mBACA,mBACA,WACA,0CACA,0BACA,yBACA,MAEA,WACA,gDACA,oBACA,IAEA,SACA,gDACA,iBACA,sDClBmB,IAEnB,mBACA,uBACA,KACA,kCACA,QACA,gBACA,aAEA,WACA,6CACA,iBACA,IAEA,SACA,6CACA,cACA,8CCnBA,IAEA,mBACA,eACA,qBACA,KAEA,WACA,oBACA,WACA,IAEA,SACA,oBACA,QACA,sCCgCA,iBACA,WACA,SACA,WACA,mBAAmB,EAAO,IAC1B,WACA,aAGA,oBACA,wBACA,iBACA,uEA1DA,IAEA,mBACA,iBACA,CACA,QACA,iBACA,WAEA,QACA,YAEA,UAEA,YACA,wBACA,EAEA,SACA,OACA,MACA,yBACA,SAEA,EAEA,YACA,0DACA,IAEA,WACA,OACA,wCAAyE,yBAEzE,IAAkC,oCAAgD,4BAElF,IAEA,eACA,IACA,+CAEA,sCACA,YACA,+CC1CA,aACA,MACA,yBAEA,mBACA,kBACA,8BAGA,8BACA,SACA,UACA,UACA,SAEA,QAAe,EAAe,QAC9B,OACA,OACA,QAAmB,EAAO,QAC1B,OACA,OACA,QAAuB,EAAO,IAC9B,YAEA,wBACA,WACA,GAEA,OAEA,aACA,kBACA,QAAuB,EAAe,IACtC,YAEA,CAEA,IACA,mBAGA,wCACA,YA3CA,GA6CA,YACA,4BACA,aACA,CACA,mBACA,OAEA,0BACA,MAEA,UACA,yBAGA,0CACA,YACA,YAEA,QAAmB,EAAe,IAClC,UAAuB,EAAW,QAClC,OAA2B,EAAO,IAClC,qBAEA,iBACA,OAGA,SAA+B,EAAQ,KACvC,UAAuB,EAAW,QAClC,SAA+B,EAAe,IAC9C,qBAEA,iBACA,OAGA,CACA,QAGA,iCC/EA,eACA,aACA,iBACA,yBAEA,qBACA,kBACA,2BAGA,yCACA,uBACA,KACA,WACA,SACA,IAGA,OADA,WAIA,mBAGA,gBACA,OAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,UAAK,KACL,oBACA,KACA,eAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,YAEA,MACA,SACA,SACA,SACA,IAoCA,mBAEA,eACA,IAEA,QAAe,EAAO,IACtB,aAGA,cAAmB,EAAO,QAC1B,OACA,IACA,IAAmB,EAAO,IAC1B,SAGA,SACA,mBACA,KAAuB,EAAO,IAC9B,aACA,cACA,UAES,MACT,OAAuB,EAAO,IAC9B,IACA,gBAGA,eACA,KACA,KACA,QAGA,SACA,OACA,WACA,MAAuB,EAAO,IAC9B,SAGA,QAAuB,EAAO,QAC9B,OACA,KACA,iBACA,cAA+B,OAAY,EAC3C,eACA,WAEA,UACA,MAEA,OACA,IAAuB,EAAO,IAC9B,IACA,gBAGA,cACA,OAAuB,EAAO,IAC9B,YAGA,WAAuB,EAAO,QAC9B,OACA,OACA,KAA2B,SAAY,EACvC,sBAEA,cACA,cACA,CACA,CACA,CACA,MAEA,OAAe,MAAW,MAC1B,cACA,gBACA,QACA,SACA,OAAuB,EAAQ,KAC/B,gBAGA,WAAuB,EAAQ,SAC/B,OACA,IAA2B,EAAQ,KACnC,iBAEA,cAA2B,EAAQ,KACnC,eAEA,IACA,CAEA,OAAmB,EAAQ,KAC3B,cAEA,CAEA,OAAe,EAAO,IACtB,aACA,gBAGA,cACA,OACA,EAEA,mBAEA,qBACA,cACA,EAEA,QAAe,EAAO,IACtB,WAGA,YAEA,QACA,IACA,EAEA,8BAAe,EAAO,QACtB,qBACA,OACA,IACA,gBAGA,MAGA,WACA,GACA,IAGA,WACA,qBACA,mBACA,GACA,QAGA,eACA,kBACA,WACA,OACA,SAA+B,EAAO,IACtC,IAKA,mBACA,OACA,EACA,IACA,UACA,KACA,IACA,MAA+B,EAAQ,KACvC,QACA,IACA,IACA,QACA,OACA,iBACA,aACA,MACA,SACA,aACA,sBAEA,QAA+B,EAAO,IACtC,aACA,uBACA,sBAIA,eACA,YACA,SAEA,GACA,eACA,IACA,CACA,aACA,CAEA,OAAe,MAAW,MAC1B,KACA,MACA,SAAuB,EAAO,IAC9B,IACA,SACA,MAIA,SACA,eACA,KACA,SAAuB,EAAO,IAC9B,MACA,gBACA,QAGA,SACA,EAEA,mBAEA,OACA,MACA,YACA,EAEA,UAAqB,OAAe,MACpC,OACA,EAAmB,IAAW,KAC9B,gBAGA,aACA,OACA,EAA0B,IAAQ,KAClC,gBACA,aAGA,WACA,KACA,WAGA,OACA,OAEA,QAAuB,IAAO,QAC9B,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,OAAuB,EAAW,SAClC,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,QACA,eACA,GACA,CAEA,OAAe,EAAO,IACtB,UAAmB,EAAO,IAC1B,oBAIA,UAAsB,OAAc,EACpC,qBACA,SAA2B,EAAW,KACtC,gBAGA,OAAuB,IAAW,SAClC,OACA,EAA2B,IAAW,KACtC,YAGA,4BACA,GAA2B,IAAW,KACtC,eAEA,IACA,CAEA,EAEA,qBACA,SACA,IACA,MACA,EACA,0BACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,kBACA,QACA,IAEA,QAAe,EAAQ,IACvB,cACA,YACA,aAGA,WAAoC,GAAQ,IAC5C,SAIA,oBACA,KACA,IACA,yBACA,SACA,QAEA,oBAGA,OAGA,OACA,MACA,gBACA,aACA,EACA,MACS,kBACT,oBACA,8BACA,IACA,UACA,MACA,gCACA,OAEA,aACA,gBACA,WACA,aACA,GACA,eAEA,YACA,OACA,WACA,UACA,OACA,MACA,YAIA,mBAA+B,EAAQ,IACvC,UACA,sBACA,0BAGA,UAA2B,EAAQ,KACnC,aACA,mBACA,0BAGA,QAA6B,IAAW,KACxC,aACA,mBACA,0BAEA,GACA,aACA,SACA,QACA,UAGA,MACA,IACA,CAAS,KACT,MACA,UACA,IACA,EACA,iBACA,mBAGA,aACA,KACA,KAA6B,IAAQ,KACrC,IAEA,qCACA,QACA,UACA,UAEA,IACA,gBACA,IACA,WACA,OACA,KACA,QAEA,iBACA,KAAiC,IAAQ,KACzC,IAEA,WACA,WACA,KAKA,aACA,EACA,SACA,UACA,MACA,+BACA,cACA,oBACA,eAIA,oBAGA,2EAGA,QAGA,YAA2B,EAAQ,KACnC,cACA,MACA,cAIA,OAAuB,SAAY,YAEnC,EACA,iBACA,cACA,mBACA,cACA,KAOA,yBAIA,OAjBA,mBAkBA,KACA,QAGA,UACA,KACA,MAEA,0BAIA,cALqB,YAMrB,MACA,MAIA,cAA+B,IAAQ,IACvC,oBAEA,mBACA,0BAGA,cACA,wBAGA,UAA+B,WAAyB,GACxD,yBAEA,mBACA,uBAGA,KACA,+BAGA,QAAiC,IAAW,KAC5C,yBAEA,mBACA,uBAGA,KACA,+BAEA,GAEA,CACA,CAEA,IAIA,eAAoB,EAAQ,KAC5B,SACA,OAEA,KACA,UACA,YACA,MAA2B,EAAQ,SACnC,OACA,YACA,EAA2B,IAAQ,KACnC,eAGA,WACA,OACA,IAEA,YACA,IACA,2BAEA,oBACA,SACA,+BACA,YACA,OACA,6CAGA,YACA,SACA,YAAmC,IAAQ,KAC3C,IAIA,UACS,SACT,YAEA,qBACA,6BACA,iCAEA,+BACA,sBACA,eAGA,cACA,UACA,MAA2B,EAAQ,SACnC,OACA,IACA,EAA2B,IAAQ,KACnC,sBACA,cAGA,aAEA,UACA,OACA,IACA,IAEA,YACA,IACA,iBACA,oBACA,aAEA,cACA,SACA,oCACA,MACA,oBACA,mCAEA,+BACA,qBACA,aACA,aACA,oCACA,4CAEA,gCACA,2BACA,eAIA,wBACA,UACA,YAAmC,IAAQ,KAC3C,qBACA,KAIA,UAIA,OAAe,EAAQ,IACvB,YACA,QAAuB,IAAQ,IAC/B,YAKA,gBAAoB,EAAU,KAC9B,QAAqB,IAAW,SAChC,OACA,EAAyB,OAAwB,OACjD,eAEA,QACA,SAEA,GAEA,mBACA,OACA,cACA,QACA,QACA,kBAEA,YACA,QACA,gBAEA,UAEA,gBAtwBqC,IAErC,QACA,CAGA,oBAmDA,YACA,sBACA,aACA,CACA,4BACA,aACA,CACA,yBACA,0BACA,yBAEA,SACA,CACA,sBACA,YACA,SACA,SACA,OACA,YACA,QAAmB,EAAO,QAC1B,OAAuB,EAAO,IAC9B,YAEA,UACA,KACA,iBACa,KACb,mBAEA,KACA,CACA,QACA,qCChFA,aACA,cACA,qBACA,2DACA,iCANA,0ICAkD,eCRlD,QACA,oCACA,oDCFA,IAEA,mBACA,iBACA,gBACA,QACA,QAEA,WACA,+BACA,UACA,IAEA,OACA,+BACA,OACA,8CChBA,IAEA,mBACA,eACA,kBACA,QAEA,WACA,yCACA,KACA,IAEA,SACA,yCACA,EACA,8CCfA,IAEA,mBACA,eACA,kBACA,QAEA,WACA,oCACA,OACA,IAEA,SACA,oCACA,IACA,8CCfA,IAEA,mBACA,iBACA,aACA,cACA,KAEA,WACA,6BACA,SACA,IAEA,SACA,6BACA,MACA,sDCfqB,IAErB,mBACA,mBACA,WACA,0CACA,0BACA,yBACA,MAEA,WACA,gDACA,oBACA,IAEA,SACA,gDACA,iBACA,sDClBmB,IAEnB,mBACA,uBACA,KACA,kCACA,QACA,gBACA,aAEA,WACA,6CACA,iBACA,IAEA,SACA,6CACA,cACA,8CCnBA,IAEA,mBACA,eACA,qBACA,KAEA,WACA,oBACA,WACA,IAEA,SACA,oBACA,QACA,sCCsEA,mBACA,OACA,mBAAmB,EAAY,IAC/B,IAGA,eACA,mBAEmB,EAAnB,MAAsC,WACtC,WACA,OAEA,WACA,UAAuB,MAAc,OACrC,gBACA,eACA,eACA,KAIA,sBACA,uBACA,YAEA,IAEA,GACA,WACA,0BACA,YAQA,CACA,iBACA,eACA,YAEA,WAAmB,MAAc,WACjC,kBAEA,cACA,MACA,iBACA,OACA,GACA,OAEA,OACA,KAAa,uBACb,WACA,GACA,OAEA,OACA,KACA,KACA,UAIA,cACA,OAEA,QACA,CACA,QAOA,CACA,eACA,aACA,YACA,UAAmB,MAAc,WACjC,YACA,gBACA,kBAAuB,MAAmB,OAC1C,qBAEA,KAEA,sBACA,YAEA,iBACA,OACA,YAAmB,MAAmB,OACtC,gBAEA,MACA,SAEA,aACA,4BAEA,kBACA,aACA,SACA,YAEA,GAEA,sEApMc,KAEd,mBACA,mBACA,CACA,QACA,sBACA,qBACA,2BAEA,mBACA,YAEA,YAEA,SACA,OACA,MACA,yCACA,mBACA,yBAEA,aAEA,YACA,6BACA,aAEA,YACA,aACA,gBAEA,WACA,aACA,gBAEA,gBACA,OACA,MACA,KAEA,YACA,OACA,MAGA,UACA,KACA,aAAuB,sBAA8B,OACrD,MACA,GACA,6BACA,iCAEA,mBACA,sDAEA,kDAIA,iEACA,IACiB,qCACjB,MAGA,UAEA,UACA,8BAGA,IACA,WAEA,eACA,IACA,0DAEA,gDACA,YACA,+CCXA,iBACA,SACA,eACA,OACA,YAAmB,EAAS,IAC5B,gBAA2B,EAAS,IACpC,WACA,gCAIA,SACA,eAEA,OACA,mBAAmB,EAAS,IAC5B,gBAGA,OACA,oBACA,mCACA,+EA7Fc,KACd,uBAEA,mBASA,iBACA,CACA,QAEA,qBACA,uBACA,8BAGA,mBACA,YAGA,UAEA,SACA,OACA,MACA,gCACA,qBAEA,UAEA,YACA,0BACA,SAEA,YACA,+BACA,KAEA,YACA,OACA,wBACA,qBACA,wCACA,mBACA,cACA,oCACA,qBACA,SACA,CACA,uBAEA,aACA,QAEA,WACA,aACA,WAEA,eACA,IACA,kDAEA,+BACA,YACA,+CCnEA,aACA,MACA,yBAEA,mBACA,kBACA,8BAGA,8BACA,SACA,UACA,UACA,SAEA,QAAe,EAAe,QAC9B,OACA,OACA,QAAmB,EAAO,QAC1B,OACA,OACA,QAAuB,EAAO,IAC9B,YAEA,wBACA,WACA,GAEA,OAEA,aACA,kBACA,QAAuB,EAAe,IACtC,YAEA,CAEA,IACA,mBAGA,wCACA,YA3CA,GA6CA,YACA,4BACA,aACA,CACA,mBACA,OAEA,0BACA,MAEA,UACA,yBAGA,0CACA,YACA,YAEA,QAAmB,EAAe,IAClC,UAAuB,EAAW,QAClC,OAA2B,EAAO,IAClC,qBAEA,iBACA,OAGA,SAA+B,EAAQ,KACvC,UAAuB,EAAW,QAClC,SAA+B,EAAe,IAC9C,qBAEA,iBACA,OAGA,CACA,QAGA,uCC/EA,eACA,aACA,iBACA,yBAEA,qBACA,kBACA,2BAGA,yCACA,uBACA,KACA,WACA,SACA,IAGA,OADA,WAIA,mBAGA,gBACA,OAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,UAAK,KACL,oBACA,KACA,eAAmB,EAAO,IAC1B,UAAuB,EAAO,IAC9B,cAGA,SACA,WACA,YAEA,MACA,SACA,SACA,SACA,IAoCA,mBAEA,eACA,IAEA,QAAe,EAAO,IACtB,aAGA,cAAmB,EAAO,QAC1B,OACA,IACA,IAAmB,EAAO,IAC1B,SAGA,SACA,mBACA,KAAuB,EAAO,IAC9B,aACA,cACA,UAES,MACT,OAAuB,EAAO,IAC9B,IACA,gBAGA,eACA,KACA,KACA,QAGA,SACA,OACA,WACA,MAAuB,EAAO,IAC9B,SAGA,QAAuB,EAAO,QAC9B,OACA,KACA,iBACA,cAA+B,OAAY,EAC3C,eACA,WAEA,UACA,MAEA,OACA,IAAuB,EAAO,IAC9B,IACA,gBAGA,cACA,OAAuB,EAAO,IAC9B,YAGA,WAAuB,EAAO,QAC9B,OACA,OACA,KAA2B,SAAY,EACvC,sBAEA,cACA,cACA,CACA,CACA,CACA,MAEA,OAAe,MAAW,MAC1B,cACA,gBACA,QACA,SACA,OAAuB,EAAQ,KAC/B,gBAGA,WAAuB,EAAQ,SAC/B,OACA,IAA2B,EAAQ,KACnC,iBAEA,cAA2B,EAAQ,KACnC,eAEA,IACA,CAEA,OAAmB,EAAQ,KAC3B,cAEA,CAEA,OAAe,EAAO,IACtB,aACA,gBAGA,cACA,OACA,EAEA,mBAEA,qBACA,cACA,EAEA,QAAe,EAAO,IACtB,WAGA,YAEA,QACA,IACA,EAEA,8BAAe,EAAO,QACtB,qBACA,OACA,IACA,gBAGA,MAGA,WACA,GACA,IAGA,WACA,qBACA,mBACA,GACA,QAGA,eACA,kBACA,WACA,OACA,SAA+B,EAAO,IACtC,IAKA,mBACA,OACA,EACA,IACA,UACA,KACA,IACA,MAA+B,EAAQ,KACvC,QACA,IACA,IACA,QACA,OACA,iBACA,aACA,MACA,SACA,aACA,sBAEA,QAA+B,EAAO,IACtC,aACA,uBACA,sBAIA,eACA,YACA,SAEA,GACA,eACA,IACA,CACA,aACA,CAEA,OAAe,MAAW,MAC1B,KACA,MACA,SAAuB,EAAO,IAC9B,IACA,SACA,MAIA,SACA,eACA,KACA,SAAuB,EAAO,IAC9B,MACA,gBACA,QAGA,SACA,EAEA,mBAEA,OACA,MACA,YACA,EAEA,UAAqB,OAAe,MACpC,OACA,EAAmB,IAAW,KAC9B,gBAGA,aACA,OACA,EAA0B,IAAQ,KAClC,gBACA,aAGA,WACA,KACA,WAGA,OACA,OAEA,QAAuB,IAAO,QAC9B,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,OAAuB,EAAW,SAClC,OACA,EAA8B,IAAQ,KACtC,YAIA,iBAA2B,IAAW,KACtC,eAEA,IAEA,QACA,eACA,GACA,CAEA,OAAe,EAAO,IACtB,UAAmB,EAAO,IAC1B,oBAIA,UAAsB,OAAc,EACpC,qBACA,SAA2B,EAAW,KACtC,gBAGA,OAAuB,IAAW,SAClC,OACA,EAA2B,IAAW,KACtC,YAGA,4BACA,GAA2B,IAAW,KACtC,eAEA,IACA,CAEA,EAEA,qBACA,SACA,IACA,MACA,EACA,0BACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,kBACA,QACA,IAEA,QAAe,EAAQ,IACvB,cACA,YACA,aAGA,WAAoC,GAAQ,IAC5C,SAIA,oBACA,KACA,IACA,yBACA,SACA,QAEA,oBAGA,OAGA,OACA,MACA,gBACA,aACA,EACA,MACS,kBACT,oBACA,8BACA,IACA,UACA,MACA,gCACA,OAEA,aACA,gBACA,WACA,aACA,GACA,eAEA,YACA,OACA,WACA,UACA,OACA,MACA,YAIA,mBAA+B,EAAQ,IACvC,UACA,sBACA,0BAGA,UAA2B,EAAQ,KACnC,aACA,mBACA,0BAGA,QAA6B,IAAW,KACxC,aACA,mBACA,0BAEA,GACA,aACA,SACA,QACA,UAGA,MACA,IACA,CAAS,KACT,MACA,UACA,IACA,EACA,iBACA,mBAGA,aACA,KACA,KAA6B,IAAQ,KACrC,IAEA,qCACA,QACA,UACA,UAEA,IACA,gBACA,IACA,WACA,OACA,KACA,QAEA,iBACA,KAAiC,IAAQ,KACzC,IAEA,WACA,WACA,KAKA,aACA,EACA,SACA,UACA,MACA,+BACA,cACA,oBACA,eAIA,oBAGA,2EAGA,QAGA,YAA2B,EAAQ,KACnC,cACA,MACA,cAIA,OAAuB,SAAY,YAEnC,EACA,iBACA,cACA,mBACA,cACA,KAOA,yBAIA,OAjBA,mBAkBA,KACA,QAGA,UACA,KACA,MAEA,0BAIA,cALqB,YAMrB,MACA,MAIA,cAA+B,IAAQ,IACvC,oBAEA,mBACA,0BAGA,cACA,wBAGA,UAA+B,WAAyB,GACxD,yBAEA,mBACA,uBAGA,KACA,+BAGA,QAAiC,IAAW,KAC5C,yBAEA,mBACA,uBAGA,KACA,+BAEA,GAEA,CACA,CAEA,IAIA,eAAoB,EAAQ,KAC5B,SACA,OAEA,KACA,UACA,YACA,MAA2B,EAAQ,SACnC,OACA,YACA,EAA2B,IAAQ,KACnC,eAGA,WACA,OACA,IAEA,YACA,IACA,2BAEA,oBACA,SACA,+BACA,YACA,OACA,6CAGA,YACA,SACA,YAAmC,IAAQ,KAC3C,IAIA,UACS,SACT,YAEA,qBACA,6BACA,iCAEA,+BACA,sBACA,eAGA,cACA,UACA,MAA2B,EAAQ,SACnC,OACA,IACA,EAA2B,IAAQ,KACnC,sBACA,cAGA,aAEA,UACA,OACA,IACA,IAEA,YACA,IACA,iBACA,oBACA,aAEA,cACA,SACA,oCACA,MACA,oBACA,mCAEA,+BACA,qBACA,aACA,aACA,oCACA,4CAEA,gCACA,2BACA,eAIA,wBACA,UACA,YAAmC,IAAQ,KAC3C,qBACA,KAIA,UAIA,OAAe,EAAQ,IACvB,YACA,QAAuB,IAAQ,IAC/B,YAKA,gBAAoB,EAAU,KAC9B,QAAqB,IAAW,SAChC,OACA,EAAyB,OAAwB,OACjD,eAEA,QACA,SAEA,GAEA,mBACA,OACA,cACA,QACA,QACA,kBAEA,YACA,QACA,gBAEA,UAEA,gBAtwBqC,IAErC,QACA,CAGA,oBAmDA,YACA,sBACA,aACA,CACA,4BACA,aACA,CACA,yBACA,0BACA,yBAEA,SACA,CACA,sBACA,YACA,SACA,SACA,OACA,YACA,QAAmB,EAAO,QAC1B,OAAuB,EAAO,IAC9B,YAEA,UACA,KACA,iBACa,KACb,mBAEA,KACA,CACA,QACA,uCChFA,eACA,cACA,qBACA,2DACA,aATA,WACA,cACA,6BACA,qCALA,eCHA,QACA,oCACA,oDCFA,IAEA,mBACA,iBACA,gBACA,QACA,QAEA,WACA,+BACA,UACA,IAEA,OACA,+BACA,OACA,8CChBA,IAEA,mBACA,eACA,kBACA,QAEA,WACA,yCACA,KACA,IAEA,SACA,yCACA,EACA,8CCfA,IAEA,mBACA,eACA,kBACA,QAEA,WACA,oCACA,OACA,IAEA,SACA,oCACA,IACA,8CCfA,IAEA,mBACA,iBACA,aACA,cACA,KAEA,WACA,6BACA,SACA,IAEA,SACA,6BACA,MACA,sDCfqB,IAErB,mBACA,mBACA,WACA,0CACA,0BACA,yBACA,MAEA,WACA,gDACA,oBACA,IAEA,SACA,gDACA,iBACA,sDClBmB,IAEnB,mBACA,uBACA,KACA,kCACA,QACA,gBACA,aAEA,WACA,6CACA,iBACA,IAEA,SACA,6CACA,cACA,8CCnBA,IAEA,mBACA,eACA,qBACA,KAEA,WACA,oBACA,WACA,IAEA,SACA,oBACA,QACA,yBCfA,aAEA,UACA,QACA,WACA,UAEA,QAEA,MACA,QACA,eACA,WACA,iBAIA,uBACA,iBACA,mBACA,IACA,QACA,oBACA,oBACA,yBACA,gCACA,+CAEA,iBACA,yBAES,aACT,UAEA,4CACA,mBACA,eACA,8BAEA,oBACA,YACA,2BACA,gCACA,mBAEA,WACA,mCAEA,kBACA,CAEA,YACA,8DACA,EAEA,SACA,OACA,MACA,mCACA,kBACA,uBACA,8BAEA,eAIA,YAHA,yBAEA,UAGA,eACA,IACA,qDAEA,yBACA,YACA,EAEA,6BC7EA,aAsLA,eACA,aACA,UAAmB,MAAY,KAC/B,mBAEA,MACA,QAQA,CACA,eACA,cACA,YArMA,UACA,QACA,WACA,QAEA,MACA,OAGA,GACA,iBASA,mBACA,CACA,QACA,2CACA,2BACA,QACA,aACA,YAEA,MACA,mBAGA,iBACA,4BACA,WACA,qBACA,SAEA,2BAEA,OACA,mCAGA,mBAUA,WACA,sBACA,8BAGA,4BACA,WAGA,aACA,gEAEA,2CACA,0BAGA,2CACA,qCACA,oBAEA,iCACA,uBAEA,0BACA,6BACA,6BAEA,kBACA,iBACA,iBAEA,eACA,aAEA,IAAuB,YAAiB,UACxC,QACA,kBAA2B,IAAY,KACvC,6BACA,UACA,eAEA,GAEA,2BACA,CACA,8BACA,+BAGA,mCACA,iCACA,gCACA,WACA,CAEA,WACA,iBAAmB,EAAkB,IACrC,cAGA,MAEA,YACA,yBAEA,oFAEA,UAEA,IAAmB,EAAmB,KACtC,eACA,UAAuB,EAAY,KACnC,2DACA,SAGA,GAEA,YACA,aACA,OAEA,KACA,IAEA,IAAuB,UAAiB,MACxC,cAA2B,UAAqB,QAChD,0CACA,GAIA,IACA,QAEA,SACA,OACA,MACA,uBACA,wBAEA,cAIA,YAHA,yBAEA,UAGA,eACA,IACA,yCAEA,+BACA,YAEA,EAEA,EASA,2BC1KA,aAEA,eACA,qBAEA,YAEA,iBAQA,qBACA,CACA,WAEA,gBACA,WACA,IACA,yBAES,aACT,SACA,gBACA,4BAGA,kEACA,2BACA,QACA,KAfA,OAgBA,mCAEA,kBACA,CAEA,YACA,wBACA,EAEA,SACA,QAAmB,2CACnB,GAIA,YAHA,yBAEA,UAGA,YACA,0CACA,CAEA,WAEA,OACA,iCAAyE,aAEzE,IAAkC,6BAAgD,gBAElF,IAEA,eACA,IACA,mDAEA,0CACA,YACA,EAEA,2BCnFA,aAEA,gCACA,OACA,SAEA,aAEA,sBAIA,gBAEA,iBAGA,6BCjBA,aAEA,cACA,iCCHA,aAoBA,eACA,CACA,0BAEA,WACA,cACA,aAEA,YACA,KACA,QACA,MAAmB,EAAU,IAC7B,UAAuB,EAAU,IACjC,UAGA,UACA,KAAK,SACL,YACA,SACA,MAAmB,EAAU,QAC7B,UACA,IAAuB,EAAU,IACjC,UAEA,QACA,OACK,SACL,YACA,SACA,MAAmB,EAAU,QAC7B,UACA,IAAuB,EAAU,IACjC,UAEA,QACA,OAEA,sBAEA,qBACA,SAEA,iBACA,wBACA,SAAmB,EAAO,IAC1B,WAEA,MACA,SAEA,iBACA,CACA,wBAEA,WACA,aACA,gBACA,wBACA,SAEA,WAAmB,EAAU,QAC7B,mBACA,IAAuB,EAAU,IACjC,cACA,KACA,QAGA,wBAEA,MAEA,QACA,CACA,SAqIA,iBACA,CACA,0BAEA,GACA,wBACA,iBACS,EACT,sBAGA,UACA,WACA,UACA,MAEA,sBACA,eAEA,WACA,OACA,WAAmB,EAAU,IAC7B,SAEA,eAAmB,EAAU,IAC7B,QAAuB,IAAU,QACjC,OACA,IAA2B,EAAU,IACrC,+BAEA,MACA,KACA,UACA,SAEA,CAAK,eACL,OACA,WAAmB,EAAU,IAC7B,SAEA,eAAmB,EAAU,IAC7B,QAAuB,IAAU,QACjC,OACA,IAA2B,EAAU,IACrC,+BAEA,MACA,KACA,UACA,SAEA,CACA,sBAGA,qBACA,SA4BA,iBACA,aACA,+BACA,aACA,gBAEA,iBACA,MACA,QACA,SACA,WAEA,KACA,SACA,WAAmB,EAAO,IAC1B,oBAIA,cAAe,EAAO,QACtB,OACA,iBAAoC,OAAQ,IAC5C,iBAEA,IACA,CACA,SAEA,iBACA,2BACA,SACA,SACA,WAEA,KACA,SACA,WAAmB,EAAO,IAC1B,oBAIA,cAAe,EAAO,QACtB,OACA,OACA,iBAA0C,OAAQ,IAClD,oBACA,kBAGA,KACA,CACA,SA4BA,iBACA,CACA,0BAEA,WACA,gBACA,oBACA,iBAEA,WACA,OACA,WAAmB,EAAU,IAC7B,SAEA,QAAmB,EAAU,IAC7B,UACA,OACA,OAAuB,EAAU,IACjC,UAGA,MAAK,eACL,OACA,WAAmB,EAAU,IAC7B,SAEA,QAAmB,EAAU,IAC7B,UACA,OACA,OAAuB,EAAU,IACjC,UAGA,MACA,sBAGA,6BACA,UACA,kBAAsC,OAAQ,IAC9C,IAGA,QACA,SAcA,qBACA,MACA,OACA,SACA,0BAEA,WACA,UACA,MAEA,sBACA,eAEA,WACA,OACA,WAAmB,EAAU,IAC7B,SAEA,eAAmB,EAAU,IAC7B,QAAuB,IAAU,QACjC,OACA,IAA2B,EAAU,IACrC,oCAEA,cACA,YACA,GAEA,CAAK,eACL,OACA,WAAmB,EAAU,IAC7B,SAEA,eAAmB,EAAU,IAC7B,QAAuB,IAAU,QACjC,OACA,IAA2B,EAAU,IACrC,oCAEA,cACA,YACA,GAEA,CACA,sBAGA,qBACA,SAhfA,QAEA,IAgfA,UACA,CACA,QAhfA,aACA,CACA,0BAEA,aACA,MACA,cACA,SAAmB,EAAQ,IAC3B,cAAuB,EAAQ,IAC/B,iBAGA,iBACA,IAoeA,OACA,oBACA,WACA,OAxZA,WACA,2BACA,SAEA,WAAmB,IAAU,QAC7B,GACA,mBAAuB,EAAU,IACjC,SAEA,UACA,eACA,YACA,OAEA,4BAEA,GACA,CACA,UAuYA,KArYA,WACA,SACA,cACA,SACA,WACA,QAAe,EAAU,QACzB,WACA,WAAuB,EAAU,IACjC,SAEA,QACA,WAEA,QAAmB,EAAU,QAC7B,iBACA,SACA,KAEA,aACA,aACA,EAEA,IAEA,WACA,QAAmB,EAAW,IAC9B,IACA,WACA,KAIA,UACA,IACA,CACA,UAmWA,SAjWA,aACA,yBACA,gBACA,oBACA,SAEA,WAAmB,EAAO,QAC1B,eACA,IAAuB,IAAO,IAC9B,cACA,QACA,OAGA,YACA,MACA,cAEA,QACA,cACA,SAEA,KADA,IAEA,KAEA,OACA,CACA,UAuUA,SArUA,aACA,yBACA,gBACA,uBACA,SAEA,WAAmB,EAAO,QAC1B,eACA,IAAuB,IAAO,IAC9B,cACA,QACA,OAEA,cACA,MAEA,SACA,YACA,QAEA,kCADA,MAGA,yBADA,IAEA,mBAEA,CACA,CACA,UA2SA,cAzSA,WACA,aACA,kBACA,SACA,WAEA,OAAmB,EAAO,IAC1B,SAEA,OACA,UAgSA,WA9RA,aACA,OACA,gBA6RA,UACA,YAlOA,WACA,OACA,OACA,YACA,aACA,cACA,SAGA,WADA,QACe,EAAU,IACzB,SAEA,eAAe,EAAU,IACzB,QAAmB,IAAU,QAC7B,WACA,UAA8C,OAAO,IACrD,eAEA,aACA,EACA,UACA,SAEA,CACA,UA2MA,UACA,SACA,cACA,iBAvJA,aACA,OACA,SACA,gBACA,wBACA,SAEA,WAAmB,EAAU,QAC7B,WACA,QAEA,IAAuB,EAAU,QACjC,eACA,OAEA,WACA,KACA,QACA,GAEA,YACA,OAEA,CACA,UAgIA,eACA,mBAjFA,iBACA,MACA,OACA,uBACA,UAAwC,OAAQ,IAChD,OACA,aAEA,cACA,aACA,eAwEA,oCCrgBA,mBAEA,QAEA,4BACA,iBAEA,KATA,YAWA,kBACA,0BAEA,mCACA,mDACA,KAEA,wCACA,mBACA,iBACA,gBACA,qFACA,OAEA,kCACA,iBACA,yEAEA,E,2BC7BA,aAIA,eACA,OACA,KAJA,YAMA,iBACA,YACA,WAAmB,MAAmB,OACtC,cAAuB,SAAsB,OAC7C,kBAGA,SACA,UAEA,iBACA,WACA,WAAmB,MAAmB,OACtC,cAAuB,SAAsB,OAC7C,kBAGA,SACA,UAEA,oBACA,WACA,YACA,WAAmB,MAAmB,OACtC,cAAuB,SAAsB,OAC7C,kBACA,uBAGA,eACA,CACA,MAEA,QAEA,uBACA,CACA,0BAEA,aACA,MACA,cACA,SAAmB,EAAQ,IAC3B,cAAuB,EAAQ,IAC/B,iBAGA,iBACA,IAEA,oBACA,CACA,0BAEA,WACA,cACA,aAEA,YACA,KACA,QACA,MAAmB,EAAU,IAC7B,UAAuB,EAAU,IACjC,UAGA,UACA,KAAK,SACL,YACA,SACA,MAAmB,EAAU,QAC7B,UACA,IAAuB,EAAU,IACjC,UAEA,QACA,OACK,SACL,YACA,SACA,MAAmB,EAAU,QAC7B,UACA,IAAuB,EAAU,IACjC,UAEA,QACA,OAEA,sBAEA,qBACA,UAEA,mBACA,CACA,0BAEA,WACA,cACA,WAEA,MACA,UACA,QAAmB,EAAU,IAC7B,UAAuB,EAAU,IACjC,UAGK,gBACL,YACA,WAAmB,EAAU,IAC7B,aACA,IAAuB,EAAU,IACjC,UAGK,gBACL,YACA,WAAmB,EAAU,IAC7B,aACA,IAAuB,EAAU,IACjC,UAIA,6BAEA,qBACA,UAEA,uBACA,CACA,0BAEA,WACA,cACA,WAEA,MACA,UACA,QAAmB,EAAU,IAC7B,UAAuB,EAAU,IACjC,UAGK,gBACL,YACA,WAAmB,EAAU,IAC7B,aACA,IAAuB,EAAU,IACjC,UAGK,gBACL,YACA,WAAmB,EAAU,IAC7B,aACA,IAAuB,EAAU,IACjC,UAIA,6BAEA,qBACA,UAEA,mCACA,iCACA,SAAmB,EAAO,IAC1B,WAEA,MACA,UAEA,0BACA,CACA,wBAEA,aACA,gBACA,gBACA,wBACA,SAEA,WAAmB,EAAU,QAC7B,mBACA,IAAuB,EAAU,IACjC,cACA,KACA,QAGA,wBAEA,MAEA,QACA,CACA,UAEA,oBACA,2BACA,SAEA,WAAmB,IAAU,QAC7B,GACA,mBAAuB,EAAU,IACjC,SAEA,UACA,gBACA,YACA,OAEA,4BAEA,GACA,CACA,UAEA,kBACA,SACA,cACA,SACA,WACA,QAAe,EAAU,QACzB,WACA,WAAuB,EAAU,IACjC,SAEA,QACA,WAEA,QAAmB,EAAU,QAC7B,iBACA,SACA,KAEA,aACA,aACA,EAEA,IAEA,WACA,QAAmB,EAAW,IAC9B,IACA,WACA,KAIA,UACA,IACA,CACA,UAEA,wBACA,yBACA,kBACA,uBACA,SAEA,WAAmB,EAAO,QAC1B,eACA,IAAuB,IAAO,IAC9B,cACA,QACA,OAGA,YACA,MACA,cAEA,QACA,cACA,SAEA,KADA,IAEA,KAEA,OACA,CACA,UAEA,wBACA,yBACA,kBACA,0BACA,SAEA,WAAmB,EAAO,QAC1B,eACA,IAAuB,IAAO,IAC9B,cACA,QACA,OAEA,cACA,MAEA,SACA,YACA,QAEA,kCADA,MAGA,yBADA,IAEA,mBAEA,CACA,CACA,UAEA,2BACA,aACA,WACA,yBACA,SACA,WAEA,OAAmB,EAAO,IAC1B,SAEA,OACA,UAEA,0BACA,UACA,qBAEA,yBACA,CACA,0BAEA,GACA,wBACA,iBACS,EACT,sBAGA,YACA,cACA,UACA,MAEA,sBACA,eAEA,WACA,OACA,WAAmB,EAAU,IAC7B,SAEA,eAAmB,EAAU,IAC7B,QAAuB,IAAU,QACjC,OACA,IAA2B,EAAU,IACrC,+BAEA,MACA,KACA,UACA,SAEA,CAAK,eACL,OACA,WAAmB,EAAU,IAC7B,SAEA,eAAmB,EAAU,IAC7B,QAAuB,IAAU,QACjC,OACA,IAA2B,EAAU,IACrC,+BAEA,MACA,KACA,UACA,SAEA,CACA,sBAGA,qBACA,UAEA,yBACA,SACA,YACA,8BACA,mBACA,cACA,SAGA,WADA,QACe,EAAU,IACzB,SAEA,eAAe,EAAU,IACzB,QAAmB,IAAU,QAC7B,WACA,UAA8C,OAAO,IACrD,eAEA,aACA,EACA,UACA,SAEA,CACA,UAEA,yBACA,eACA,oCACA,2CACA,sBAEA,wBACA,QACA,WACA,SACA,WAEA,KACA,SACA,WAAmB,EAAO,IAC1B,oBAIA,cAAe,EAAO,QACtB,OACA,iBAAoC,OAAQ,IAC5C,iBAEA,IACA,CACA,UAEA,6BACA,6BACA,yBACA,SACA,WAEA,KACA,SACA,WAAmB,EAAO,IAC1B,oBAIA,cAAe,EAAO,QACtB,OACA,OACA,iBAA0C,OAAQ,IAClD,oBACA,kBAGA,KACA,CACA,UAEA,gCACA,SACA,YACA,gBACA,wBACA,SAEA,WAAmB,EAAU,QAC7B,WACA,QAEA,IAAuB,EAAU,QACjC,eACA,OAEA,WACA,KACA,QACA,GAEA,YACA,OAEA,CACA,UAEA,8BACA,CACA,0BAEA,WACA,gBACA,oBACA,iBAEA,WACA,OACA,WAAmB,EAAU,IAC7B,SAEA,QAAmB,EAAU,IAC7B,UACA,OACA,OAAuB,EAAU,IACjC,UAGA,MAAK,eACL,OACA,WAAmB,EAAU,IAC7B,SAEA,QAAmB,EAAU,IAC7B,UACA,OACA,OAAuB,EAAU,IACjC,UAGA,MACA,sBAGA,6BACA,UACA,kBAAsC,OAAQ,IAC9C,IAGA,QACA,UAEA,sCACA,MACA,SACA,kCACA,UAAwC,OAAQ,IAChD,OACA,aAEA,cACA,gBACA,4BAEA,qCACA,MACA,SACA,oBACA,0BAEA,WACA,UACA,MAEA,sBACA,eAEA,WACA,OACA,WAAmB,EAAU,IAC7B,SAEA,eAAmB,EAAU,IAC7B,QAAuB,IAAU,QACjC,OACA,IAA2B,EAAU,IACrC,oCAEA,cACA,YACA,GAEA,CAAK,eACL,OACA,WAAmB,EAAU,IAC7B,SAEA,eAAmB,EAAU,IAC7B,QAAuB,IAAU,QACjC,OACA,IAA2B,EAAU,IACrC,oCAEA,cACA,YACA,GAEA,CACA,sBAGA,qBACA,uBCrlBA,aACA,uBACA,SACA,UACA,OAEA,kBACA,IAAmB,EAAW,OAC9B,IACA,YAEA,WAGA,gBACA,IAAmB,EAAW,OAC9B,IACA,iBAGA,iCACA,iBACA,EAGA,qBACA,EAGA,eACA,CACA,MACA,cACA,qBAIA,iBAUA,CACA,qBACA,gBACA,iBAGA,iEAEA,8DACA,aAQA,CACA,MACA,WACA,eACA,WACA,SACA,KAWA,YAmBA,UACA,CACA,KApBA,mBACA,QAEA,QADA,UAEA,yBAEA,YACA,aAGA,kCACA,eAGA,kCACA,kCACA,QAKA,2BCpHA,UAEA,aACA,MACA,YACA,WAAiB,EAAO,IACxB,IAEA,OACA,uBCTA,aACA,mCACA,OACA,oBCHA,CAWA,YACA,iBACA,mCACA,YACA,iBACA,oCACA,CAoBA,aACA,QAEA,+BAGA,mBACA,oBACA,wBAEA,MAEA,YACA,EAAK,SACL,IAEA,sBACA,EAAS,SAET,sBACA,EACA,CAGA,EACA,aACA,QAEA,mBAGA,iCACA,sBACA,aAEA,mBAEA,OACA,KAAK,SACL,IAEA,eACA,OAAS,SAGT,eACA,OACA,CAIA,EAMA,YACA,CAGA,OACA,OACA,WAEA,aAEA,IACA,QAEA,KAEA,YACA,CAGA,aACA,KAEA,iBACA,UACA,KACA,IACA,KAEA,eAGA,SACA,MACA,MACA,GACA,KACA,KACA,MAgBA,eACA,MACA,WACA,QAWA,cAhKA,QAOA,WACA,eASA,IACA,GACA,8BAIA,YAAK,SACL,CACA,GACA,IACA,GACA,gCAIA,cAAK,SACL,CACA,GACA,CAAC,KAqDD,GACA,MACA,UACA,EAyCA,sBACA,8BACA,MACA,6BAAuB,cAAsB,OAC7C,WAGA,oBACA,YACA,iBAEA,IAEA,EAKA,0BACA,0BACA,QACA,kBACA,aACA,SACA,UACA,UAAqB,GACrB,cAIA,OACA,gBACA,SACA,QACA,mBACA,uBACA,SACA,oBACA,wBAEA,sBAAqC,WAErC,oBACA,iBACA,qCAEA,gBAA2B,YAC3B,kBACA,iBACA,mCACA,kBAA4B,OAAU,gBCvLtC,WAEA,8CACA,GACA,+CACA,aACA,CACA,QACA,cACA,YAGA,kBAGA,eACA,GACA,0BACA,gBACA,sBACA,kBACA,aACA,eCtBA,qBACA,WACA,oBACA,2BACA,2BACA,8B,kBCLA,eAmBA,CAyGA,eAEA,OACA,CACA,QAGA,0DACA,6CACA,IAEA,OAGA,kBAGA,iCACA,oCACA,mBACA,kCACA,+BACA,mBACA,OAmCA,eACA,SAGA,0CACA,6BAIA,MAGA,aACA,CACA,SAGA,aACA,IAEA,MAKA,4BAJA,CACA,OAEA,KAIA,iBAGA,MAEA,sBAEA,wBAEA,uDACA,SACA,aAIA,MAHA,UAEA,WAIA,OACA,OACA,KAIA,sBACA,UAEA,UACA,sBAKA,wBACA,gCACA,mCAIA,sBACA,SACA,0BACA,sCACA,UACA,IACA,wDAEA,aACA,sDAEA,WACA,WAEA,KAEA,eAGA,eACA,OACA,KAIA,kBACA,0BACA,oBACA,GAGA,IACA,uCAIA,SACA,wCAIA,SACA,aAGA,yBACA,6BAGA,MACA,UACA,kDAEA,+BAIA,kBAEA,WAEA,cAEA,8BACA,OACA,eAGA,UAEA,MACA,SAGA,eACA,IACA,kCACA,qBACA,+CACA,iBACA,4BACA,wBACA,SACA,OACA,qBACA,UACA,oBAEA,WACA,sBACA,eAGA,aACA,4CACA,IAGA,qBACA,QACA,cAAmC,OAAO,IAC1C,IACA,iBAGA,2BAGA,IAOA,4BANA,SACA,iBAGA,gBACA,KAIA,uBACA,SACA,6CAAyD,OACzD,QACA,MACA,kCAEA,kCAGA,aACA,6BAGA,YACA,iBAGA,SACA,6BACA,iBAEA,oBAEA,IAEA,qDACA,OACA,MAAW,qBAEX,uCACA,OACA,OAAW,QAIX,iCAGA,iBACA,eACA,SAEA,0BACA,cACA,uDACA,iBAEA,2BACA,uBACA,wBACA,oBAEA,UAEA,UACA,OAGA,iBACA,OACA,0BACA,OACA,yBACA,6CACA,CAAG,EAEH,SACA,QACA,gBACA,OACA,WACA,SACA,MAGA,iCACA,EAIA,CACA,aACA,cACA,WAGA,aACA,OACA,oBAGA,aACA,OACA,UAQA,aACA,OACA,mBAGA,aACA,OACA,mBAQA,aACA,YACA,OAGA,aACA,cACA,yBAGA,aACA,2BACA,SAGA,aACA,cACA,uBAGA,aACA,OACA,6CACA,QAGA,aACA,OACA,qBAeA,aACA,kCACA,QAGA,aACA,2CACA,IAOA,YACA,UACA,aACA,gBACA,sCACA,gDACA,IAGA,CAiCA,eACA,wCACA,UApjBA,iBACA,oBACA,UACA,QACA,QAAmB,cAAsB,OACzC,aAEA,6BACA,IAEA,WACA,IACA,cACA,qCACA,mBACA,YACA,SACA,4BACA,0BACA,SACA,QACA,yBACA,KAAS,SACT,OACA,YACA,CACA,QAEA,UACA,KAAuB,KAAS,QAChC,eACA,KAEA,UAGA,KACA,QAKA,EACA,yBAEA,QACA,0BACA,oCACA,UAGA,YACA,cAGA,YACA,MAeA,iBAdA,OACA,MACA,0BACO,iBACP,yBAEA,iBAEA,SACA,IACA,qBACA,UAEA,GAIA,GACA,QACA,sBACA,IACA,2BACA,QACA,eACA,8CACA,SACA,mBACA,wBACA,yBACA,kBACA,CACA,sBAGA,QACA,KAUA,EAyBA,EAGA,UACA,EAgBA,+LACA,EAUA,iIAiRA,YAKA,cAKA,WAKA,oBAHA,WACA,OACA,UAMA,aAKA,aAKA,WAHA,WACA,OACA,oBAMA,gBAKA,aAKA,aAKA,WAMA,YAKA,eAUA,cARA,WACA,OACA,WACA,qBACA,oBACA,oBACA,oBACA,uBAGA,kBAYA,GAGA,6EAWA,gBACA,4CACA,WAeA,EACA,kBAEA,uBAEA,cAEA,0BACA,YACA,OACA,eAEA,MACA,+CCrkBA,GAGA,aACA,OACA,KAAC,IAED,GAEA,0CACA,OAAC,SAED,CACA,4BACA,OAI4C,CAE5C","file":"ml.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ML\"] = factory();\n\telse\n\t\troot[\"ML\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition","'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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-performance/src/index.js\n// module id = 87\n// module chunks = 0","'use strict';\n\nconst utils = require('./utils');\nconst init = require('./initialization');\nconst KMeansResult = require('./KMeansResult');\nconst squaredDistance = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n maxIterations: 100,\n tolerance: 1e-6,\n withIterations: false,\n initialization: 'mostDistant',\n distanceFunction: squaredDistance\n};\n\n/**\n * Each step operation for kmeans\n * @ignore\n * @param {Array>} centers - the K centers in format [x,y,z,...]\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 * @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 = utils.updateClusterID(data, centers, clusterID, options.distanceFunction);\n var newCenters = utils.updateCenters(data, clusterID, K);\n var converged = utils.converged(newCenters, centers, options.distanceFunction, options.tolerance);\n return new KMeansResult(clusterID, newCenters, converged, iterations, options.distanceFunction);\n}\n\n/**\n * Generator version for the algorithm\n * @ignore\n * @param {Array>} centers - the K centers in format [x,y,z,...]\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 * @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 {String|Array>} [options.initialization = 'moreDistant'] - K centers in format [x,y,z,...] or a method for initialize the data:\n * * `'random'` will choose K random different values.\n * * `'mostDistant'` will choose the more distant points to a first random pick\n * @returns {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 */\nfunction 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('K should be a positive integer bigger than the number of points');\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 'random':\n centers = init.random(data, K);\n break;\n case 'mostDistant':\n centers = init.mostDistant(data, K, utils.calculateDistanceMatrix(data, options.distanceFunction));\n break;\n default:\n throw new Error('Unknown initialization method: \"' + options.initialization + '\"');\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\nmodule.exports = kmeans;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kmeans/src/kmeans.js\n// module id = 81\n// module chunks = 0","'use strict';\n\nfunction logistic(val) {\n return 1 / (1 + Math.exp(-val));\n}\n\nfunction expELU(val, param) {\n return val < 0 ? param * (Math.exp(val) - 1) : val;\n}\n\nfunction softExponential(val, param) {\n if (param < 0) {\n return -Math.log(1 - param * (val + param)) / param;\n }\n if (param > 0) {\n return ((Math.exp(param * val) - 1) / param) + param;\n }\n return val;\n}\n\nfunction softExponentialPrime(val, param) {\n if (param < 0) {\n return 1 / (1 - param * (param + val));\n } else {\n return Math.exp(param * val);\n }\n}\n\nconst ACTIVATION_FUNCTIONS = {\n 'tanh': {\n activation: Math.tanh,\n derivate: val => 1 - (val * val)\n },\n 'identity': {\n activation: val => val,\n derivate: () => 1\n },\n 'logistic': {\n activation: logistic,\n derivate: val => logistic(val) * (1 - logistic(val))\n },\n 'arctan': {\n activation: Math.atan,\n derivate: val => 1 / (val * val + 1)\n },\n 'softsign': {\n activation: val => val / (1 + Math.abs(val)),\n derivate: val => 1 / ((1 + Math.abs(val)) * (1 + Math.abs(val)))\n },\n 'relu': {\n activation: val => val < 0 ? 0 : val,\n derivate: val => val < 0 ? 0 : 1\n },\n 'softplus': {\n activation: val => Math.log(1 + Math.exp(val)),\n derivate: val => 1 / (1 + Math.exp(-val))\n },\n 'bent': {\n activation: val => ((Math.sqrt(val * val + 1) - 1) / 2) + val,\n derivate: val => (val / (2 * Math.sqrt(val * val + 1))) + 1\n },\n 'sinusoid': {\n activation: Math.sin,\n derivate: Math.cos\n },\n 'sinc': {\n activation: val => val === 0 ? 1 : Math.sin(val) / val,\n derivate: val => val === 0 ? 0 : (Math.cos(val) / val) - (Math.sin(val) / (val * val))\n },\n 'gaussian': {\n activation: val => Math.exp(-(val * val)),\n derivate: val => -2 * val * Math.exp(-(val * val))\n },\n 'parametric-relu': {\n activation: (val, param) => val < 0 ? param * val : val,\n derivate: (val, param) => val < 0 ? param : 1\n },\n 'exponential-elu': {\n activation: expELU,\n derivate: (val, param) => val < 0 ? expELU(val, param) + param : 1\n },\n 'soft-exponential': {\n activation: softExponential,\n derivate: softExponentialPrime\n }\n};\n\nmodule.exports = ACTIVATION_FUNCTIONS;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-fnn/src/activationFunctions.js\n// module id = 56\n// module chunks = 0","/**\n * Created by acastillo on 8/24/15.\n */\n/**\n * Non in-place function definitions, compatible with mathjs code *\n */\n\n'use strict';\n\nvar Matrix = require('ml-matrix');\n\nfunction matrix(A,B){\n return new Matrix(A,B);\n}\n\nfunction ones(rows, cols){\n return Matrix.ones(rows,cols);\n}\n\nfunction eye(rows, cols){\n return Matrix.eye(rows, cols);\n}\n\nfunction zeros(rows, cols){\n return Matrix.zeros(rows, cols);\n}\n\nfunction random(rows, cols){\n return Matrix.rand(rows,cols);\n}\n\nfunction transpose(A){\n if(typeof A == 'number')\n return A;\n var result = A.clone();\n return result.transpose();\n}\n\nfunction add(A, B){\n if(typeof A == 'number'&&typeof B === 'number')\n return A+B;\n if(typeof A == 'number')\n return this.add(B,A);\n\n var result = A.clone();\n return result.add(B);\n\n}\n\nfunction subtract(A, B){\n if(typeof A == 'number'&&typeof B === 'number')\n return A-B;\n if(typeof A == 'number')\n return this.subtract(B,A);\n var result = A.clone();\n return result.sub(B);\n}\n\nfunction multiply(A, B){\n if(typeof A == 'number'&&typeof B === 'number')\n return A*B;\n if(typeof A == 'number')\n return this.multiply(B,A);\n\n var result = A.clone();\n\n if(typeof B === 'number')\n result.mul(B);\n else\n result = result.mmul(B);\n\n if(result.rows==1&&result.columns==1)\n return result[0][0];\n else\n return result;\n\n}\n\nfunction dotMultiply(A, B){\n var result = A.clone();\n return result.mul(B);\n}\n\nfunction dotDivide(A, B){\n var result = A.clone();\n return result.div(B);\n}\n\nfunction diag(A){\n var diag = null;\n var rows = A.rows, cols = A.columns, j, r;\n //It is an array\n if(typeof cols === \"undefined\" && (typeof A)=='object'){\n if(A[0]&&A[0].length){\n rows = A.length;\n cols = A[0].length;\n r = Math.min(rows,cols);\n diag = Matrix.zeros(cols, cols);\n for (j = 0; j < cols; j++) {\n diag[j][j]=A[j][j];\n }\n }\n else{\n cols = A.length;\n diag = Matrix.zeros(cols, cols);\n for (j = 0; j < cols; j++) {\n diag[j][j]=A[j];\n }\n }\n\n }\n if(rows == 1){\n diag = Matrix.zeros(cols, cols);\n for (j = 0; j < cols; j++) {\n diag[j][j]=A[0][j];\n }\n }\n else{\n if(rows>0 && cols > 0){\n r = Math.min(rows,cols);\n diag = new Array(r);\n for (j = 0; j < r; j++) {\n diag[j] = A[j][j];\n }\n }\n }\n return diag;\n}\n\nfunction min(A, B){\n if(typeof A==='number' && typeof B ==='number')\n return Math.min(A,B);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n if (A[i][j] < B[i][j]) {\n result[i][j] = A[i][j];\n }\n else{\n result[i][j] = B[i][j];\n }\n }\n }\n return result;\n}\n\nfunction max(A, B){\n if(typeof A==='number' && typeof B ==='number')\n return Math.max(A,B);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n if (A[i][j] > B[i][j]) {\n result[i][j] = A[i][j];\n }\n else{\n result[i][j] = B[i][j];\n }\n }\n }\n return result;\n}\n\nfunction sqrt(A){\n if(typeof A==='number' )\n return Math.sqrt(A);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n result[i][j] = Math.sqrt(A[i][j]);\n\n }\n }\n return result;\n}\n\nfunction abs(A){\n if(typeof A==='number' )\n return Math.abs(A);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n result[i][j] = Math.abs(A[i][j]);\n\n }\n }\n return result;\n}\n\nfunction exp(A){\n if(typeof A==='number' )\n return Math.sqrt(A);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n result[i][j] = Math.exp(A[i][j]);\n }\n }\n return result;\n}\n\nfunction dotPow(A, b){\n if(typeof A==='number' )\n return Math.pow(A,b);\n //console.log(A);\n var ii = A.rows, jj = A.columns;\n var result = new Matrix(ii,jj);\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n result[i][j] = Math.pow(A[i][j],b);\n }\n }\n return result;\n}\n\nfunction solve(A, B){\n return A.solve(B);\n}\n\nfunction inv(A){\n if(typeof A ===\"number\")\n return 1/A;\n return A.inverse();\n}\n\nmodule.exports = {\n transpose:transpose,\n add:add,\n subtract:subtract,\n multiply:multiply,\n dotMultiply:dotMultiply,\n dotDivide:dotDivide,\n diag:diag,\n min:min,\n max:max,\n solve:solve,\n inv:inv,\n sqrt:sqrt,\n exp:exp,\n dotPow:dotPow,\n abs:abs,\n matrix:matrix,\n ones:ones,\n zeros:zeros,\n random:random,\n eye:eye\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-curve-fitting/src/algebra.js\n// module id = 45\n// module chunks = 0","import LuDecomposition from './dc/lu';\nimport SvDecomposition from './dc/svd';\nimport {scale} from 'ml-array-utils';\nimport * as util from './util';\nimport MatrixTransposeView from './views/transpose';\nimport MatrixRowView from './views/row';\nimport MatrixSubView from './views/sub';\nimport MatrixSelectionView from './views/selection';\nimport MatrixColumnView from './views/column';\nimport MatrixFlipRowView from './views/flipRow';\nimport MatrixFlipColumnView from './views/flipColumn';\n\nexport default function AbstractMatrix(superCtor) {\n if (superCtor === undefined) superCtor = Object;\n\n /**\n * Real matrix\n * @class Matrix\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\n * 2D array containing the data or Matrix instance to clone\n * @param {number} [nColumns] - Number of columns of the new matrix\n */\n class Matrix extends superCtor {\n static get [Symbol.species]() {\n return this;\n }\n\n /**\n * Constructs a Matrix with the chosen dimensions from a 1D array\n * @param {number} newRows - Number of rows\n * @param {number} newColumns - Number of columns\n * @param {Array} newData - A 1D array containing data for the matrix\n * @return {Matrix} - The new matrix\n */\n static from1DArray(newRows, newColumns, newData) {\n var length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('Data length does not match given dimensions');\n }\n var newMatrix = new this(newRows, newColumns);\n for (var row = 0; row < newRows; row++) {\n for (var column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n /**\n * Creates a row vector, a matrix with only one row.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static rowVector(newData) {\n var vector = new this(1, newData.length);\n for (var i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates a column vector, a matrix with only one column.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static columnVector(newData) {\n var vector = new this(newData.length, 1);\n for (var i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static empty(rows, columns) {\n return new this(rows, columns);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to zero.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static zeros(rows, columns) {\n return this.empty(rows, columns).fill(0);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to one.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static ones(rows, columns) {\n return this.empty(rows, columns).fill(1);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be randomly set.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static rand(rows, columns, rng) {\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n matrix.set(i, j, rng());\n }\n }\n return matrix;\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be random integers.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {number} [maxValue=1000] - Maximum value\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static randInt(rows, columns, maxValue, rng) {\n if (maxValue === undefined) maxValue = 1000;\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = Math.floor(rng() * maxValue);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n /**\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\n * @param {number} rows - Number of rows\n * @param {number} [columns=rows] - Number of columns\n * @param {number} [value=1] - Value to fill the diagonal with\n * @return {Matrix} - The new identity matrix\n */\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n var min = Math.min(rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n /**\n * Creates a diagonal matrix based on the given array.\n * @param {Array} data - Array containing the data for the diagonal\n * @param {number} [rows] - Number of rows (Default: data.length)\n * @param {number} [columns] - Number of columns (Default: rows)\n * @return {Matrix} - The new diagonal matrix\n */\n static diag(data, rows, columns) {\n var l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n var min = Math.min(l, rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n /**\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Check that the provided value is a Matrix and tries to instantiate one if not\n * @param {*} value - The value to check\n * @return {Matrix}\n */\n static checkMatrix(value) {\n return Matrix.isMatrix(value) ? value : new this(value);\n }\n\n /**\n * Returns true if the argument is a Matrix, false otherwise\n * @param {*} value - The value to check\n * @return {boolean}\n */\n static isMatrix(value) {\n return (value != null) && (value.klass === 'Matrix');\n }\n\n /**\n * @prop {number} size - The number of elements in the matrix.\n */\n get size() {\n return this.rows * this.columns;\n }\n\n /**\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\n * @return {Matrix} this\n */\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n var ii = this.rows;\n var jj = this.columns;\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n /**\n * Returns a new 1D array filled row by row with the matrix values\n * @return {Array}\n */\n to1DArray() {\n var array = new Array(this.size);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n array[i * this.columns + j] = this.get(i, j);\n }\n }\n return array;\n }\n\n /**\n * Returns a 2D array containing a copy of the data\n * @return {Array}\n */\n to2DArray() {\n var copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n /**\n * @return {boolean} true if the matrix has one row\n */\n isRowVector() {\n return this.rows === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one column\n */\n isColumnVector() {\n return this.columns === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one row or one column\n */\n isVector() {\n return (this.rows === 1) || (this.columns === 1);\n }\n\n /**\n * @return {boolean} true if the matrix has the same number of rows and columns\n */\n isSquare() {\n return this.rows === this.columns;\n }\n\n /**\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\n */\n isSymmetric() {\n if (this.isSquare()) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j <= i; j++) {\n if (this.get(i, j) !== this.get(j, i)) {\n return false;\n }\n }\n }\n return true;\n }\n return false;\n }\n\n /**\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @param {number} value - The new value for the element\n * @return {Matrix} this\n */\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\n throw new Error('set method is unimplemented');\n }\n\n /**\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @return {number}\n */\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\n throw new Error('get method is unimplemented');\n }\n\n /**\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\n * rows of the matrix, and colRep times the number of columns of the matrix\n * @param {number} rowRep - Number of times the rows should be repeated\n * @param {number} colRep - Number of times the columns should be re\n * @return {Matrix}\n * @example\n * var matrix = new Matrix([[1,2]]);\n * matrix.repeat(2); // [[1,2],[1,2]]\n */\n repeat(rowRep, colRep) {\n rowRep = rowRep || 1;\n colRep = colRep || 1;\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\n for (var i = 0; i < rowRep; i++) {\n for (var j = 0; j < colRep; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n /**\n * Fills the matrix with a given value. All elements will be set to this value.\n * @param {number} value - New value\n * @return {Matrix} this\n */\n fill(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n /**\n * Negates the matrix. All elements will be multiplied by (-1)\n * @return {Matrix} this\n */\n neg() {\n return this.mulS(-1);\n }\n\n /**\n * Returns a new array from the given row index\n * @param {number} index - Row index\n * @return {Array}\n */\n getRow(index) {\n util.checkRowIndex(this, index);\n var row = new Array(this.columns);\n for (var i = 0; i < this.columns; i++) {\n row[i] = this.get(index, i);\n }\n return row;\n }\n\n /**\n * Returns a new row vector from the given row index\n * @param {number} index - Row index\n * @return {Matrix}\n */\n getRowVector(index) {\n return this.constructor.rowVector(this.getRow(index));\n }\n\n /**\n * Sets a row at the given index\n * @param {number} index - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setRow(index, array) {\n util.checkRowIndex(this, index);\n array = util.checkRowVector(this, array);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two rows\n * @param {number} row1 - First row index\n * @param {number} row2 - Second row index\n * @return {Matrix} this\n */\n swapRows(row1, row2) {\n util.checkRowIndex(this, row1);\n util.checkRowIndex(this, row2);\n for (var i = 0; i < this.columns; i++) {\n var temp = this.get(row1, i);\n this.set(row1, i, this.get(row2, i));\n this.set(row2, i, temp);\n }\n return this;\n }\n\n /**\n * Returns a new array from the given column index\n * @param {number} index - Column index\n * @return {Array}\n */\n getColumn(index) {\n util.checkColumnIndex(this, index);\n var column = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n column[i] = this.get(i, index);\n }\n return column;\n }\n\n /**\n * Returns a new column vector from the given column index\n * @param {number} index - Column index\n * @return {Matrix}\n */\n getColumnVector(index) {\n return this.constructor.columnVector(this.getColumn(index));\n }\n\n /**\n * Sets a column at the given index\n * @param {number} index - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setColumn(index, array) {\n util.checkColumnIndex(this, index);\n array = util.checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two columns\n * @param {number} column1 - First column index\n * @param {number} column2 - Second column index\n * @return {Matrix} this\n */\n swapColumns(column1, column2) {\n util.checkColumnIndex(this, column1);\n util.checkColumnIndex(this, column2);\n for (var i = 0; i < this.rows; i++) {\n var temp = this.get(i, column1);\n this.set(i, column1, this.get(i, column2));\n this.set(i, column2, temp);\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each row by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each column by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a row with a scalar\n * @param {number} index - Row index\n * @param {number} value\n * @return {Matrix} this\n */\n mulRow(index, value) {\n util.checkRowIndex(this, index);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n /**\n * Multiplies the values of a column with a scalar\n * @param {number} index - Column index\n * @param {number} value\n * @return {Matrix} this\n */\n mulColumn(index, value) {\n util.checkColumnIndex(this, index);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n /**\n * Returns the maximum value of the matrix\n * @return {number}\n */\n max() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value\n * @return {Array}\n */\n maxIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of the matrix\n * @return {number}\n */\n min() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value\n * @return {Array}\n */\n minIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n maxRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n maxRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n minRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n minRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n maxColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n maxColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n minColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n minColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns an array containing the diagonal values of the matrix\n * @return {Array}\n */\n diag() {\n var min = Math.min(this.rows, this.columns);\n var diag = new Array(min);\n for (var i = 0; i < min; i++) {\n diag[i] = this.get(i, i);\n }\n return diag;\n }\n\n /**\n * Returns the sum by the argument given, if no argument given,\n * it returns the sum of all elements of the matrix.\n * @param {string} by - sum by 'row' or 'column'.\n * @return {Matrix|number}\n */\n sum(by) {\n switch (by) {\n case 'row':\n return util.sumByRow(this);\n case 'column':\n return util.sumByColumn(this);\n default:\n return util.sumAll(this);\n }\n }\n\n /**\n * Returns the mean of all elements of the matrix\n * @return {number}\n */\n mean() {\n return this.sum() / this.size;\n }\n\n /**\n * Returns the product of all elements of the matrix\n * @return {number}\n */\n prod() {\n var prod = 1;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n prod *= this.get(i, j);\n }\n }\n return prod;\n }\n\n /**\n * Computes the cumulative sum of the matrix elements (in place, row by row)\n * @return {Matrix} this\n */\n cumulativeSum() {\n var sum = 0;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n sum += this.get(i, j);\n this.set(i, j, sum);\n }\n }\n return this;\n }\n\n /**\n * Computes the dot (scalar) product between the matrix and another\n * @param {Matrix} vector2 vector\n * @return {number}\n */\n dot(vector2) {\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n var vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n var dot = 0;\n for (var i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n /**\n * Returns the matrix product between this and other\n * @param {Matrix} other\n * @return {Matrix}\n */\n mmul(other) {\n other = this.constructor.checkMatrix(other);\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n var m = this.rows;\n var n = this.columns;\n var p = other.columns;\n\n var result = new this.constructor[Symbol.species](m, p);\n\n var Bcolj = new Array(n);\n for (var j = 0; j < p; j++) {\n for (var k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (var i = 0; i < m; i++) {\n var s = 0;\n for (k = 0; k < n; k++) {\n s += this.get(i, k) * Bcolj[k];\n }\n\n result.set(i, j, s);\n }\n }\n return result;\n }\n\n strassen2x2(other) {\n var result = new this.constructor[Symbol.species](2, 2);\n const a11 = this.get(0, 0);\n const b11 = other.get(0, 0);\n const a12 = this.get(0, 1);\n const b12 = other.get(0, 1);\n const a21 = this.get(1, 0);\n const b21 = other.get(1, 0);\n const a22 = this.get(1, 1);\n const b22 = other.get(1, 1);\n\n // Compute intermediate values.\n const m1 = (a11 + a22) * (b11 + b22);\n const m2 = (a21 + a22) * b11;\n const m3 = a11 * (b12 - b22);\n const m4 = a22 * (b21 - b11);\n const m5 = (a11 + a12) * b22;\n const m6 = (a21 - a11) * (b11 + b12);\n const m7 = (a12 - a22) * (b21 + b22);\n\n // Combine intermediate values into the output.\n const c00 = m1 + m4 - m5 + m7;\n const c01 = m3 + m5;\n const c10 = m2 + m4;\n const c11 = m1 - m2 + m3 + m6;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n return result;\n }\n\n strassen3x3(other) {\n var result = new this.constructor[Symbol.species](3, 3);\n\n const a00 = this.get(0, 0);\n const a01 = this.get(0, 1);\n const a02 = this.get(0, 2);\n const a10 = this.get(1, 0);\n const a11 = this.get(1, 1);\n const a12 = this.get(1, 2);\n const a20 = this.get(2, 0);\n const a21 = this.get(2, 1);\n const a22 = this.get(2, 2);\n\n const b00 = other.get(0, 0);\n const b01 = other.get(0, 1);\n const b02 = other.get(0, 2);\n const b10 = other.get(1, 0);\n const b11 = other.get(1, 1);\n const b12 = other.get(1, 2);\n const b20 = other.get(2, 0);\n const b21 = other.get(2, 1);\n const b22 = other.get(2, 2);\n\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\n const m2 = (a00 - a10) * (-b01 + b11);\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\n const m5 = (a10 + a11) * (-b00 + b01);\n const m6 = a00 * b00;\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\n const m8 = (-a00 + a20) * (b02 - b12);\n const m9 = (a20 + a21) * (-b00 + b02);\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\n const m13 = (a02 - a22) * (b11 - b21);\n const m14 = a02 * b20;\n const m15 = (a21 + a22) * (-b20 + b21);\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\n const m17 = (a02 - a12) * (b12 - b22);\n const m18 = (a11 + a12) * (-b20 + b22);\n const m19 = a01 * b10;\n const m20 = a12 * b21;\n const m21 = a10 * b02;\n const m22 = a20 * b01;\n const m23 = a22 * b22;\n\n const c00 = m6 + m14 + m19;\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\n const c11 = m2 + m4 + m5 + m6 + m20;\n const c12 = m14 + m16 + m17 + m18 + m21;\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\n const c21 = m12 + m13 + m14 + m15 + m22;\n const c22 = m6 + m7 + m8 + m9 + m23;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(0, 2, c02);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n result.set(1, 2, c12);\n result.set(2, 0, c20);\n result.set(2, 1, c21);\n result.set(2, 2, c22);\n return result;\n }\n\n /**\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\n * @param {Matrix} y\n * @return {Matrix}\n */\n mmulStrassen(y) {\n var x = this.clone();\n var r1 = x.rows;\n var c1 = x.columns;\n var r2 = y.rows;\n var c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\n }\n\n // Put a matrix into the top left of a matrix of zeros.\n // `rows` and `cols` are the dimensions of the output matrix.\n function embed(mat, rows, cols) {\n var r = mat.rows;\n var c = mat.columns;\n if ((r === rows) && (c === cols)) {\n return mat;\n } else {\n var resultat = Matrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\n }\n }\n\n\n // Make sure both matrices are the same size.\n // This is exclusively for simplicity:\n // this algorithm can be implemented with matrices of different sizes.\n\n var r = Math.max(r1, r2);\n var c = Math.max(c1, c2);\n x = embed(x, r, c);\n y = embed(y, r, c);\n\n // Our recursive multiplication function.\n function blockMult(a, b, rows, cols) {\n // For small matrices, resort to naive multiplication.\n if (rows <= 512 || cols <= 512) {\n return a.mmul(b); // a is equivalent to this\n }\n\n // Apply dynamic padding.\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\n a = embed(a, rows + 1, cols + 1);\n b = embed(b, rows + 1, cols + 1);\n } else if (rows % 2 === 1) {\n a = embed(a, rows + 1, cols);\n b = embed(b, rows + 1, cols);\n } else if (cols % 2 === 1) {\n a = embed(a, rows, cols + 1);\n b = embed(b, rows, cols + 1);\n }\n\n var halfRows = parseInt(a.rows / 2);\n var halfCols = parseInt(a.columns / 2);\n // Subdivide input matrices.\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\n\n // Combine intermediate values into the output.\n var c11 = Matrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n var c12 = Matrix.add(m3, m5);\n var c21 = Matrix.add(m2, m4);\n var c22 = Matrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n //Crop output to the desired size (undo dynamic padding).\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\n resultat = resultat.setSubMatrix(c11, 0, 0);\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\n }\n return blockMult(x, y, r, c);\n }\n\n /**\n * Returns a row-by-row scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The scaled matrix\n */\n scaleRows(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.rows; i++) {\n var scaled = scale(this.getRow(i), {min, max});\n newMatrix.setRow(i, scaled);\n }\n return newMatrix;\n }\n\n /**\n * Returns a new column-by-column scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The new scaled matrix\n * @example\n * var matrix = new Matrix([[1,2],[-1,0]]);\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\n */\n scaleColumns(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.columns; i++) {\n var scaled = scale(this.getColumn(i), {\n min: min,\n max: max\n });\n newMatrix.setColumn(i, scaled);\n }\n return newMatrix;\n }\n\n\n /**\n * Returns the Kronecker product (also known as tensor product) between this and other\n * See https://en.wikipedia.org/wiki/Kronecker_product\n * @param {Matrix} other\n * @return {Matrix}\n */\n kroneckerProduct(other) {\n other = this.constructor.checkMatrix(other);\n\n var m = this.rows;\n var n = this.columns;\n var p = other.rows;\n var q = other.columns;\n\n var result = new this.constructor[Symbol.species](m * p, n * q);\n for (var i = 0; i < m; i++) {\n for (var j = 0; j < n; j++) {\n for (var k = 0; k < p; k++) {\n for (var l = 0; l < q; l++) {\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Transposes the matrix and returns a new one containing the result\n * @return {Matrix}\n */\n transpose() {\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n /**\n * Sorts the rows (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortRows(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Sorts the columns (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortColumns(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Returns a subset of the matrix\n * @param {number} startRow - First row index\n * @param {number} endRow - Last row index\n * @param {number} startColumn - First column index\n * @param {number} endColumn - Last column index\n * @return {Matrix}\n */\n subMatrix(startRow, endRow, startColumn, endColumn) {\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\n for (var i = startRow; i <= endRow; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of row indices\n * @param {Array} indices - Array containing the row indices\n * @param {number} [startColumn = 0] - First column index\n * @param {number} [endColumn = this.columns-1] - Last column index\n * @return {Matrix}\n */\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n if (indices[i] < 0 || indices[i] >= this.rows) {\n throw new RangeError('Row index out of range: ' + indices[i]);\n }\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of column indices\n * @param {Array} indices - Array containing the column indices\n * @param {number} [startRow = 0] - First row index\n * @param {number} [endRow = this.rows-1] - Last row index\n * @return {Matrix}\n */\n subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startRow; j <= endRow; j++) {\n if (indices[i] < 0 || indices[i] >= this.columns) {\n throw new RangeError('Column index out of range: ' + indices[i]);\n }\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\n }\n }\n return newMatrix;\n }\n\n /**\n * Set a part of the matrix to the given sub-matrix\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\n * @param {number} startRow - The index of the first row to set\n * @param {number} startColumn - The index of the first column to set\n * @return {Matrix}\n */\n setSubMatrix(matrix, startRow, startColumn) {\n matrix = this.constructor.checkMatrix(matrix);\n var endRow = startRow + matrix.rows - 1;\n var endColumn = startColumn + matrix.columns - 1;\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n this[startRow + i][startColumn + j] = matrix.get(i, j);\n }\n }\n return this;\n }\n\n /**\n * Return a new matrix based on a selection of rows and columns\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\n * @return {Matrix} The new matrix\n */\n selection(rowIndices, columnIndices) {\n var indices = util.checkIndices(this, rowIndices, columnIndices);\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\n for (var i = 0; i < indices.row.length; i++) {\n var rowIndex = indices.row[i];\n for (var j = 0; j < indices.column.length; j++) {\n var columnIndex = indices.column[j];\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns the trace of the matrix (sum of the diagonal elements)\n * @return {number}\n */\n trace() {\n var min = Math.min(this.rows, this.columns);\n var trace = 0;\n for (var i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n /*\n Matrix views\n */\n\n /**\n * Returns a view of the transposition of the matrix\n * @return {MatrixTransposeView}\n */\n transposeView() {\n return new MatrixTransposeView(this);\n }\n\n /**\n * Returns a view of the row vector with the given index\n * @param {number} row - row index of the vector\n * @return {MatrixRowView}\n */\n rowView(row) {\n util.checkRowIndex(this, row);\n return new MatrixRowView(this, row);\n }\n\n /**\n * Returns a view of the column vector with the given index\n * @param {number} column - column index of the vector\n * @return {MatrixColumnView}\n */\n columnView(column) {\n util.checkColumnIndex(this, column);\n return new MatrixColumnView(this, column);\n }\n\n /**\n * Returns a view of the matrix flipped in the row axis\n * @return {MatrixFlipRowView}\n */\n flipRowView() {\n return new MatrixFlipRowView(this);\n }\n\n /**\n * Returns a view of the matrix flipped in the column axis\n * @return {MatrixFlipColumnView}\n */\n flipColumnView() {\n return new MatrixFlipColumnView(this);\n }\n\n /**\n * Returns a view of a submatrix giving the index boundaries\n * @param {number} startRow - first row index of the submatrix\n * @param {number} endRow - last row index of the submatrix\n * @param {number} startColumn - first column index of the submatrix\n * @param {number} endColumn - last column index of the submatrix\n * @return {MatrixSubView}\n */\n subMatrixView(startRow, endRow, startColumn, endColumn) {\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\n }\n\n /**\n * Returns a view of the cross of the row indices and the column indices\n * @example\n * // resulting vector is [[2], [2]]\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\n * @param {Array} rowIndices\n * @param {Array} columnIndices\n * @return {MatrixSelectionView}\n */\n selectionView(rowIndices, columnIndices) {\n return new MatrixSelectionView(this, rowIndices, columnIndices);\n }\n\n\n /**\n * Calculates and returns the determinant of a matrix as a Number\n * @example\n * new Matrix([[1,2,3], [4,5,6]]).det()\n * @return {number}\n */\n det() {\n if (this.isSquare()) {\n var a, b, c, d;\n if (this.columns === 2) {\n // 2 x 2 matrix\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(1, 0);\n d = this.get(1, 1);\n\n return a * d - (b * c);\n } else if (this.columns === 3) {\n // 3 x 3 matrix\n var subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(0, 2);\n\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(this).determinant;\n }\n\n } else {\n throw Error('Determinant can only be calculated for a square matrix.');\n }\n }\n\n /**\n * Returns inverse of a matrix if it exists or the pseudoinverse\n * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)\n * @return {Matrix} the (pseudo)inverted matrix.\n */\n pseudoInverse(threshold) {\n if (threshold === undefined) threshold = Number.EPSILON;\n var svdSolution = new SvDecomposition(this, {autoTranspose: true});\n\n var U = svdSolution.leftSingularVectors;\n var V = svdSolution.rightSingularVectors;\n var s = svdSolution.diagonal;\n\n for (var i = 0; i < s.length; i++) {\n if (Math.abs(s[i]) > threshold) {\n s[i] = 1.0 / s[i];\n } else {\n s[i] = 0.0;\n }\n }\n\n // convert list to diagonal\n s = this.constructor[Symbol.species].diag(s);\n return V.mmul(s.mmul(U.transposeView()));\n }\n }\n\n Matrix.prototype.klass = 'Matrix';\n\n function compareNumbers(a, b) {\n return a - b;\n }\n\n /*\n Synonyms\n */\n\n Matrix.random = Matrix.rand;\n Matrix.diagonal = Matrix.diag;\n Matrix.prototype.diagonal = Matrix.prototype.diag;\n Matrix.identity = Matrix.eye;\n Matrix.prototype.negate = Matrix.prototype.neg;\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\n Matrix.prototype.determinant = Matrix.prototype.det;\n\n /*\n Add dynamically instance and static methods for mathematical operations\n */\n\n var inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var inplaceOperatorScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n`;\n\n var inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n`;\n\n var staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n`;\n\n var inplaceMethod = `\n(function %name%() {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%();\n})\n`;\n\n var inplaceMethodWithArgs = `\n(function %name%(%args%) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), %args%));\n }\n }\n return this;\n})\n`;\n\n var staticMethodWithArgs = `\n(function %name%(matrix, %args%) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(%args%);\n})\n`;\n\n\n var inplaceMethodWithOneArgScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), value));\n }\n }\n return this;\n})\n`;\n var inplaceMethodWithOneArgMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var inplaceMethodWithOneArg = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var staticMethodWithOneArg = staticMethodWithArgs;\n\n var operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n ];\n\n var i;\n var eval2 = eval;\n for (var operator of operators) {\n var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]}));\n var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]}));\n var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]}));\n var staticOp = eval2(fillTemplateFunction(staticOperator, {name: operator[1]}));\n for (i = 1; i < operator.length; i++) {\n Matrix.prototype[operator[i]] = inplaceOp;\n Matrix.prototype[operator[i] + 'S'] = inplaceOpS;\n Matrix.prototype[operator[i] + 'M'] = inplaceOpM;\n Matrix[operator[i]] = staticOp;\n }\n }\n\n var methods = [\n ['~', 'not']\n ];\n\n [\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n ].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n });\n\n for (var method of methods) {\n var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]}));\n var staticMeth = eval2(fillTemplateFunction(staticMethod, {name: method[1]}));\n for (i = 1; i < method.length; i++) {\n Matrix.prototype[method[i]] = inplaceMeth;\n Matrix[method[i]] = staticMeth;\n }\n }\n\n var methodsWithArgs = [\n ['Math.pow', 1, 'pow']\n ];\n\n for (var methodWithArg of methodsWithArgs) {\n var args = 'arg0';\n for (i = 1; i < methodWithArg[1]; i++) {\n args += `, arg${i}`;\n }\n if (methodWithArg[1] !== 1) {\n var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, {\n name: methodWithArg[2],\n method: methodWithArg[0],\n args: args\n }));\n var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args}));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\n Matrix[methodWithArg[i]] = staticMethWithArgs;\n }\n } else {\n var tmplVar = {\n name: methodWithArg[2],\n args: args,\n method: methodWithArg[0]\n };\n var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\n var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\n var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\n var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\n Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM;\n Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS;\n Matrix[methodWithArg[i]] = staticMethod2;\n }\n }\n }\n\n function fillTemplateFunction(template, values) {\n for (var value in values) {\n template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]);\n }\n return template;\n }\n\n return Matrix;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/abstractMatrix.js\n// module id = 23\n// module chunks = 0"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// identity function for calling harmony imports with the correct context\n \t__webpack_require__.i = function(value) { return value; };\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 97);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap bdc072b449082cbd48ad","'use strict';\n\nmodule.exports = require('./matrix').Matrix;\nmodule.exports.Decompositions = module.exports.DC = require('./decompositions');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/index.js\n// module id = 0\n// module chunks = 0","'use strict';\n\nfunction squaredEuclidean(p, q) {\n var d = 0;\n for (var i = 0; i < p.length; i++) {\n d += (p[i] - q[i]) * (p[i] - q[i]);\n }\n return d;\n}\n\nfunction euclidean(p, q) {\n return Math.sqrt(squaredEuclidean(p, q));\n}\n\nmodule.exports = euclidean;\neuclidean.squared = squaredEuclidean;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance-euclidean/euclidean.js\n// module id = 1\n// module chunks = 0","'use strict';\n\nexports.array = require('./array');\nexports.matrix = require('./matrix');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-stat/index.js\n// module id = 2\n// module chunks = 0","import './symbol-species';\nimport AbstractMatrix from './abstractMatrix';\nimport {\n checkColumnIndex,\n checkColumnVector,\n checkRowIndex,\n checkRowVector\n} from './util';\n\nexport default class Matrix extends AbstractMatrix(Array) {\n constructor(nRows, nColumns) {\n var i;\n if (arguments.length === 1 && typeof nRows === 'number') {\n return new Array(nRows);\n }\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) { // Create an empty matrix\n super(nRows);\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (i = 0; i < nRows; i++) {\n this[i] = new Array(nColumns);\n }\n } else {\n throw new TypeError('nColumns must be a positive integer');\n }\n } else if (Array.isArray(nRows)) { // Copy the values from the 2D array\n const matrix = nRows;\n nRows = matrix.length;\n nColumns = matrix[0].length;\n if (typeof nColumns !== 'number' || nColumns === 0) {\n throw new TypeError('Data must be a 2D array with at least one element');\n }\n super(nRows);\n for (i = 0; i < nRows; i++) {\n if (matrix[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this[i] = [].concat(matrix[i]);\n }\n } else {\n throw new TypeError('First argument must be a positive number or an array');\n }\n this.rows = nRows;\n this.columns = nColumns;\n return this;\n }\n\n set(rowIndex, columnIndex, value) {\n this[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this[rowIndex][columnIndex];\n }\n\n /**\n * Creates an exact and independent copy of the matrix\n * @return {Matrix}\n */\n clone() {\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\n for (var row = 0; row < this.rows; row++) {\n for (var column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n /**\n * Removes a row from the given index\n * @param {number} index - Row index\n * @return {Matrix} this\n */\n removeRow(index) {\n checkRowIndex(this, index);\n if (this.rows === 1) {\n throw new RangeError('A matrix cannot have less than one row');\n }\n this.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n /**\n * Adds a row at the given index\n * @param {number} [index = this.rows] - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = checkRowVector(this, array, true);\n this.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\n\n /**\n * Removes a column from the given index\n * @param {number} index - Column index\n * @return {Matrix} this\n */\n removeColumn(index) {\n checkColumnIndex(this, index);\n if (this.columns === 1) {\n throw new RangeError('A matrix cannot have less than one column');\n }\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 1);\n }\n this.columns -= 1;\n return this;\n }\n\n /**\n * Adds a column at the given index\n * @param {number} [index = this.columns] - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addColumn(index, array) {\n if (typeof array === 'undefined') {\n array = index;\n index = this.columns;\n }\n checkColumnIndex(this, index, true);\n array = checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 0, array[i]);\n }\n this.columns += 1;\n return this;\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/matrix.js\n// module id = 3\n// module chunks = 0","'use strict';\n\nrequire('./symbol-species');\nvar abstractMatrix = require('./abstractMatrix');\nvar util = require('./util');\n\nclass Matrix extends abstractMatrix(Array) {\n constructor(nRows, nColumns) {\n var i;\n if (arguments.length === 1 && typeof nRows === 'number') {\n return new Array(nRows);\n }\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) { // Create an empty matrix\n super(nRows);\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (i = 0; i < nRows; i++) {\n this[i] = new Array(nColumns);\n }\n } else {\n throw new TypeError('nColumns must be a positive integer');\n }\n } else if (Array.isArray(nRows)) { // Copy the values from the 2D array\n const matrix = nRows;\n nRows = matrix.length;\n nColumns = matrix[0].length;\n if (typeof nColumns !== 'number' || nColumns === 0) {\n throw new TypeError('Data must be a 2D array with at least one element');\n }\n super(nRows);\n for (i = 0; i < nRows; i++) {\n if (matrix[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this[i] = [].concat(matrix[i]);\n }\n } else {\n throw new TypeError('First argument must be a positive number or an array');\n }\n this.rows = nRows;\n this.columns = nColumns;\n return this;\n }\n\n set(rowIndex, columnIndex, value) {\n this[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this[rowIndex][columnIndex];\n }\n\n /**\n * Creates an exact and independent copy of the matrix\n * @return {Matrix}\n */\n clone() {\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\n for (var row = 0; row < this.rows; row++) {\n for (var column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n /**\n * Removes a row from the given index\n * @param {number} index - Row index\n * @return {Matrix} this\n */\n removeRow(index) {\n util.checkRowIndex(this, index);\n if (this.rows === 1) {\n throw new RangeError('A matrix cannot have less than one row');\n }\n this.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n /**\n * Adds a row at the given index\n * @param {number} [index = this.rows] - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n util.checkRowIndex(this, index, true);\n array = util.checkRowVector(this, array, true);\n this.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\n\n /**\n * Removes a column from the given index\n * @param {number} index - Column index\n * @return {Matrix} this\n */\n removeColumn(index) {\n util.checkColumnIndex(this, index);\n if (this.columns === 1) {\n throw new RangeError('A matrix cannot have less than one column');\n }\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 1);\n }\n this.columns -= 1;\n return this;\n }\n\n /**\n * Adds a column at the given index\n * @param {number} [index = this.columns] - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addColumn(index, array) {\n if (typeof array === 'undefined') {\n array = index;\n index = this.columns;\n }\n util.checkColumnIndex(this, index, true);\n array = util.checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 0, array[i]);\n }\n this.columns += 1;\n return this;\n }\n}\n\nexports.Matrix = Matrix;\nMatrix.abstractMatrix = abstractMatrix;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/matrix.js\n// module id = 4\n// module chunks = 0","import './symbol-species';\nimport AbstractMatrix from './abstractMatrix';\nimport {\n checkColumnIndex,\n checkColumnVector,\n checkRowIndex,\n checkRowVector\n} from './util';\n\nexport default class Matrix extends AbstractMatrix(Array) {\n constructor(nRows, nColumns) {\n var i;\n if (arguments.length === 1 && typeof nRows === 'number') {\n return new Array(nRows);\n }\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) { // Create an empty matrix\n super(nRows);\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (i = 0; i < nRows; i++) {\n this[i] = new Array(nColumns);\n }\n } else {\n throw new TypeError('nColumns must be a positive integer');\n }\n } else if (Array.isArray(nRows)) { // Copy the values from the 2D array\n const matrix = nRows;\n nRows = matrix.length;\n nColumns = matrix[0].length;\n if (typeof nColumns !== 'number' || nColumns === 0) {\n throw new TypeError('Data must be a 2D array with at least one element');\n }\n super(nRows);\n for (i = 0; i < nRows; i++) {\n if (matrix[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this[i] = [].concat(matrix[i]);\n }\n } else {\n throw new TypeError('First argument must be a positive number or an array');\n }\n this.rows = nRows;\n this.columns = nColumns;\n return this;\n }\n\n set(rowIndex, columnIndex, value) {\n this[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this[rowIndex][columnIndex];\n }\n\n /**\n * Creates an exact and independent copy of the matrix\n * @return {Matrix}\n */\n clone() {\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\n for (var row = 0; row < this.rows; row++) {\n for (var column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n /**\n * Removes a row from the given index\n * @param {number} index - Row index\n * @return {Matrix} this\n */\n removeRow(index) {\n checkRowIndex(this, index);\n if (this.rows === 1) {\n throw new RangeError('A matrix cannot have less than one row');\n }\n this.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n /**\n * Adds a row at the given index\n * @param {number} [index = this.rows] - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = checkRowVector(this, array, true);\n this.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\n\n /**\n * Removes a column from the given index\n * @param {number} index - Column index\n * @return {Matrix} this\n */\n removeColumn(index) {\n checkColumnIndex(this, index);\n if (this.columns === 1) {\n throw new RangeError('A matrix cannot have less than one column');\n }\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 1);\n }\n this.columns -= 1;\n return this;\n }\n\n /**\n * Adds a column at the given index\n * @param {number} [index = this.columns] - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addColumn(index, array) {\n if (typeof array === 'undefined') {\n array = index;\n index = this.columns;\n }\n checkColumnIndex(this, index, true);\n array = checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 0, array[i]);\n }\n this.columns += 1;\n return this;\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/matrix.js\n// module id = 5\n// module chunks = 0","import './symbol-species';\nimport AbstractMatrix from './abstractMatrix';\nimport {\n checkColumnIndex,\n checkColumnVector,\n checkRowIndex,\n checkRowVector\n} from './util';\n\nexport default class Matrix extends AbstractMatrix(Array) {\n constructor(nRows, nColumns) {\n var i;\n if (arguments.length === 1 && typeof nRows === 'number') {\n return new Array(nRows);\n }\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) { // Create an empty matrix\n super(nRows);\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (i = 0; i < nRows; i++) {\n this[i] = new Array(nColumns);\n }\n } else {\n throw new TypeError('nColumns must be a positive integer');\n }\n } else if (Array.isArray(nRows)) { // Copy the values from the 2D array\n const matrix = nRows;\n nRows = matrix.length;\n nColumns = matrix[0].length;\n if (typeof nColumns !== 'number' || nColumns === 0) {\n throw new TypeError('Data must be a 2D array with at least one element');\n }\n super(nRows);\n for (i = 0; i < nRows; i++) {\n if (matrix[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this[i] = [].concat(matrix[i]);\n }\n } else {\n throw new TypeError('First argument must be a positive number or an array');\n }\n this.rows = nRows;\n this.columns = nColumns;\n return this;\n }\n\n set(rowIndex, columnIndex, value) {\n this[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this[rowIndex][columnIndex];\n }\n\n /**\n * Creates an exact and independent copy of the matrix\n * @return {Matrix}\n */\n clone() {\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\n for (var row = 0; row < this.rows; row++) {\n for (var column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n /**\n * Removes a row from the given index\n * @param {number} index - Row index\n * @return {Matrix} this\n */\n removeRow(index) {\n checkRowIndex(this, index);\n if (this.rows === 1) {\n throw new RangeError('A matrix cannot have less than one row');\n }\n this.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n /**\n * Adds a row at the given index\n * @param {number} [index = this.rows] - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = checkRowVector(this, array, true);\n this.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\n\n /**\n * Removes a column from the given index\n * @param {number} index - Column index\n * @return {Matrix} this\n */\n removeColumn(index) {\n checkColumnIndex(this, index);\n if (this.columns === 1) {\n throw new RangeError('A matrix cannot have less than one column');\n }\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 1);\n }\n this.columns -= 1;\n return this;\n }\n\n /**\n * Adds a column at the given index\n * @param {number} [index = this.columns] - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addColumn(index, array) {\n if (typeof array === 'undefined') {\n array = index;\n index = this.columns;\n }\n checkColumnIndex(this, index, true);\n array = checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 0, array[i]);\n }\n this.columns += 1;\n return this;\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/matrix.js\n// module id = 6\n// module chunks = 0","import './symbol-species';\nimport AbstractMatrix from './abstractMatrix';\nimport {\n checkColumnIndex,\n checkColumnVector,\n checkRowIndex,\n checkRowVector\n} from './util';\n\nexport default class Matrix extends AbstractMatrix(Array) {\n constructor(nRows, nColumns) {\n var i;\n if (arguments.length === 1 && typeof nRows === 'number') {\n return new Array(nRows);\n }\n if (Matrix.isMatrix(nRows)) {\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows > 0) { // Create an empty matrix\n super(nRows);\n if (Number.isInteger(nColumns) && nColumns > 0) {\n for (i = 0; i < nRows; i++) {\n this[i] = new Array(nColumns);\n }\n } else {\n throw new TypeError('nColumns must be a positive integer');\n }\n } else if (Array.isArray(nRows)) { // Copy the values from the 2D array\n const matrix = nRows;\n nRows = matrix.length;\n nColumns = matrix[0].length;\n if (typeof nColumns !== 'number' || nColumns === 0) {\n throw new TypeError('Data must be a 2D array with at least one element');\n }\n super(nRows);\n for (i = 0; i < nRows; i++) {\n if (matrix[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this[i] = [].concat(matrix[i]);\n }\n } else {\n throw new TypeError('First argument must be a positive number or an array');\n }\n this.rows = nRows;\n this.columns = nColumns;\n return this;\n }\n\n set(rowIndex, columnIndex, value) {\n this[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this[rowIndex][columnIndex];\n }\n\n /**\n * Creates an exact and independent copy of the matrix\n * @return {Matrix}\n */\n clone() {\n var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);\n for (var row = 0; row < this.rows; row++) {\n for (var column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n /**\n * Removes a row from the given index\n * @param {number} index - Row index\n * @return {Matrix} this\n */\n removeRow(index) {\n checkRowIndex(this, index);\n if (this.rows === 1) {\n throw new RangeError('A matrix cannot have less than one row');\n }\n this.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n /**\n * Adds a row at the given index\n * @param {number} [index = this.rows] - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = checkRowVector(this, array, true);\n this.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\n\n /**\n * Removes a column from the given index\n * @param {number} index - Column index\n * @return {Matrix} this\n */\n removeColumn(index) {\n checkColumnIndex(this, index);\n if (this.columns === 1) {\n throw new RangeError('A matrix cannot have less than one column');\n }\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 1);\n }\n this.columns -= 1;\n return this;\n }\n\n /**\n * Adds a column at the given index\n * @param {number} [index = this.columns] - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n addColumn(index, array) {\n if (typeof array === 'undefined') {\n array = index;\n index = this.columns;\n }\n checkColumnIndex(this, index, true);\n array = checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this[i].splice(index, 0, array[i]);\n }\n this.columns += 1;\n return this;\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/matrix.js\n// module id = 7\n// module chunks = 0","import AbstractMatrix from '../abstractMatrix';\nimport Matrix from '../matrix';\n\nexport default class BaseView extends AbstractMatrix() {\n constructor(matrix, rows, columns) {\n super();\n this.matrix = matrix;\n this.rows = rows;\n this.columns = columns;\n }\n\n static get [Symbol.species]() {\n return Matrix;\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/views/base.js\n// module id = 8\n// module chunks = 0","'use strict';\n\nvar abstractMatrix = require('../abstractMatrix');\nvar Matrix = require('../matrix');\n\nclass BaseView extends abstractMatrix() {\n constructor(matrix, rows, columns) {\n super();\n this.matrix = matrix;\n this.rows = rows;\n this.columns = columns;\n }\n\n static get [Symbol.species]() {\n return Matrix.Matrix;\n }\n}\n\nmodule.exports = BaseView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/base.js\n// module id = 9\n// module chunks = 0","import AbstractMatrix from '../abstractMatrix';\nimport Matrix from '../matrix';\n\nexport default class BaseView extends AbstractMatrix() {\n constructor(matrix, rows, columns) {\n super();\n this.matrix = matrix;\n this.rows = rows;\n this.columns = columns;\n }\n\n static get [Symbol.species]() {\n return Matrix;\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/views/base.js\n// module id = 10\n// module chunks = 0","import AbstractMatrix from '../abstractMatrix';\nimport Matrix from '../matrix';\n\nexport default class BaseView extends AbstractMatrix() {\n constructor(matrix, rows, columns) {\n super();\n this.matrix = matrix;\n this.rows = rows;\n this.columns = columns;\n }\n\n static get [Symbol.species]() {\n return Matrix;\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/base.js\n// module id = 11\n// module chunks = 0","import AbstractMatrix from '../abstractMatrix';\nimport Matrix from '../matrix';\n\nexport default class BaseView extends AbstractMatrix() {\n constructor(matrix, rows, columns) {\n super();\n this.matrix = matrix;\n this.rows = rows;\n this.columns = columns;\n }\n\n static get [Symbol.species]() {\n return Matrix;\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/views/base.js\n// module id = 12\n// module chunks = 0","module.exports = exports = require('./ArrayUtils');\n\n\nexports.getEquallySpacedData = require('./getEquallySpaced').getEquallySpacedData;\nexports.SNV = require('./snv').SNV;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-array-utils/src/index.js\n// module id = 13\n// module chunks = 0","export {default as maybeToPrecision} from './maybeToPrecision';\nexport {default as checkArrayLength} from './checkArrayLength';\n\nexport default class BaseRegression {\n constructor() {\n if (new.target === BaseRegression) {\n throw new Error('BaseRegression must be subclassed');\n }\n }\n\n predict(x) {\n if (typeof x === 'number') {\n return this._predict(x);\n } else if (Array.isArray(x)) {\n const y = new Array(x.length);\n for (let i = 0; i < x.length; i++) {\n y[i] = this._predict(x[i]);\n }\n return y;\n } else {\n throw new TypeError('x must be a number or array');\n }\n }\n\n _predict() {\n throw new Error('_predict must be implemented');\n }\n\n train() {\n //Do nothing for this package\n }\n\n toString() {\n return '';\n }\n\n toLaTeX() {\n return '';\n }\n\n /**\n * Return the correlation coefficient of determination (r) and chi-square.\n * @param {Array} x\n * @param {Array} y\n * @return {object}\n */\n score(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y) || x.length !== y.length) {\n throw new Error('x and y must be arrays of the same length');\n }\n\n const n = x.length;\n const y2 = new Array(n);\n for (let i = 0; i < n; i++) {\n y2[i] = this._predict(x[i]);\n }\n\n let xSum = 0;\n let ySum = 0;\n let chi2 = 0;\n let rmsd = 0;\n let xSquared = 0;\n let ySquared = 0;\n let xY = 0;\n for (let i = 0; i < n; i++) {\n xSum += y2[i];\n ySum += y[i];\n xSquared += y2[i] * y2[i];\n ySquared += y[i] * y[i];\n xY += y2[i] * y[i];\n if (y[i] !== 0) {\n chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i];\n }\n rmsd = (y[i] - y2[i]) * (y[i] - y2[i]);\n }\n\n const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));\n\n return {\n r: r,\n r2: r * r,\n chi2: chi2,\n rmsd: rmsd * rmsd / n\n };\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-base/src/index.js\n// module id = 14\n// module chunks = 0","import Matrix from './matrix';\n\n/**\n * @private\n * Check that a row index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkRowIndex(matrix, index, outer) {\n var max = outer ? matrix.rows : matrix.rows - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Row index out of range');\n }\n}\n\n/**\n * @private\n * Check that a column index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkColumnIndex(matrix, index, outer) {\n var max = outer ? matrix.columns : matrix.columns - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Column index out of range');\n }\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexport function checkRowVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.columns) {\n throw new RangeError('vector size must be the same as the number of columns');\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 var rowOut = rowIndices.some(r => {\n return r < 0 || r >= matrix.rows;\n\n });\n\n var columnOut = columnIndices.some(c => {\n return c < 0 || c >= matrix.columns;\n });\n\n if (rowOut || columnOut) {\n throw new RangeError('Indices are out of range');\n }\n\n if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') {\n throw new TypeError('Unexpected type for row/column indices');\n }\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\n if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices);\n\n return {\n row: rowIndices,\n column: columnIndices\n };\n}\n\nexport function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\n if (arguments.length !== 5) throw new TypeError('Invalid argument type');\n var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) {\n return typeof arg !== 'number';\n });\n if (notAllNumbers) throw new TypeError('Invalid argument type');\n 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) {\n throw new RangeError('Submatrix indices are out of range');\n }\n}\n\nexport function getRange(from, to) {\n var arr = new Array(to - from + 1);\n for (var i = 0; i < arr.length; i++) {\n arr[i] = from + i;\n }\n return arr;\n}\n\nexport function sumByRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n var v = 0;\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/util.js\n// module id = 15\n// module chunks = 0","'use strict';\n\nvar Matrix = require('./matrix');\n\n/**\n * @private\n * Check that a row index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexports.checkRowIndex = function checkRowIndex(matrix, index, outer) {\n var max = outer ? matrix.rows : matrix.rows - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Row index out of range');\n }\n};\n\n/**\n * @private\n * Check that a column index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexports.checkColumnIndex = function checkColumnIndex(matrix, index, outer) {\n var max = outer ? matrix.columns : matrix.columns - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Column index out of range');\n }\n};\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexports.checkRowVector = function checkRowVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.columns) {\n throw new RangeError('vector size must be the same as the number of columns');\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 */\nexports.checkColumnVector = 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\nexports.checkIndices = function checkIndices(matrix, rowIndices, columnIndices) {\n var rowOut = rowIndices.some(r => {\n return r < 0 || r >= matrix.rows;\n\n });\n\n var columnOut = columnIndices.some(c => {\n return c < 0 || c >= matrix.columns;\n });\n\n if (rowOut || columnOut) {\n throw new RangeError('Indices are out of range');\n }\n\n if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') {\n throw new TypeError('Unexpected type for row/column indices');\n }\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\n if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices);\n\n return {\n row: rowIndices,\n column: columnIndices\n };\n};\n\nexports.checkRange = function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\n if (arguments.length !== 5) throw new TypeError('Invalid argument type');\n var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) {\n return typeof arg !== 'number';\n });\n if (notAllNumbers) throw new TypeError('Invalid argument type');\n 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) {\n throw new RangeError('Submatrix indices are out of range');\n }\n};\n\nexports.getRange = function getRange(from, to) {\n var arr = new Array(to - from + 1);\n for (var i = 0; i < arr.length; i++) {\n arr[i] = from + i;\n }\n return arr;\n};\n\nexports.sumByRow = function sumByRow(matrix) {\n var sum = Matrix.Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\n }\n }\n return sum;\n};\n\nexports.sumByColumn = function sumByColumn(matrix) {\n var sum = Matrix.Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\n }\n }\n return sum;\n};\n\nexports.sumAll = function sumAll(matrix) {\n var v = 0;\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/util.js\n// module id = 16\n// module chunks = 0","import Matrix from './matrix';\n\n/**\n * @private\n * Check that a row index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkRowIndex(matrix, index, outer) {\n var max = outer ? matrix.rows : matrix.rows - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Row index out of range');\n }\n}\n\n/**\n * @private\n * Check that a column index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkColumnIndex(matrix, index, outer) {\n var max = outer ? matrix.columns : matrix.columns - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Column index out of range');\n }\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexport function checkRowVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.columns) {\n throw new RangeError('vector size must be the same as the number of columns');\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 var rowOut = rowIndices.some(r => {\n return r < 0 || r >= matrix.rows;\n\n });\n\n var columnOut = columnIndices.some(c => {\n return c < 0 || c >= matrix.columns;\n });\n\n if (rowOut || columnOut) {\n throw new RangeError('Indices are out of range');\n }\n\n if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') {\n throw new TypeError('Unexpected type for row/column indices');\n }\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\n if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices);\n\n return {\n row: rowIndices,\n column: columnIndices\n };\n}\n\nexport function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\n if (arguments.length !== 5) throw new TypeError('Invalid argument type');\n var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) {\n return typeof arg !== 'number';\n });\n if (notAllNumbers) throw new TypeError('Invalid argument type');\n 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) {\n throw new RangeError('Submatrix indices are out of range');\n }\n}\n\nexport function getRange(from, to) {\n var arr = new Array(to - from + 1);\n for (var i = 0; i < arr.length; i++) {\n arr[i] = from + i;\n }\n return arr;\n}\n\nexport function sumByRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n var v = 0;\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/util.js\n// module id = 17\n// module chunks = 0","import Matrix from './matrix';\n\n/**\n * @private\n * Check that a row index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkRowIndex(matrix, index, outer) {\n var max = outer ? matrix.rows : matrix.rows - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Row index out of range');\n }\n}\n\n/**\n * @private\n * Check that a column index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkColumnIndex(matrix, index, outer) {\n var max = outer ? matrix.columns : matrix.columns - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Column index out of range');\n }\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexport function checkRowVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.columns) {\n throw new RangeError('vector size must be the same as the number of columns');\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 var rowOut = rowIndices.some(r => {\n return r < 0 || r >= matrix.rows;\n\n });\n\n var columnOut = columnIndices.some(c => {\n return c < 0 || c >= matrix.columns;\n });\n\n if (rowOut || columnOut) {\n throw new RangeError('Indices are out of range');\n }\n\n if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') {\n throw new TypeError('Unexpected type for row/column indices');\n }\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\n if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices);\n\n return {\n row: rowIndices,\n column: columnIndices\n };\n}\n\nexport function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\n if (arguments.length !== 5) throw new TypeError('Invalid argument type');\n var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) {\n return typeof arg !== 'number';\n });\n if (notAllNumbers) throw new TypeError('Invalid argument type');\n 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) {\n throw new RangeError('Submatrix indices are out of range');\n }\n}\n\nexport function getRange(from, to) {\n var arr = new Array(to - from + 1);\n for (var i = 0; i < arr.length; i++) {\n arr[i] = from + i;\n }\n return arr;\n}\n\nexport function sumByRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n var v = 0;\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/util.js\n// module id = 18\n// module chunks = 0","import Matrix from './matrix';\n\n/**\n * @private\n * Check that a row index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkRowIndex(matrix, index, outer) {\n var max = outer ? matrix.rows : matrix.rows - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Row index out of range');\n }\n}\n\n/**\n * @private\n * Check that a column index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkColumnIndex(matrix, index, outer) {\n var max = outer ? matrix.columns : matrix.columns - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Column index out of range');\n }\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexport function checkRowVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.columns) {\n throw new RangeError('vector size must be the same as the number of columns');\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 var rowOut = rowIndices.some(r => {\n return r < 0 || r >= matrix.rows;\n\n });\n\n var columnOut = columnIndices.some(c => {\n return c < 0 || c >= matrix.columns;\n });\n\n if (rowOut || columnOut) {\n throw new RangeError('Indices are out of range');\n }\n\n if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') {\n throw new TypeError('Unexpected type for row/column indices');\n }\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\n if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices);\n\n return {\n row: rowIndices,\n column: columnIndices\n };\n}\n\nexport function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\n if (arguments.length !== 5) throw new TypeError('Invalid argument type');\n var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) {\n return typeof arg !== 'number';\n });\n if (notAllNumbers) throw new TypeError('Invalid argument type');\n 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) {\n throw new RangeError('Submatrix indices are out of range');\n }\n}\n\nexport function getRange(from, to) {\n var arr = new Array(to - from + 1);\n for (var i = 0; i < arr.length; i++) {\n arr[i] = from + i;\n }\n return arr;\n}\n\nexport function sumByRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum.set(0, j, sum.get(0, j) + matrix.get(i, j));\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n var v = 0;\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/util.js\n// module id = 19\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix').Matrix;\n\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst ANOVAKernel = require('./kernels/anova-kernel');\nconst CauchyKernel = require('./kernels/cauchy-kernel');\nconst ExponentialKernel = require('./kernels/exponential-kernel');\nconst HistogramKernel = require('./kernels/histogram-intersection-kernel');\nconst LaplacianKernel = require('./kernels/laplacian-kernel');\nconst MultiquadraticKernel = require('./kernels/multiquadratic-kernel');\nconst RationalKernel = require('./kernels/rational-quadratic-kernel');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\nconst kernelType = {\n gaussian: GaussianKernel,\n rbf: GaussianKernel,\n polynomial: PolynomialKernel,\n poly: PolynomialKernel,\n anova: ANOVAKernel,\n cauchy: CauchyKernel,\n exponential: ExponentialKernel,\n histogram: HistogramKernel,\n min: HistogramKernel,\n laplacian: LaplacianKernel,\n multiquadratic: MultiquadraticKernel,\n rational: RationalKernel,\n sigmoid: SigmoidKernel,\n mlp: SigmoidKernel\n};\n\nclass Kernel {\n constructor(type, options) {\n this.kernelType = type;\n if (type === 'linear') return;\n\n if (typeof type === 'string') {\n type = type.toLowerCase();\n\n var KernelConstructor = kernelType[type];\n if (KernelConstructor) {\n this.kernelFunction = new KernelConstructor(options);\n } else {\n throw new Error('unsupported kernel type: ' + type);\n }\n } else if (typeof type === 'object' && typeof type.compute === 'function') {\n this.kernelFunction = type;\n } else {\n throw new TypeError('first argument must be a valid kernel type or instance');\n }\n }\n\n compute(inputs, landmarks) {\n if (landmarks === undefined) {\n landmarks = inputs;\n }\n\n if (this.kernelType === 'linear') {\n var matrix = new Matrix(inputs);\n return matrix.mmul(new Matrix(landmarks).transposeView());\n }\n\n const kernelMatrix = new Matrix(inputs.length, landmarks.length);\n var i, j;\n if (inputs === landmarks) { // fast path, matrix is symmetric\n for (i = 0; i < inputs.length; i++) {\n for (j = i; j < inputs.length; j++) {\n kernelMatrix[i][j] = kernelMatrix[j][i] = this.kernelFunction.compute(inputs[i], inputs[j]);\n }\n }\n } else {\n for (i = 0; i < inputs.length; i++) {\n for (j = 0; j < landmarks.length; j++) {\n kernelMatrix[i][j] = this.kernelFunction.compute(inputs[i], landmarks[j]);\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernel.js\n// module id = 20\n// module chunks = 0","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = target[name];\n\t\t\t\tcopy = options[name];\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\ttarget[name] = extend(deep, clone, copy);\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\ttarget[name] = copy;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/extend/index.js\n// module id = 21\n// module chunks = 0","'use strict';\n\nconst Heap = require('heap');\n\nfunction Cluster() {\n this.children = [];\n this.distance = -1;\n this.index = [];\n}\n\n/**\n * Creates an array of values where maximum distance smaller than the threshold\n * @param {number} threshold\n * @return {Array }\n */\nCluster.prototype.cut = function (threshold) {\n if (threshold < 0) throw new RangeError('Threshold too small');\n var root = new Cluster();\n root.children = this.children;\n root.distance = this.distance;\n root.index = this.index;\n var list = [root];\n var ans = [];\n while (list.length > 0) {\n var aux = list.shift();\n if (threshold >= aux.distance) {\n ans.push(aux);\n } else {\n list = list.concat(aux.children);\n }\n }\n return ans;\n};\n\n/**\n * Merge the leaves in the minimum way to have 'minGroups' number of clusters\n * @param {number} minGroups - Them minimum number of children the first level of the tree should have\n * @return {Cluster}\n */\nCluster.prototype.group = function (minGroups) {\n if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer');\n\n const heap = new Heap(function (a, b) {\n return b.distance - a.distance;\n });\n\n heap.push(this);\n\n while (heap.size() < minGroups) {\n var first = heap.pop();\n if (first.children.length === 0) {\n break;\n }\n first.children.forEach(child => heap.push(child));\n }\n\n var root = new Cluster();\n root.children = heap.toArray();\n root.distance = this.distance;\n\n return root;\n};\n\n/**\n * Traverses the tree depth-first and provide callback to be called on each individual node\n * @param {function} cb - The callback to be called on each node encounter\n * @type {Cluster}\n */\nCluster.prototype.traverse = function (cb) {\n function visit(root, callback) {\n callback(root);\n if (root.children) {\n for (var i = root.children.length - 1; i >= 0; i--) {\n visit(root.children[i], callback);\n }\n }\n }\n visit(this, cb);\n};\n\nmodule.exports = Cluster;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/Cluster.js\n// module id = 22\n// module chunks = 0","import Matrix from '../matrix';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\nfunction LuDecomposition(matrix) {\n if (!(this instanceof LuDecomposition)) {\n return new LuDecomposition(matrix);\n }\n\n matrix = Matrix.checkMatrix(matrix);\n\n var lu = matrix.clone(),\n rows = lu.rows,\n columns = lu.columns,\n pivotVector = new Array(rows),\n pivotSign = 1,\n i, j, k, p, s, t, v,\n LUrowi, LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Array(rows);\n\n for (j = 0; j < columns; j++) {\n\n for (i = 0; i < rows; i++) {\n LUcolj[i] = lu[i][j];\n }\n\n for (i = 0; i < rows; i++) {\n LUrowi = lu[i];\n kmax = Math.min(i, j);\n s = 0;\n for (k = 0; k < kmax; k++) {\n s += LUrowi[k] * LUcolj[k];\n }\n LUrowi[j] = LUcolj[i] -= s;\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[p][k];\n lu[p][k] = lu[j][k];\n lu[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[j][j] !== 0) {\n for (i = j + 1; i < rows; i++) {\n lu[i][j] /= lu[j][j];\n }\n }\n }\n\n this.LU = lu;\n this.pivotVector = pivotVector;\n this.pivotSign = pivotSign;\n}\n\nLuDecomposition.prototype = {\n isSingular: function () {\n var data = this.LU,\n col = data.columns;\n for (var j = 0; j < col; j++) {\n if (data[j][j] === 0) {\n return true;\n }\n }\n return false;\n },\n get determinant() {\n var data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n var determinant = this.pivotSign, col = data.columns;\n for (var j = 0; j < col; j++) {\n determinant *= data[j][j];\n }\n return determinant;\n },\n get lowerTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i > j) {\n X[i][j] = data[i][j];\n } else if (i === j) {\n X[i][j] = 1;\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get upperTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i <= j) {\n X[i][j] = data[i][j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get pivotPermutationVector() {\n return this.pivotVector.slice();\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var lu = this.LU,\n rows = lu.rows;\n\n if (rows !== value.rows) {\n throw new Error('Invalid matrix dimensions');\n }\n if (this.isSingular()) {\n throw new Error('LU matrix is singular');\n }\n\n var count = value.columns;\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n var columns = lu.columns;\n var i, j, k;\n\n for (k = 0; k < columns; k++) {\n for (i = k + 1; i < columns; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= lu[k][k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n return X;\n }\n};\n\nexport default LuDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/dc/lu.js\n// module id = 24\n// module chunks = 0","export function hypotenuse(a, b) {\n var r;\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\n// For use in the decomposition algorithms. With big matrices, access time is\n// too long on elements from array subclass\n// todo check when it is fixed in v8\n// http://jsperf.com/access-and-write-array-subclass\nexport function getEmpty2DArray(rows, columns) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n }\n return array;\n}\n\nexport function getFilled2DArray(rows, columns, value) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n for (var j = 0; j < columns; j++) {\n array[i][j] = value;\n }\n }\n return array;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/dc/util.js\n// module id = 25\n// module chunks = 0","'use strict';\n\nexports.hypotenuse = function hypotenuse(a, b) {\n var r;\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\n// For use in the decomposition algorithms. With big matrices, access time is\n// too long on elements from array subclass\n// todo check when it is fixed in v8\n// http://jsperf.com/access-and-write-array-subclass\nexports.getEmpty2DArray = function (rows, columns) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n }\n return array;\n};\n\nexports.getFilled2DArray = function (rows, columns, value) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n for (var j = 0; j < columns; j++) {\n array[i][j] = value;\n }\n }\n return array;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/util.js\n// module id = 26\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix');\nconst Stat = require('ml-stat');\n\n/**\n * Function that given vector, returns his norm\n * @param {Vector} X\n * @returns {number} Norm of the vector\n */\nfunction norm(X) {\n return Math.sqrt(X.clone().apply(pow2array).sum());\n}\n\n/**\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 i - index i.\n * @param j - index j.\n * @return The Matrix object modified at the index i, j.\n * */\nfunction pow2array(i, j) {\n this[i][j] = this[i][j] * this[i][j];\n return this;\n}\n\n/**\n * Function that normalize the dataset and return the means and\n * standard deviation of each feature.\n * @param dataset\n * @returns {{result: Matrix, means: (*|number), std: Matrix}} dataset normalized, means\n * and standard deviations\n */\nfunction featureNormalize(dataset) {\n var means = Stat.matrix.mean(dataset);\n var std = Stat.matrix.standardDeviation(dataset, means, true);\n var result = Matrix.checkMatrix(dataset).subRowVector(means);\n return {result: result.divRowVector(std), means: means, std: std};\n}\n\nmodule.exports = {\n norm: norm,\n pow2array: pow2array,\n featureNormalize: featureNormalize\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pls/src/utils.js\n// module id = 27\n// module chunks = 0","import LuDecomposition from './dc/lu';\nimport SvDecomposition from './dc/svd';\nimport {scale} from 'ml-array-utils';\nimport * as util from './util';\nimport MatrixTransposeView from './views/transpose';\nimport MatrixRowView from './views/row';\nimport MatrixSubView from './views/sub';\nimport MatrixSelectionView from './views/selection';\nimport MatrixColumnView from './views/column';\nimport MatrixFlipRowView from './views/flipRow';\nimport MatrixFlipColumnView from './views/flipColumn';\n\nexport default function AbstractMatrix(superCtor) {\n if (superCtor === undefined) superCtor = Object;\n\n /**\n * Real matrix\n * @class Matrix\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\n * 2D array containing the data or Matrix instance to clone\n * @param {number} [nColumns] - Number of columns of the new matrix\n */\n class Matrix extends superCtor {\n static get [Symbol.species]() {\n return this;\n }\n\n /**\n * Constructs a Matrix with the chosen dimensions from a 1D array\n * @param {number} newRows - Number of rows\n * @param {number} newColumns - Number of columns\n * @param {Array} newData - A 1D array containing data for the matrix\n * @return {Matrix} - The new matrix\n */\n static from1DArray(newRows, newColumns, newData) {\n var length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('Data length does not match given dimensions');\n }\n var newMatrix = new this(newRows, newColumns);\n for (var row = 0; row < newRows; row++) {\n for (var column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n /**\n * Creates a row vector, a matrix with only one row.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static rowVector(newData) {\n var vector = new this(1, newData.length);\n for (var i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates a column vector, a matrix with only one column.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static columnVector(newData) {\n var vector = new this(newData.length, 1);\n for (var i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static empty(rows, columns) {\n return new this(rows, columns);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to zero.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static zeros(rows, columns) {\n return this.empty(rows, columns).fill(0);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to one.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static ones(rows, columns) {\n return this.empty(rows, columns).fill(1);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be randomly set.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static rand(rows, columns, rng) {\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n matrix.set(i, j, rng());\n }\n }\n return matrix;\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be random integers.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {number} [maxValue=1000] - Maximum value\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static randInt(rows, columns, maxValue, rng) {\n if (maxValue === undefined) maxValue = 1000;\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = Math.floor(rng() * maxValue);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n /**\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\n * @param {number} rows - Number of rows\n * @param {number} [columns=rows] - Number of columns\n * @param {number} [value=1] - Value to fill the diagonal with\n * @return {Matrix} - The new identity matrix\n */\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n var min = Math.min(rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n /**\n * Creates a diagonal matrix based on the given array.\n * @param {Array} data - Array containing the data for the diagonal\n * @param {number} [rows] - Number of rows (Default: data.length)\n * @param {number} [columns] - Number of columns (Default: rows)\n * @return {Matrix} - The new diagonal matrix\n */\n static diag(data, rows, columns) {\n var l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n var min = Math.min(l, rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n /**\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Check that the provided value is a Matrix and tries to instantiate one if not\n * @param {*} value - The value to check\n * @return {Matrix}\n */\n static checkMatrix(value) {\n return Matrix.isMatrix(value) ? value : new this(value);\n }\n\n /**\n * Returns true if the argument is a Matrix, false otherwise\n * @param {*} value - The value to check\n * @return {boolean}\n */\n static isMatrix(value) {\n return (value != null) && (value.klass === 'Matrix');\n }\n\n /**\n * @prop {number} size - The number of elements in the matrix.\n */\n get size() {\n return this.rows * this.columns;\n }\n\n /**\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\n * @return {Matrix} this\n */\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n var ii = this.rows;\n var jj = this.columns;\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n /**\n * Returns a new 1D array filled row by row with the matrix values\n * @return {Array}\n */\n to1DArray() {\n var array = new Array(this.size);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n array[i * this.columns + j] = this.get(i, j);\n }\n }\n return array;\n }\n\n /**\n * Returns a 2D array containing a copy of the data\n * @return {Array}\n */\n to2DArray() {\n var copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n /**\n * @return {boolean} true if the matrix has one row\n */\n isRowVector() {\n return this.rows === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one column\n */\n isColumnVector() {\n return this.columns === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one row or one column\n */\n isVector() {\n return (this.rows === 1) || (this.columns === 1);\n }\n\n /**\n * @return {boolean} true if the matrix has the same number of rows and columns\n */\n isSquare() {\n return this.rows === this.columns;\n }\n\n /**\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\n */\n isSymmetric() {\n if (this.isSquare()) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j <= i; j++) {\n if (this.get(i, j) !== this.get(j, i)) {\n return false;\n }\n }\n }\n return true;\n }\n return false;\n }\n\n /**\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @param {number} value - The new value for the element\n * @return {Matrix} this\n */\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\n throw new Error('set method is unimplemented');\n }\n\n /**\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @return {number}\n */\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\n throw new Error('get method is unimplemented');\n }\n\n /**\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\n * rows of the matrix, and colRep times the number of columns of the matrix\n * @param {number} rowRep - Number of times the rows should be repeated\n * @param {number} colRep - Number of times the columns should be re\n * @return {Matrix}\n * @example\n * var matrix = new Matrix([[1,2]]);\n * matrix.repeat(2); // [[1,2],[1,2]]\n */\n repeat(rowRep, colRep) {\n rowRep = rowRep || 1;\n colRep = colRep || 1;\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\n for (var i = 0; i < rowRep; i++) {\n for (var j = 0; j < colRep; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n /**\n * Fills the matrix with a given value. All elements will be set to this value.\n * @param {number} value - New value\n * @return {Matrix} this\n */\n fill(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n /**\n * Negates the matrix. All elements will be multiplied by (-1)\n * @return {Matrix} this\n */\n neg() {\n return this.mulS(-1);\n }\n\n /**\n * Returns a new array from the given row index\n * @param {number} index - Row index\n * @return {Array}\n */\n getRow(index) {\n util.checkRowIndex(this, index);\n var row = new Array(this.columns);\n for (var i = 0; i < this.columns; i++) {\n row[i] = this.get(index, i);\n }\n return row;\n }\n\n /**\n * Returns a new row vector from the given row index\n * @param {number} index - Row index\n * @return {Matrix}\n */\n getRowVector(index) {\n return this.constructor.rowVector(this.getRow(index));\n }\n\n /**\n * Sets a row at the given index\n * @param {number} index - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setRow(index, array) {\n util.checkRowIndex(this, index);\n array = util.checkRowVector(this, array);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two rows\n * @param {number} row1 - First row index\n * @param {number} row2 - Second row index\n * @return {Matrix} this\n */\n swapRows(row1, row2) {\n util.checkRowIndex(this, row1);\n util.checkRowIndex(this, row2);\n for (var i = 0; i < this.columns; i++) {\n var temp = this.get(row1, i);\n this.set(row1, i, this.get(row2, i));\n this.set(row2, i, temp);\n }\n return this;\n }\n\n /**\n * Returns a new array from the given column index\n * @param {number} index - Column index\n * @return {Array}\n */\n getColumn(index) {\n util.checkColumnIndex(this, index);\n var column = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n column[i] = this.get(i, index);\n }\n return column;\n }\n\n /**\n * Returns a new column vector from the given column index\n * @param {number} index - Column index\n * @return {Matrix}\n */\n getColumnVector(index) {\n return this.constructor.columnVector(this.getColumn(index));\n }\n\n /**\n * Sets a column at the given index\n * @param {number} index - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setColumn(index, array) {\n util.checkColumnIndex(this, index);\n array = util.checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two columns\n * @param {number} column1 - First column index\n * @param {number} column2 - Second column index\n * @return {Matrix} this\n */\n swapColumns(column1, column2) {\n util.checkColumnIndex(this, column1);\n util.checkColumnIndex(this, column2);\n for (var i = 0; i < this.rows; i++) {\n var temp = this.get(i, column1);\n this.set(i, column1, this.get(i, column2));\n this.set(i, column2, temp);\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each row by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each column by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a row with a scalar\n * @param {number} index - Row index\n * @param {number} value\n * @return {Matrix} this\n */\n mulRow(index, value) {\n util.checkRowIndex(this, index);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n /**\n * Multiplies the values of a column with a scalar\n * @param {number} index - Column index\n * @param {number} value\n * @return {Matrix} this\n */\n mulColumn(index, value) {\n util.checkColumnIndex(this, index);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n /**\n * Returns the maximum value of the matrix\n * @return {number}\n */\n max() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value\n * @return {Array}\n */\n maxIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of the matrix\n * @return {number}\n */\n min() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value\n * @return {Array}\n */\n minIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n maxRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n maxRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n minRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n minRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n maxColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n maxColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n minColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n minColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns an array containing the diagonal values of the matrix\n * @return {Array}\n */\n diag() {\n var min = Math.min(this.rows, this.columns);\n var diag = new Array(min);\n for (var i = 0; i < min; i++) {\n diag[i] = this.get(i, i);\n }\n return diag;\n }\n\n /**\n * Returns the sum by the argument given, if no argument given,\n * it returns the sum of all elements of the matrix.\n * @param {string} by - sum by 'row' or 'column'.\n * @return {Matrix|number}\n */\n sum(by) {\n switch (by) {\n case 'row':\n return util.sumByRow(this);\n case 'column':\n return util.sumByColumn(this);\n default:\n return util.sumAll(this);\n }\n }\n\n /**\n * Returns the mean of all elements of the matrix\n * @return {number}\n */\n mean() {\n return this.sum() / this.size;\n }\n\n /**\n * Returns the product of all elements of the matrix\n * @return {number}\n */\n prod() {\n var prod = 1;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n prod *= this.get(i, j);\n }\n }\n return prod;\n }\n\n /**\n * Computes the cumulative sum of the matrix elements (in place, row by row)\n * @return {Matrix} this\n */\n cumulativeSum() {\n var sum = 0;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n sum += this.get(i, j);\n this.set(i, j, sum);\n }\n }\n return this;\n }\n\n /**\n * Computes the dot (scalar) product between the matrix and another\n * @param {Matrix} vector2 vector\n * @return {number}\n */\n dot(vector2) {\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n var vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n var dot = 0;\n for (var i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n /**\n * Returns the matrix product between this and other\n * @param {Matrix} other\n * @return {Matrix}\n */\n mmul(other) {\n other = this.constructor.checkMatrix(other);\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n var m = this.rows;\n var n = this.columns;\n var p = other.columns;\n\n var result = new this.constructor[Symbol.species](m, p);\n\n var Bcolj = new Array(n);\n for (var j = 0; j < p; j++) {\n for (var k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (var i = 0; i < m; i++) {\n var s = 0;\n for (k = 0; k < n; k++) {\n s += this.get(i, k) * Bcolj[k];\n }\n\n result.set(i, j, s);\n }\n }\n return result;\n }\n\n strassen2x2(other) {\n var result = new this.constructor[Symbol.species](2, 2);\n const a11 = this.get(0, 0);\n const b11 = other.get(0, 0);\n const a12 = this.get(0, 1);\n const b12 = other.get(0, 1);\n const a21 = this.get(1, 0);\n const b21 = other.get(1, 0);\n const a22 = this.get(1, 1);\n const b22 = other.get(1, 1);\n\n // Compute intermediate values.\n const m1 = (a11 + a22) * (b11 + b22);\n const m2 = (a21 + a22) * b11;\n const m3 = a11 * (b12 - b22);\n const m4 = a22 * (b21 - b11);\n const m5 = (a11 + a12) * b22;\n const m6 = (a21 - a11) * (b11 + b12);\n const m7 = (a12 - a22) * (b21 + b22);\n\n // Combine intermediate values into the output.\n const c00 = m1 + m4 - m5 + m7;\n const c01 = m3 + m5;\n const c10 = m2 + m4;\n const c11 = m1 - m2 + m3 + m6;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n return result;\n }\n\n strassen3x3(other) {\n var result = new this.constructor[Symbol.species](3, 3);\n\n const a00 = this.get(0, 0);\n const a01 = this.get(0, 1);\n const a02 = this.get(0, 2);\n const a10 = this.get(1, 0);\n const a11 = this.get(1, 1);\n const a12 = this.get(1, 2);\n const a20 = this.get(2, 0);\n const a21 = this.get(2, 1);\n const a22 = this.get(2, 2);\n\n const b00 = other.get(0, 0);\n const b01 = other.get(0, 1);\n const b02 = other.get(0, 2);\n const b10 = other.get(1, 0);\n const b11 = other.get(1, 1);\n const b12 = other.get(1, 2);\n const b20 = other.get(2, 0);\n const b21 = other.get(2, 1);\n const b22 = other.get(2, 2);\n\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\n const m2 = (a00 - a10) * (-b01 + b11);\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\n const m5 = (a10 + a11) * (-b00 + b01);\n const m6 = a00 * b00;\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\n const m8 = (-a00 + a20) * (b02 - b12);\n const m9 = (a20 + a21) * (-b00 + b02);\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\n const m13 = (a02 - a22) * (b11 - b21);\n const m14 = a02 * b20;\n const m15 = (a21 + a22) * (-b20 + b21);\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\n const m17 = (a02 - a12) * (b12 - b22);\n const m18 = (a11 + a12) * (-b20 + b22);\n const m19 = a01 * b10;\n const m20 = a12 * b21;\n const m21 = a10 * b02;\n const m22 = a20 * b01;\n const m23 = a22 * b22;\n\n const c00 = m6 + m14 + m19;\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\n const c11 = m2 + m4 + m5 + m6 + m20;\n const c12 = m14 + m16 + m17 + m18 + m21;\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\n const c21 = m12 + m13 + m14 + m15 + m22;\n const c22 = m6 + m7 + m8 + m9 + m23;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(0, 2, c02);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n result.set(1, 2, c12);\n result.set(2, 0, c20);\n result.set(2, 1, c21);\n result.set(2, 2, c22);\n return result;\n }\n\n /**\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\n * @param {Matrix} y\n * @return {Matrix}\n */\n mmulStrassen(y) {\n var x = this.clone();\n var r1 = x.rows;\n var c1 = x.columns;\n var r2 = y.rows;\n var c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\n }\n\n // Put a matrix into the top left of a matrix of zeros.\n // `rows` and `cols` are the dimensions of the output matrix.\n function embed(mat, rows, cols) {\n var r = mat.rows;\n var c = mat.columns;\n if ((r === rows) && (c === cols)) {\n return mat;\n } else {\n var resultat = Matrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\n }\n }\n\n\n // Make sure both matrices are the same size.\n // This is exclusively for simplicity:\n // this algorithm can be implemented with matrices of different sizes.\n\n var r = Math.max(r1, r2);\n var c = Math.max(c1, c2);\n x = embed(x, r, c);\n y = embed(y, r, c);\n\n // Our recursive multiplication function.\n function blockMult(a, b, rows, cols) {\n // For small matrices, resort to naive multiplication.\n if (rows <= 512 || cols <= 512) {\n return a.mmul(b); // a is equivalent to this\n }\n\n // Apply dynamic padding.\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\n a = embed(a, rows + 1, cols + 1);\n b = embed(b, rows + 1, cols + 1);\n } else if (rows % 2 === 1) {\n a = embed(a, rows + 1, cols);\n b = embed(b, rows + 1, cols);\n } else if (cols % 2 === 1) {\n a = embed(a, rows, cols + 1);\n b = embed(b, rows, cols + 1);\n }\n\n var halfRows = parseInt(a.rows / 2);\n var halfCols = parseInt(a.columns / 2);\n // Subdivide input matrices.\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\n\n // Combine intermediate values into the output.\n var c11 = Matrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n var c12 = Matrix.add(m3, m5);\n var c21 = Matrix.add(m2, m4);\n var c22 = Matrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n //Crop output to the desired size (undo dynamic padding).\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\n resultat = resultat.setSubMatrix(c11, 0, 0);\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\n }\n return blockMult(x, y, r, c);\n }\n\n /**\n * Returns a row-by-row scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The scaled matrix\n */\n scaleRows(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.rows; i++) {\n var scaled = scale(this.getRow(i), {min, max});\n newMatrix.setRow(i, scaled);\n }\n return newMatrix;\n }\n\n /**\n * Returns a new column-by-column scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The new scaled matrix\n * @example\n * var matrix = new Matrix([[1,2],[-1,0]]);\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\n */\n scaleColumns(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.columns; i++) {\n var scaled = scale(this.getColumn(i), {\n min: min,\n max: max\n });\n newMatrix.setColumn(i, scaled);\n }\n return newMatrix;\n }\n\n\n /**\n * Returns the Kronecker product (also known as tensor product) between this and other\n * See https://en.wikipedia.org/wiki/Kronecker_product\n * @param {Matrix} other\n * @return {Matrix}\n */\n kroneckerProduct(other) {\n other = this.constructor.checkMatrix(other);\n\n var m = this.rows;\n var n = this.columns;\n var p = other.rows;\n var q = other.columns;\n\n var result = new this.constructor[Symbol.species](m * p, n * q);\n for (var i = 0; i < m; i++) {\n for (var j = 0; j < n; j++) {\n for (var k = 0; k < p; k++) {\n for (var l = 0; l < q; l++) {\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Transposes the matrix and returns a new one containing the result\n * @return {Matrix}\n */\n transpose() {\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n /**\n * Sorts the rows (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortRows(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Sorts the columns (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortColumns(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Returns a subset of the matrix\n * @param {number} startRow - First row index\n * @param {number} endRow - Last row index\n * @param {number} startColumn - First column index\n * @param {number} endColumn - Last column index\n * @return {Matrix}\n */\n subMatrix(startRow, endRow, startColumn, endColumn) {\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\n for (var i = startRow; i <= endRow; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of row indices\n * @param {Array} indices - Array containing the row indices\n * @param {number} [startColumn = 0] - First column index\n * @param {number} [endColumn = this.columns-1] - Last column index\n * @return {Matrix}\n */\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n if (indices[i] < 0 || indices[i] >= this.rows) {\n throw new RangeError('Row index out of range: ' + indices[i]);\n }\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of column indices\n * @param {Array} indices - Array containing the column indices\n * @param {number} [startRow = 0] - First row index\n * @param {number} [endRow = this.rows-1] - Last row index\n * @return {Matrix}\n */\n subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startRow; j <= endRow; j++) {\n if (indices[i] < 0 || indices[i] >= this.columns) {\n throw new RangeError('Column index out of range: ' + indices[i]);\n }\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\n }\n }\n return newMatrix;\n }\n\n /**\n * Set a part of the matrix to the given sub-matrix\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\n * @param {number} startRow - The index of the first row to set\n * @param {number} startColumn - The index of the first column to set\n * @return {Matrix}\n */\n setSubMatrix(matrix, startRow, startColumn) {\n matrix = this.constructor.checkMatrix(matrix);\n var endRow = startRow + matrix.rows - 1;\n var endColumn = startColumn + matrix.columns - 1;\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n this[startRow + i][startColumn + j] = matrix.get(i, j);\n }\n }\n return this;\n }\n\n /**\n * Return a new matrix based on a selection of rows and columns\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\n * @return {Matrix} The new matrix\n */\n selection(rowIndices, columnIndices) {\n var indices = util.checkIndices(this, rowIndices, columnIndices);\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\n for (var i = 0; i < indices.row.length; i++) {\n var rowIndex = indices.row[i];\n for (var j = 0; j < indices.column.length; j++) {\n var columnIndex = indices.column[j];\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns the trace of the matrix (sum of the diagonal elements)\n * @return {number}\n */\n trace() {\n var min = Math.min(this.rows, this.columns);\n var trace = 0;\n for (var i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n /*\n Matrix views\n */\n\n /**\n * Returns a view of the transposition of the matrix\n * @return {MatrixTransposeView}\n */\n transposeView() {\n return new MatrixTransposeView(this);\n }\n\n /**\n * Returns a view of the row vector with the given index\n * @param {number} row - row index of the vector\n * @return {MatrixRowView}\n */\n rowView(row) {\n util.checkRowIndex(this, row);\n return new MatrixRowView(this, row);\n }\n\n /**\n * Returns a view of the column vector with the given index\n * @param {number} column - column index of the vector\n * @return {MatrixColumnView}\n */\n columnView(column) {\n util.checkColumnIndex(this, column);\n return new MatrixColumnView(this, column);\n }\n\n /**\n * Returns a view of the matrix flipped in the row axis\n * @return {MatrixFlipRowView}\n */\n flipRowView() {\n return new MatrixFlipRowView(this);\n }\n\n /**\n * Returns a view of the matrix flipped in the column axis\n * @return {MatrixFlipColumnView}\n */\n flipColumnView() {\n return new MatrixFlipColumnView(this);\n }\n\n /**\n * Returns a view of a submatrix giving the index boundaries\n * @param {number} startRow - first row index of the submatrix\n * @param {number} endRow - last row index of the submatrix\n * @param {number} startColumn - first column index of the submatrix\n * @param {number} endColumn - last column index of the submatrix\n * @return {MatrixSubView}\n */\n subMatrixView(startRow, endRow, startColumn, endColumn) {\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\n }\n\n /**\n * Returns a view of the cross of the row indices and the column indices\n * @example\n * // resulting vector is [[2], [2]]\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\n * @param {Array} rowIndices\n * @param {Array} columnIndices\n * @return {MatrixSelectionView}\n */\n selectionView(rowIndices, columnIndices) {\n return new MatrixSelectionView(this, rowIndices, columnIndices);\n }\n\n\n /**\n * Calculates and returns the determinant of a matrix as a Number\n * @example\n * new Matrix([[1,2,3], [4,5,6]]).det()\n * @return {number}\n */\n det() {\n if (this.isSquare()) {\n var a, b, c, d;\n if (this.columns === 2) {\n // 2 x 2 matrix\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(1, 0);\n d = this.get(1, 1);\n\n return a * d - (b * c);\n } else if (this.columns === 3) {\n // 3 x 3 matrix\n var subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(0, 2);\n\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(this).determinant;\n }\n\n } else {\n throw Error('Determinant can only be calculated for a square matrix.');\n }\n }\n\n /**\n * Returns inverse of a matrix if it exists or the pseudoinverse\n * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)\n * @return {Matrix} the (pseudo)inverted matrix.\n */\n pseudoInverse(threshold) {\n if (threshold === undefined) threshold = Number.EPSILON;\n var svdSolution = new SvDecomposition(this, {autoTranspose: true});\n\n var U = svdSolution.leftSingularVectors;\n var V = svdSolution.rightSingularVectors;\n var s = svdSolution.diagonal;\n\n for (var i = 0; i < s.length; i++) {\n if (Math.abs(s[i]) > threshold) {\n s[i] = 1.0 / s[i];\n } else {\n s[i] = 0.0;\n }\n }\n\n // convert list to diagonal\n s = this.constructor[Symbol.species].diag(s);\n return V.mmul(s.mmul(U.transposeView()));\n }\n }\n\n Matrix.prototype.klass = 'Matrix';\n\n function compareNumbers(a, b) {\n return a - b;\n }\n\n /*\n Synonyms\n */\n\n Matrix.random = Matrix.rand;\n Matrix.diagonal = Matrix.diag;\n Matrix.prototype.diagonal = Matrix.prototype.diag;\n Matrix.identity = Matrix.eye;\n Matrix.prototype.negate = Matrix.prototype.neg;\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\n Matrix.prototype.determinant = Matrix.prototype.det;\n\n /*\n Add dynamically instance and static methods for mathematical operations\n */\n\n var inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var inplaceOperatorScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n`;\n\n var inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n`;\n\n var staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n`;\n\n var inplaceMethod = `\n(function %name%() {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%();\n})\n`;\n\n var inplaceMethodWithArgs = `\n(function %name%(%args%) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), %args%));\n }\n }\n return this;\n})\n`;\n\n var staticMethodWithArgs = `\n(function %name%(matrix, %args%) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(%args%);\n})\n`;\n\n\n var inplaceMethodWithOneArgScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), value));\n }\n }\n return this;\n})\n`;\n var inplaceMethodWithOneArgMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var inplaceMethodWithOneArg = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var staticMethodWithOneArg = staticMethodWithArgs;\n\n var operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n ];\n\n var i;\n var eval2 = eval;\n for (var operator of operators) {\n var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]}));\n var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]}));\n var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]}));\n var staticOp = eval2(fillTemplateFunction(staticOperator, {name: operator[1]}));\n for (i = 1; i < operator.length; i++) {\n Matrix.prototype[operator[i]] = inplaceOp;\n Matrix.prototype[operator[i] + 'S'] = inplaceOpS;\n Matrix.prototype[operator[i] + 'M'] = inplaceOpM;\n Matrix[operator[i]] = staticOp;\n }\n }\n\n var methods = [\n ['~', 'not']\n ];\n\n [\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n ].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n });\n\n for (var method of methods) {\n var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]}));\n var staticMeth = eval2(fillTemplateFunction(staticMethod, {name: method[1]}));\n for (i = 1; i < method.length; i++) {\n Matrix.prototype[method[i]] = inplaceMeth;\n Matrix[method[i]] = staticMeth;\n }\n }\n\n var methodsWithArgs = [\n ['Math.pow', 1, 'pow']\n ];\n\n for (var methodWithArg of methodsWithArgs) {\n var args = 'arg0';\n for (i = 1; i < methodWithArg[1]; i++) {\n args += `, arg${i}`;\n }\n if (methodWithArg[1] !== 1) {\n var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, {\n name: methodWithArg[2],\n method: methodWithArg[0],\n args: args\n }));\n var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args}));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\n Matrix[methodWithArg[i]] = staticMethWithArgs;\n }\n } else {\n var tmplVar = {\n name: methodWithArg[2],\n args: args,\n method: methodWithArg[0]\n };\n var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\n var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\n var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\n var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\n Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM;\n Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS;\n Matrix[methodWithArg[i]] = staticMethod2;\n }\n }\n }\n\n function fillTemplateFunction(template, values) {\n for (var value in values) {\n template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]);\n }\n return template;\n }\n\n return Matrix;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/abstractMatrix.js\n// module id = 28\n// module chunks = 0","import Matrix from '../matrix';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\nfunction LuDecomposition(matrix) {\n if (!(this instanceof LuDecomposition)) {\n return new LuDecomposition(matrix);\n }\n\n matrix = Matrix.checkMatrix(matrix);\n\n var lu = matrix.clone(),\n rows = lu.rows,\n columns = lu.columns,\n pivotVector = new Array(rows),\n pivotSign = 1,\n i, j, k, p, s, t, v,\n LUrowi, LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Array(rows);\n\n for (j = 0; j < columns; j++) {\n\n for (i = 0; i < rows; i++) {\n LUcolj[i] = lu[i][j];\n }\n\n for (i = 0; i < rows; i++) {\n LUrowi = lu[i];\n kmax = Math.min(i, j);\n s = 0;\n for (k = 0; k < kmax; k++) {\n s += LUrowi[k] * LUcolj[k];\n }\n LUrowi[j] = LUcolj[i] -= s;\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[p][k];\n lu[p][k] = lu[j][k];\n lu[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[j][j] !== 0) {\n for (i = j + 1; i < rows; i++) {\n lu[i][j] /= lu[j][j];\n }\n }\n }\n\n this.LU = lu;\n this.pivotVector = pivotVector;\n this.pivotSign = pivotSign;\n}\n\nLuDecomposition.prototype = {\n isSingular: function () {\n var data = this.LU,\n col = data.columns;\n for (var j = 0; j < col; j++) {\n if (data[j][j] === 0) {\n return true;\n }\n }\n return false;\n },\n get determinant() {\n var data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n var determinant = this.pivotSign, col = data.columns;\n for (var j = 0; j < col; j++) {\n determinant *= data[j][j];\n }\n return determinant;\n },\n get lowerTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i > j) {\n X[i][j] = data[i][j];\n } else if (i === j) {\n X[i][j] = 1;\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get upperTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i <= j) {\n X[i][j] = data[i][j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get pivotPermutationVector() {\n return this.pivotVector.slice();\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var lu = this.LU,\n rows = lu.rows;\n\n if (rows !== value.rows) {\n throw new Error('Invalid matrix dimensions');\n }\n if (this.isSingular()) {\n throw new Error('LU matrix is singular');\n }\n\n var count = value.columns;\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n var columns = lu.columns;\n var i, j, k;\n\n for (k = 0; k < columns; k++) {\n for (i = k + 1; i < columns; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= lu[k][k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n return X;\n }\n};\n\nexport default LuDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/dc/lu.js\n// module id = 29\n// module chunks = 0","export function hypotenuse(a, b) {\n var r;\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\n// For use in the decomposition algorithms. With big matrices, access time is\n// too long on elements from array subclass\n// todo check when it is fixed in v8\n// http://jsperf.com/access-and-write-array-subclass\nexport function getEmpty2DArray(rows, columns) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n }\n return array;\n}\n\nexport function getFilled2DArray(rows, columns, value) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n for (var j = 0; j < columns; j++) {\n array[i][j] = value;\n }\n }\n return array;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/dc/util.js\n// module id = 30\n// module chunks = 0","import LuDecomposition from './dc/lu';\nimport SvDecomposition from './dc/svd';\nimport {scale} from 'ml-array-utils';\nimport * as util from './util';\nimport MatrixTransposeView from './views/transpose';\nimport MatrixRowView from './views/row';\nimport MatrixSubView from './views/sub';\nimport MatrixSelectionView from './views/selection';\nimport MatrixColumnView from './views/column';\nimport MatrixFlipRowView from './views/flipRow';\nimport MatrixFlipColumnView from './views/flipColumn';\n\nexport default function AbstractMatrix(superCtor) {\n if (superCtor === undefined) superCtor = Object;\n\n /**\n * Real matrix\n * @class Matrix\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\n * 2D array containing the data or Matrix instance to clone\n * @param {number} [nColumns] - Number of columns of the new matrix\n */\n class Matrix extends superCtor {\n static get [Symbol.species]() {\n return this;\n }\n\n /**\n * Constructs a Matrix with the chosen dimensions from a 1D array\n * @param {number} newRows - Number of rows\n * @param {number} newColumns - Number of columns\n * @param {Array} newData - A 1D array containing data for the matrix\n * @return {Matrix} - The new matrix\n */\n static from1DArray(newRows, newColumns, newData) {\n var length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('Data length does not match given dimensions');\n }\n var newMatrix = new this(newRows, newColumns);\n for (var row = 0; row < newRows; row++) {\n for (var column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n /**\n * Creates a row vector, a matrix with only one row.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static rowVector(newData) {\n var vector = new this(1, newData.length);\n for (var i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates a column vector, a matrix with only one column.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static columnVector(newData) {\n var vector = new this(newData.length, 1);\n for (var i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static empty(rows, columns) {\n return new this(rows, columns);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to zero.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static zeros(rows, columns) {\n return this.empty(rows, columns).fill(0);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to one.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static ones(rows, columns) {\n return this.empty(rows, columns).fill(1);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be randomly set.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static rand(rows, columns, rng) {\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n matrix.set(i, j, rng());\n }\n }\n return matrix;\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be random integers.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {number} [maxValue=1000] - Maximum value\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static randInt(rows, columns, maxValue, rng) {\n if (maxValue === undefined) maxValue = 1000;\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = Math.floor(rng() * maxValue);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n /**\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\n * @param {number} rows - Number of rows\n * @param {number} [columns=rows] - Number of columns\n * @param {number} [value=1] - Value to fill the diagonal with\n * @return {Matrix} - The new identity matrix\n */\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n var min = Math.min(rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n /**\n * Creates a diagonal matrix based on the given array.\n * @param {Array} data - Array containing the data for the diagonal\n * @param {number} [rows] - Number of rows (Default: data.length)\n * @param {number} [columns] - Number of columns (Default: rows)\n * @return {Matrix} - The new diagonal matrix\n */\n static diag(data, rows, columns) {\n var l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n var min = Math.min(l, rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n /**\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Check that the provided value is a Matrix and tries to instantiate one if not\n * @param {*} value - The value to check\n * @return {Matrix}\n */\n static checkMatrix(value) {\n return Matrix.isMatrix(value) ? value : new this(value);\n }\n\n /**\n * Returns true if the argument is a Matrix, false otherwise\n * @param {*} value - The value to check\n * @return {boolean}\n */\n static isMatrix(value) {\n return (value != null) && (value.klass === 'Matrix');\n }\n\n /**\n * @prop {number} size - The number of elements in the matrix.\n */\n get size() {\n return this.rows * this.columns;\n }\n\n /**\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\n * @return {Matrix} this\n */\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n var ii = this.rows;\n var jj = this.columns;\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n /**\n * Returns a new 1D array filled row by row with the matrix values\n * @return {Array}\n */\n to1DArray() {\n var array = new Array(this.size);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n array[i * this.columns + j] = this.get(i, j);\n }\n }\n return array;\n }\n\n /**\n * Returns a 2D array containing a copy of the data\n * @return {Array}\n */\n to2DArray() {\n var copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n /**\n * @return {boolean} true if the matrix has one row\n */\n isRowVector() {\n return this.rows === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one column\n */\n isColumnVector() {\n return this.columns === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one row or one column\n */\n isVector() {\n return (this.rows === 1) || (this.columns === 1);\n }\n\n /**\n * @return {boolean} true if the matrix has the same number of rows and columns\n */\n isSquare() {\n return this.rows === this.columns;\n }\n\n /**\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\n */\n isSymmetric() {\n if (this.isSquare()) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j <= i; j++) {\n if (this.get(i, j) !== this.get(j, i)) {\n return false;\n }\n }\n }\n return true;\n }\n return false;\n }\n\n /**\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @param {number} value - The new value for the element\n * @return {Matrix} this\n */\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\n throw new Error('set method is unimplemented');\n }\n\n /**\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @return {number}\n */\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\n throw new Error('get method is unimplemented');\n }\n\n /**\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\n * rows of the matrix, and colRep times the number of columns of the matrix\n * @param {number} rowRep - Number of times the rows should be repeated\n * @param {number} colRep - Number of times the columns should be re\n * @return {Matrix}\n * @example\n * var matrix = new Matrix([[1,2]]);\n * matrix.repeat(2); // [[1,2],[1,2]]\n */\n repeat(rowRep, colRep) {\n rowRep = rowRep || 1;\n colRep = colRep || 1;\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\n for (var i = 0; i < rowRep; i++) {\n for (var j = 0; j < colRep; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n /**\n * Fills the matrix with a given value. All elements will be set to this value.\n * @param {number} value - New value\n * @return {Matrix} this\n */\n fill(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n /**\n * Negates the matrix. All elements will be multiplied by (-1)\n * @return {Matrix} this\n */\n neg() {\n return this.mulS(-1);\n }\n\n /**\n * Returns a new array from the given row index\n * @param {number} index - Row index\n * @return {Array}\n */\n getRow(index) {\n util.checkRowIndex(this, index);\n var row = new Array(this.columns);\n for (var i = 0; i < this.columns; i++) {\n row[i] = this.get(index, i);\n }\n return row;\n }\n\n /**\n * Returns a new row vector from the given row index\n * @param {number} index - Row index\n * @return {Matrix}\n */\n getRowVector(index) {\n return this.constructor.rowVector(this.getRow(index));\n }\n\n /**\n * Sets a row at the given index\n * @param {number} index - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setRow(index, array) {\n util.checkRowIndex(this, index);\n array = util.checkRowVector(this, array);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two rows\n * @param {number} row1 - First row index\n * @param {number} row2 - Second row index\n * @return {Matrix} this\n */\n swapRows(row1, row2) {\n util.checkRowIndex(this, row1);\n util.checkRowIndex(this, row2);\n for (var i = 0; i < this.columns; i++) {\n var temp = this.get(row1, i);\n this.set(row1, i, this.get(row2, i));\n this.set(row2, i, temp);\n }\n return this;\n }\n\n /**\n * Returns a new array from the given column index\n * @param {number} index - Column index\n * @return {Array}\n */\n getColumn(index) {\n util.checkColumnIndex(this, index);\n var column = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n column[i] = this.get(i, index);\n }\n return column;\n }\n\n /**\n * Returns a new column vector from the given column index\n * @param {number} index - Column index\n * @return {Matrix}\n */\n getColumnVector(index) {\n return this.constructor.columnVector(this.getColumn(index));\n }\n\n /**\n * Sets a column at the given index\n * @param {number} index - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setColumn(index, array) {\n util.checkColumnIndex(this, index);\n array = util.checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two columns\n * @param {number} column1 - First column index\n * @param {number} column2 - Second column index\n * @return {Matrix} this\n */\n swapColumns(column1, column2) {\n util.checkColumnIndex(this, column1);\n util.checkColumnIndex(this, column2);\n for (var i = 0; i < this.rows; i++) {\n var temp = this.get(i, column1);\n this.set(i, column1, this.get(i, column2));\n this.set(i, column2, temp);\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each row by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each column by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a row with a scalar\n * @param {number} index - Row index\n * @param {number} value\n * @return {Matrix} this\n */\n mulRow(index, value) {\n util.checkRowIndex(this, index);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n /**\n * Multiplies the values of a column with a scalar\n * @param {number} index - Column index\n * @param {number} value\n * @return {Matrix} this\n */\n mulColumn(index, value) {\n util.checkColumnIndex(this, index);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n /**\n * Returns the maximum value of the matrix\n * @return {number}\n */\n max() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value\n * @return {Array}\n */\n maxIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of the matrix\n * @return {number}\n */\n min() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value\n * @return {Array}\n */\n minIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n maxRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n maxRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n minRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n minRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n maxColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n maxColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n minColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n minColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns an array containing the diagonal values of the matrix\n * @return {Array}\n */\n diag() {\n var min = Math.min(this.rows, this.columns);\n var diag = new Array(min);\n for (var i = 0; i < min; i++) {\n diag[i] = this.get(i, i);\n }\n return diag;\n }\n\n /**\n * Returns the sum by the argument given, if no argument given,\n * it returns the sum of all elements of the matrix.\n * @param {string} by - sum by 'row' or 'column'.\n * @return {Matrix|number}\n */\n sum(by) {\n switch (by) {\n case 'row':\n return util.sumByRow(this);\n case 'column':\n return util.sumByColumn(this);\n default:\n return util.sumAll(this);\n }\n }\n\n /**\n * Returns the mean of all elements of the matrix\n * @return {number}\n */\n mean() {\n return this.sum() / this.size;\n }\n\n /**\n * Returns the product of all elements of the matrix\n * @return {number}\n */\n prod() {\n var prod = 1;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n prod *= this.get(i, j);\n }\n }\n return prod;\n }\n\n /**\n * Computes the cumulative sum of the matrix elements (in place, row by row)\n * @return {Matrix} this\n */\n cumulativeSum() {\n var sum = 0;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n sum += this.get(i, j);\n this.set(i, j, sum);\n }\n }\n return this;\n }\n\n /**\n * Computes the dot (scalar) product between the matrix and another\n * @param {Matrix} vector2 vector\n * @return {number}\n */\n dot(vector2) {\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n var vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n var dot = 0;\n for (var i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n /**\n * Returns the matrix product between this and other\n * @param {Matrix} other\n * @return {Matrix}\n */\n mmul(other) {\n other = this.constructor.checkMatrix(other);\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n var m = this.rows;\n var n = this.columns;\n var p = other.columns;\n\n var result = new this.constructor[Symbol.species](m, p);\n\n var Bcolj = new Array(n);\n for (var j = 0; j < p; j++) {\n for (var k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (var i = 0; i < m; i++) {\n var s = 0;\n for (k = 0; k < n; k++) {\n s += this.get(i, k) * Bcolj[k];\n }\n\n result.set(i, j, s);\n }\n }\n return result;\n }\n\n strassen2x2(other) {\n var result = new this.constructor[Symbol.species](2, 2);\n const a11 = this.get(0, 0);\n const b11 = other.get(0, 0);\n const a12 = this.get(0, 1);\n const b12 = other.get(0, 1);\n const a21 = this.get(1, 0);\n const b21 = other.get(1, 0);\n const a22 = this.get(1, 1);\n const b22 = other.get(1, 1);\n\n // Compute intermediate values.\n const m1 = (a11 + a22) * (b11 + b22);\n const m2 = (a21 + a22) * b11;\n const m3 = a11 * (b12 - b22);\n const m4 = a22 * (b21 - b11);\n const m5 = (a11 + a12) * b22;\n const m6 = (a21 - a11) * (b11 + b12);\n const m7 = (a12 - a22) * (b21 + b22);\n\n // Combine intermediate values into the output.\n const c00 = m1 + m4 - m5 + m7;\n const c01 = m3 + m5;\n const c10 = m2 + m4;\n const c11 = m1 - m2 + m3 + m6;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n return result;\n }\n\n strassen3x3(other) {\n var result = new this.constructor[Symbol.species](3, 3);\n\n const a00 = this.get(0, 0);\n const a01 = this.get(0, 1);\n const a02 = this.get(0, 2);\n const a10 = this.get(1, 0);\n const a11 = this.get(1, 1);\n const a12 = this.get(1, 2);\n const a20 = this.get(2, 0);\n const a21 = this.get(2, 1);\n const a22 = this.get(2, 2);\n\n const b00 = other.get(0, 0);\n const b01 = other.get(0, 1);\n const b02 = other.get(0, 2);\n const b10 = other.get(1, 0);\n const b11 = other.get(1, 1);\n const b12 = other.get(1, 2);\n const b20 = other.get(2, 0);\n const b21 = other.get(2, 1);\n const b22 = other.get(2, 2);\n\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\n const m2 = (a00 - a10) * (-b01 + b11);\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\n const m5 = (a10 + a11) * (-b00 + b01);\n const m6 = a00 * b00;\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\n const m8 = (-a00 + a20) * (b02 - b12);\n const m9 = (a20 + a21) * (-b00 + b02);\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\n const m13 = (a02 - a22) * (b11 - b21);\n const m14 = a02 * b20;\n const m15 = (a21 + a22) * (-b20 + b21);\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\n const m17 = (a02 - a12) * (b12 - b22);\n const m18 = (a11 + a12) * (-b20 + b22);\n const m19 = a01 * b10;\n const m20 = a12 * b21;\n const m21 = a10 * b02;\n const m22 = a20 * b01;\n const m23 = a22 * b22;\n\n const c00 = m6 + m14 + m19;\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\n const c11 = m2 + m4 + m5 + m6 + m20;\n const c12 = m14 + m16 + m17 + m18 + m21;\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\n const c21 = m12 + m13 + m14 + m15 + m22;\n const c22 = m6 + m7 + m8 + m9 + m23;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(0, 2, c02);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n result.set(1, 2, c12);\n result.set(2, 0, c20);\n result.set(2, 1, c21);\n result.set(2, 2, c22);\n return result;\n }\n\n /**\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\n * @param {Matrix} y\n * @return {Matrix}\n */\n mmulStrassen(y) {\n var x = this.clone();\n var r1 = x.rows;\n var c1 = x.columns;\n var r2 = y.rows;\n var c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\n }\n\n // Put a matrix into the top left of a matrix of zeros.\n // `rows` and `cols` are the dimensions of the output matrix.\n function embed(mat, rows, cols) {\n var r = mat.rows;\n var c = mat.columns;\n if ((r === rows) && (c === cols)) {\n return mat;\n } else {\n var resultat = Matrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\n }\n }\n\n\n // Make sure both matrices are the same size.\n // This is exclusively for simplicity:\n // this algorithm can be implemented with matrices of different sizes.\n\n var r = Math.max(r1, r2);\n var c = Math.max(c1, c2);\n x = embed(x, r, c);\n y = embed(y, r, c);\n\n // Our recursive multiplication function.\n function blockMult(a, b, rows, cols) {\n // For small matrices, resort to naive multiplication.\n if (rows <= 512 || cols <= 512) {\n return a.mmul(b); // a is equivalent to this\n }\n\n // Apply dynamic padding.\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\n a = embed(a, rows + 1, cols + 1);\n b = embed(b, rows + 1, cols + 1);\n } else if (rows % 2 === 1) {\n a = embed(a, rows + 1, cols);\n b = embed(b, rows + 1, cols);\n } else if (cols % 2 === 1) {\n a = embed(a, rows, cols + 1);\n b = embed(b, rows, cols + 1);\n }\n\n var halfRows = parseInt(a.rows / 2);\n var halfCols = parseInt(a.columns / 2);\n // Subdivide input matrices.\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\n\n // Combine intermediate values into the output.\n var c11 = Matrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n var c12 = Matrix.add(m3, m5);\n var c21 = Matrix.add(m2, m4);\n var c22 = Matrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n //Crop output to the desired size (undo dynamic padding).\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\n resultat = resultat.setSubMatrix(c11, 0, 0);\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\n }\n return blockMult(x, y, r, c);\n }\n\n /**\n * Returns a row-by-row scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The scaled matrix\n */\n scaleRows(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.rows; i++) {\n var scaled = scale(this.getRow(i), {min, max});\n newMatrix.setRow(i, scaled);\n }\n return newMatrix;\n }\n\n /**\n * Returns a new column-by-column scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The new scaled matrix\n * @example\n * var matrix = new Matrix([[1,2],[-1,0]]);\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\n */\n scaleColumns(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.columns; i++) {\n var scaled = scale(this.getColumn(i), {\n min: min,\n max: max\n });\n newMatrix.setColumn(i, scaled);\n }\n return newMatrix;\n }\n\n\n /**\n * Returns the Kronecker product (also known as tensor product) between this and other\n * See https://en.wikipedia.org/wiki/Kronecker_product\n * @param {Matrix} other\n * @return {Matrix}\n */\n kroneckerProduct(other) {\n other = this.constructor.checkMatrix(other);\n\n var m = this.rows;\n var n = this.columns;\n var p = other.rows;\n var q = other.columns;\n\n var result = new this.constructor[Symbol.species](m * p, n * q);\n for (var i = 0; i < m; i++) {\n for (var j = 0; j < n; j++) {\n for (var k = 0; k < p; k++) {\n for (var l = 0; l < q; l++) {\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Transposes the matrix and returns a new one containing the result\n * @return {Matrix}\n */\n transpose() {\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n /**\n * Sorts the rows (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortRows(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Sorts the columns (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortColumns(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Returns a subset of the matrix\n * @param {number} startRow - First row index\n * @param {number} endRow - Last row index\n * @param {number} startColumn - First column index\n * @param {number} endColumn - Last column index\n * @return {Matrix}\n */\n subMatrix(startRow, endRow, startColumn, endColumn) {\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\n for (var i = startRow; i <= endRow; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of row indices\n * @param {Array} indices - Array containing the row indices\n * @param {number} [startColumn = 0] - First column index\n * @param {number} [endColumn = this.columns-1] - Last column index\n * @return {Matrix}\n */\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n if (indices[i] < 0 || indices[i] >= this.rows) {\n throw new RangeError('Row index out of range: ' + indices[i]);\n }\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of column indices\n * @param {Array} indices - Array containing the column indices\n * @param {number} [startRow = 0] - First row index\n * @param {number} [endRow = this.rows-1] - Last row index\n * @return {Matrix}\n */\n subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startRow; j <= endRow; j++) {\n if (indices[i] < 0 || indices[i] >= this.columns) {\n throw new RangeError('Column index out of range: ' + indices[i]);\n }\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\n }\n }\n return newMatrix;\n }\n\n /**\n * Set a part of the matrix to the given sub-matrix\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\n * @param {number} startRow - The index of the first row to set\n * @param {number} startColumn - The index of the first column to set\n * @return {Matrix}\n */\n setSubMatrix(matrix, startRow, startColumn) {\n matrix = this.constructor.checkMatrix(matrix);\n var endRow = startRow + matrix.rows - 1;\n var endColumn = startColumn + matrix.columns - 1;\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n this[startRow + i][startColumn + j] = matrix.get(i, j);\n }\n }\n return this;\n }\n\n /**\n * Return a new matrix based on a selection of rows and columns\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\n * @return {Matrix} The new matrix\n */\n selection(rowIndices, columnIndices) {\n var indices = util.checkIndices(this, rowIndices, columnIndices);\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\n for (var i = 0; i < indices.row.length; i++) {\n var rowIndex = indices.row[i];\n for (var j = 0; j < indices.column.length; j++) {\n var columnIndex = indices.column[j];\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns the trace of the matrix (sum of the diagonal elements)\n * @return {number}\n */\n trace() {\n var min = Math.min(this.rows, this.columns);\n var trace = 0;\n for (var i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n /*\n Matrix views\n */\n\n /**\n * Returns a view of the transposition of the matrix\n * @return {MatrixTransposeView}\n */\n transposeView() {\n return new MatrixTransposeView(this);\n }\n\n /**\n * Returns a view of the row vector with the given index\n * @param {number} row - row index of the vector\n * @return {MatrixRowView}\n */\n rowView(row) {\n util.checkRowIndex(this, row);\n return new MatrixRowView(this, row);\n }\n\n /**\n * Returns a view of the column vector with the given index\n * @param {number} column - column index of the vector\n * @return {MatrixColumnView}\n */\n columnView(column) {\n util.checkColumnIndex(this, column);\n return new MatrixColumnView(this, column);\n }\n\n /**\n * Returns a view of the matrix flipped in the row axis\n * @return {MatrixFlipRowView}\n */\n flipRowView() {\n return new MatrixFlipRowView(this);\n }\n\n /**\n * Returns a view of the matrix flipped in the column axis\n * @return {MatrixFlipColumnView}\n */\n flipColumnView() {\n return new MatrixFlipColumnView(this);\n }\n\n /**\n * Returns a view of a submatrix giving the index boundaries\n * @param {number} startRow - first row index of the submatrix\n * @param {number} endRow - last row index of the submatrix\n * @param {number} startColumn - first column index of the submatrix\n * @param {number} endColumn - last column index of the submatrix\n * @return {MatrixSubView}\n */\n subMatrixView(startRow, endRow, startColumn, endColumn) {\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\n }\n\n /**\n * Returns a view of the cross of the row indices and the column indices\n * @example\n * // resulting vector is [[2], [2]]\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\n * @param {Array} rowIndices\n * @param {Array} columnIndices\n * @return {MatrixSelectionView}\n */\n selectionView(rowIndices, columnIndices) {\n return new MatrixSelectionView(this, rowIndices, columnIndices);\n }\n\n\n /**\n * Calculates and returns the determinant of a matrix as a Number\n * @example\n * new Matrix([[1,2,3], [4,5,6]]).det()\n * @return {number}\n */\n det() {\n if (this.isSquare()) {\n var a, b, c, d;\n if (this.columns === 2) {\n // 2 x 2 matrix\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(1, 0);\n d = this.get(1, 1);\n\n return a * d - (b * c);\n } else if (this.columns === 3) {\n // 3 x 3 matrix\n var subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(0, 2);\n\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(this).determinant;\n }\n\n } else {\n throw Error('Determinant can only be calculated for a square matrix.');\n }\n }\n\n /**\n * Returns inverse of a matrix if it exists or the pseudoinverse\n * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)\n * @return {Matrix} the (pseudo)inverted matrix.\n */\n pseudoInverse(threshold) {\n if (threshold === undefined) threshold = Number.EPSILON;\n var svdSolution = new SvDecomposition(this, {autoTranspose: true});\n\n var U = svdSolution.leftSingularVectors;\n var V = svdSolution.rightSingularVectors;\n var s = svdSolution.diagonal;\n\n for (var i = 0; i < s.length; i++) {\n if (Math.abs(s[i]) > threshold) {\n s[i] = 1.0 / s[i];\n } else {\n s[i] = 0.0;\n }\n }\n\n // convert list to diagonal\n s = this.constructor[Symbol.species].diag(s);\n return V.mmul(s.mmul(U.transposeView()));\n }\n }\n\n Matrix.prototype.klass = 'Matrix';\n\n function compareNumbers(a, b) {\n return a - b;\n }\n\n /*\n Synonyms\n */\n\n Matrix.random = Matrix.rand;\n Matrix.diagonal = Matrix.diag;\n Matrix.prototype.diagonal = Matrix.prototype.diag;\n Matrix.identity = Matrix.eye;\n Matrix.prototype.negate = Matrix.prototype.neg;\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\n Matrix.prototype.determinant = Matrix.prototype.det;\n\n /*\n Add dynamically instance and static methods for mathematical operations\n */\n\n var inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var inplaceOperatorScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n`;\n\n var inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n`;\n\n var staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n`;\n\n var inplaceMethod = `\n(function %name%() {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%();\n})\n`;\n\n var inplaceMethodWithArgs = `\n(function %name%(%args%) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), %args%));\n }\n }\n return this;\n})\n`;\n\n var staticMethodWithArgs = `\n(function %name%(matrix, %args%) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(%args%);\n})\n`;\n\n\n var inplaceMethodWithOneArgScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), value));\n }\n }\n return this;\n})\n`;\n var inplaceMethodWithOneArgMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var inplaceMethodWithOneArg = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var staticMethodWithOneArg = staticMethodWithArgs;\n\n var operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n ];\n\n var i;\n var eval2 = eval;\n for (var operator of operators) {\n var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]}));\n var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]}));\n var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]}));\n var staticOp = eval2(fillTemplateFunction(staticOperator, {name: operator[1]}));\n for (i = 1; i < operator.length; i++) {\n Matrix.prototype[operator[i]] = inplaceOp;\n Matrix.prototype[operator[i] + 'S'] = inplaceOpS;\n Matrix.prototype[operator[i] + 'M'] = inplaceOpM;\n Matrix[operator[i]] = staticOp;\n }\n }\n\n var methods = [\n ['~', 'not']\n ];\n\n [\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n ].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n });\n\n for (var method of methods) {\n var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]}));\n var staticMeth = eval2(fillTemplateFunction(staticMethod, {name: method[1]}));\n for (i = 1; i < method.length; i++) {\n Matrix.prototype[method[i]] = inplaceMeth;\n Matrix[method[i]] = staticMeth;\n }\n }\n\n var methodsWithArgs = [\n ['Math.pow', 1, 'pow']\n ];\n\n for (var methodWithArg of methodsWithArgs) {\n var args = 'arg0';\n for (i = 1; i < methodWithArg[1]; i++) {\n args += `, arg${i}`;\n }\n if (methodWithArg[1] !== 1) {\n var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, {\n name: methodWithArg[2],\n method: methodWithArg[0],\n args: args\n }));\n var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args}));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\n Matrix[methodWithArg[i]] = staticMethWithArgs;\n }\n } else {\n var tmplVar = {\n name: methodWithArg[2],\n args: args,\n method: methodWithArg[0]\n };\n var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\n var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\n var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\n var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\n Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM;\n Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS;\n Matrix[methodWithArg[i]] = staticMethod2;\n }\n }\n }\n\n function fillTemplateFunction(template, values) {\n for (var value in values) {\n template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]);\n }\n return template;\n }\n\n return Matrix;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/abstractMatrix.js\n// module id = 31\n// module chunks = 0","import Matrix from '../matrix';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\nfunction LuDecomposition(matrix) {\n if (!(this instanceof LuDecomposition)) {\n return new LuDecomposition(matrix);\n }\n\n matrix = Matrix.checkMatrix(matrix);\n\n var lu = matrix.clone(),\n rows = lu.rows,\n columns = lu.columns,\n pivotVector = new Array(rows),\n pivotSign = 1,\n i, j, k, p, s, t, v,\n LUrowi, LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Array(rows);\n\n for (j = 0; j < columns; j++) {\n\n for (i = 0; i < rows; i++) {\n LUcolj[i] = lu[i][j];\n }\n\n for (i = 0; i < rows; i++) {\n LUrowi = lu[i];\n kmax = Math.min(i, j);\n s = 0;\n for (k = 0; k < kmax; k++) {\n s += LUrowi[k] * LUcolj[k];\n }\n LUrowi[j] = LUcolj[i] -= s;\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[p][k];\n lu[p][k] = lu[j][k];\n lu[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[j][j] !== 0) {\n for (i = j + 1; i < rows; i++) {\n lu[i][j] /= lu[j][j];\n }\n }\n }\n\n this.LU = lu;\n this.pivotVector = pivotVector;\n this.pivotSign = pivotSign;\n}\n\nLuDecomposition.prototype = {\n isSingular: function () {\n var data = this.LU,\n col = data.columns;\n for (var j = 0; j < col; j++) {\n if (data[j][j] === 0) {\n return true;\n }\n }\n return false;\n },\n get determinant() {\n var data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n var determinant = this.pivotSign, col = data.columns;\n for (var j = 0; j < col; j++) {\n determinant *= data[j][j];\n }\n return determinant;\n },\n get lowerTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i > j) {\n X[i][j] = data[i][j];\n } else if (i === j) {\n X[i][j] = 1;\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get upperTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i <= j) {\n X[i][j] = data[i][j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get pivotPermutationVector() {\n return this.pivotVector.slice();\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var lu = this.LU,\n rows = lu.rows;\n\n if (rows !== value.rows) {\n throw new Error('Invalid matrix dimensions');\n }\n if (this.isSingular()) {\n throw new Error('LU matrix is singular');\n }\n\n var count = value.columns;\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n var columns = lu.columns;\n var i, j, k;\n\n for (k = 0; k < columns; k++) {\n for (i = k + 1; i < columns; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= lu[k][k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n return X;\n }\n};\n\nexport default LuDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/lu.js\n// module id = 32\n// module chunks = 0","export function hypotenuse(a, b) {\n var r;\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\n// For use in the decomposition algorithms. With big matrices, access time is\n// too long on elements from array subclass\n// todo check when it is fixed in v8\n// http://jsperf.com/access-and-write-array-subclass\nexport function getEmpty2DArray(rows, columns) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n }\n return array;\n}\n\nexport function getFilled2DArray(rows, columns, value) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n for (var j = 0; j < columns; j++) {\n array[i][j] = value;\n }\n }\n return array;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/util.js\n// module id = 33\n// module chunks = 0","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\n\nexport default class SimpleLinearRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = [y.intercept, y.slope];\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n toJSON() {\n return {\n name: 'simpleLinearRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(x) {\n return this.slope * x + this.intercept;\n }\n\n computeX(y) {\n return (y - this.intercept) / this.slope;\n }\n\n toString(precision) {\n let result = 'f(x) = ';\n if (this.slope !== 0) {\n const xFactor = maybeToPrecision(this.slope, precision);\n result += (xFactor === '1' ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n const absIntercept = Math.abs(this.intercept);\n const operator = absIntercept === this.intercept ? '+' : '-';\n result += ` ${operator} ${maybeToPrecision(absIntercept, precision)}`;\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'simpleLinearRegression') {\n throw new TypeError('not a SLR model');\n }\n return new SimpleLinearRegression(true, json);\n }\n}\n\nfunction regress(slr, x, y) {\n const n = x.length;\n let xSum = 0;\n let ySum = 0;\n\n let xSquared = 0;\n let xY = 0;\n\n for (let i = 0; i < n; i++) {\n xSum += x[i];\n ySum += y[i];\n xSquared += x[i] * x[i];\n xY += x[i] * y[i];\n }\n\n const numerator = (n * xY - xSum * ySum);\n slr.slope = numerator / (n * xSquared - xSum * xSum);\n slr.intercept = (1 / n) * ySum - slr.slope * (1 / n) * xSum;\n slr.coefficients = [slr.intercept, slr.slope];\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-simple-linear/src/index.js\n// module id = 34\n// module chunks = 0","import LuDecomposition from './dc/lu';\nimport SvDecomposition from './dc/svd';\nimport {scale} from 'ml-array-utils';\nimport * as util from './util';\nimport MatrixTransposeView from './views/transpose';\nimport MatrixRowView from './views/row';\nimport MatrixSubView from './views/sub';\nimport MatrixSelectionView from './views/selection';\nimport MatrixColumnView from './views/column';\nimport MatrixFlipRowView from './views/flipRow';\nimport MatrixFlipColumnView from './views/flipColumn';\n\nexport default function AbstractMatrix(superCtor) {\n if (superCtor === undefined) superCtor = Object;\n\n /**\n * Real matrix\n * @class Matrix\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\n * 2D array containing the data or Matrix instance to clone\n * @param {number} [nColumns] - Number of columns of the new matrix\n */\n class Matrix extends superCtor {\n static get [Symbol.species]() {\n return this;\n }\n\n /**\n * Constructs a Matrix with the chosen dimensions from a 1D array\n * @param {number} newRows - Number of rows\n * @param {number} newColumns - Number of columns\n * @param {Array} newData - A 1D array containing data for the matrix\n * @return {Matrix} - The new matrix\n */\n static from1DArray(newRows, newColumns, newData) {\n var length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('Data length does not match given dimensions');\n }\n var newMatrix = new this(newRows, newColumns);\n for (var row = 0; row < newRows; row++) {\n for (var column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n /**\n * Creates a row vector, a matrix with only one row.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static rowVector(newData) {\n var vector = new this(1, newData.length);\n for (var i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates a column vector, a matrix with only one column.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static columnVector(newData) {\n var vector = new this(newData.length, 1);\n for (var i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static empty(rows, columns) {\n return new this(rows, columns);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to zero.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static zeros(rows, columns) {\n return this.empty(rows, columns).fill(0);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to one.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static ones(rows, columns) {\n return this.empty(rows, columns).fill(1);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be randomly set.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static rand(rows, columns, rng) {\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n matrix.set(i, j, rng());\n }\n }\n return matrix;\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be random integers.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {number} [maxValue=1000] - Maximum value\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static randInt(rows, columns, maxValue, rng) {\n if (maxValue === undefined) maxValue = 1000;\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = Math.floor(rng() * maxValue);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n /**\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\n * @param {number} rows - Number of rows\n * @param {number} [columns=rows] - Number of columns\n * @param {number} [value=1] - Value to fill the diagonal with\n * @return {Matrix} - The new identity matrix\n */\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n var min = Math.min(rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n /**\n * Creates a diagonal matrix based on the given array.\n * @param {Array} data - Array containing the data for the diagonal\n * @param {number} [rows] - Number of rows (Default: data.length)\n * @param {number} [columns] - Number of columns (Default: rows)\n * @return {Matrix} - The new diagonal matrix\n */\n static diag(data, rows, columns) {\n var l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n var min = Math.min(l, rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n /**\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Check that the provided value is a Matrix and tries to instantiate one if not\n * @param {*} value - The value to check\n * @return {Matrix}\n */\n static checkMatrix(value) {\n return Matrix.isMatrix(value) ? value : new this(value);\n }\n\n /**\n * Returns true if the argument is a Matrix, false otherwise\n * @param {*} value - The value to check\n * @return {boolean}\n */\n static isMatrix(value) {\n return (value != null) && (value.klass === 'Matrix');\n }\n\n /**\n * @prop {number} size - The number of elements in the matrix.\n */\n get size() {\n return this.rows * this.columns;\n }\n\n /**\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\n * @return {Matrix} this\n */\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n var ii = this.rows;\n var jj = this.columns;\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n /**\n * Returns a new 1D array filled row by row with the matrix values\n * @return {Array}\n */\n to1DArray() {\n var array = new Array(this.size);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n array[i * this.columns + j] = this.get(i, j);\n }\n }\n return array;\n }\n\n /**\n * Returns a 2D array containing a copy of the data\n * @return {Array}\n */\n to2DArray() {\n var copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n /**\n * @return {boolean} true if the matrix has one row\n */\n isRowVector() {\n return this.rows === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one column\n */\n isColumnVector() {\n return this.columns === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one row or one column\n */\n isVector() {\n return (this.rows === 1) || (this.columns === 1);\n }\n\n /**\n * @return {boolean} true if the matrix has the same number of rows and columns\n */\n isSquare() {\n return this.rows === this.columns;\n }\n\n /**\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\n */\n isSymmetric() {\n if (this.isSquare()) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j <= i; j++) {\n if (this.get(i, j) !== this.get(j, i)) {\n return false;\n }\n }\n }\n return true;\n }\n return false;\n }\n\n /**\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @param {number} value - The new value for the element\n * @return {Matrix} this\n */\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\n throw new Error('set method is unimplemented');\n }\n\n /**\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @return {number}\n */\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\n throw new Error('get method is unimplemented');\n }\n\n /**\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\n * rows of the matrix, and colRep times the number of columns of the matrix\n * @param {number} rowRep - Number of times the rows should be repeated\n * @param {number} colRep - Number of times the columns should be re\n * @return {Matrix}\n * @example\n * var matrix = new Matrix([[1,2]]);\n * matrix.repeat(2); // [[1,2],[1,2]]\n */\n repeat(rowRep, colRep) {\n rowRep = rowRep || 1;\n colRep = colRep || 1;\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\n for (var i = 0; i < rowRep; i++) {\n for (var j = 0; j < colRep; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n /**\n * Fills the matrix with a given value. All elements will be set to this value.\n * @param {number} value - New value\n * @return {Matrix} this\n */\n fill(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n /**\n * Negates the matrix. All elements will be multiplied by (-1)\n * @return {Matrix} this\n */\n neg() {\n return this.mulS(-1);\n }\n\n /**\n * Returns a new array from the given row index\n * @param {number} index - Row index\n * @return {Array}\n */\n getRow(index) {\n util.checkRowIndex(this, index);\n var row = new Array(this.columns);\n for (var i = 0; i < this.columns; i++) {\n row[i] = this.get(index, i);\n }\n return row;\n }\n\n /**\n * Returns a new row vector from the given row index\n * @param {number} index - Row index\n * @return {Matrix}\n */\n getRowVector(index) {\n return this.constructor.rowVector(this.getRow(index));\n }\n\n /**\n * Sets a row at the given index\n * @param {number} index - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setRow(index, array) {\n util.checkRowIndex(this, index);\n array = util.checkRowVector(this, array);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two rows\n * @param {number} row1 - First row index\n * @param {number} row2 - Second row index\n * @return {Matrix} this\n */\n swapRows(row1, row2) {\n util.checkRowIndex(this, row1);\n util.checkRowIndex(this, row2);\n for (var i = 0; i < this.columns; i++) {\n var temp = this.get(row1, i);\n this.set(row1, i, this.get(row2, i));\n this.set(row2, i, temp);\n }\n return this;\n }\n\n /**\n * Returns a new array from the given column index\n * @param {number} index - Column index\n * @return {Array}\n */\n getColumn(index) {\n util.checkColumnIndex(this, index);\n var column = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n column[i] = this.get(i, index);\n }\n return column;\n }\n\n /**\n * Returns a new column vector from the given column index\n * @param {number} index - Column index\n * @return {Matrix}\n */\n getColumnVector(index) {\n return this.constructor.columnVector(this.getColumn(index));\n }\n\n /**\n * Sets a column at the given index\n * @param {number} index - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setColumn(index, array) {\n util.checkColumnIndex(this, index);\n array = util.checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two columns\n * @param {number} column1 - First column index\n * @param {number} column2 - Second column index\n * @return {Matrix} this\n */\n swapColumns(column1, column2) {\n util.checkColumnIndex(this, column1);\n util.checkColumnIndex(this, column2);\n for (var i = 0; i < this.rows; i++) {\n var temp = this.get(i, column1);\n this.set(i, column1, this.get(i, column2));\n this.set(i, column2, temp);\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each row by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each column by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a row with a scalar\n * @param {number} index - Row index\n * @param {number} value\n * @return {Matrix} this\n */\n mulRow(index, value) {\n util.checkRowIndex(this, index);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n /**\n * Multiplies the values of a column with a scalar\n * @param {number} index - Column index\n * @param {number} value\n * @return {Matrix} this\n */\n mulColumn(index, value) {\n util.checkColumnIndex(this, index);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n /**\n * Returns the maximum value of the matrix\n * @return {number}\n */\n max() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value\n * @return {Array}\n */\n maxIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of the matrix\n * @return {number}\n */\n min() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value\n * @return {Array}\n */\n minIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n maxRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n maxRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n minRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n minRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n maxColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n maxColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n minColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n minColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns an array containing the diagonal values of the matrix\n * @return {Array}\n */\n diag() {\n var min = Math.min(this.rows, this.columns);\n var diag = new Array(min);\n for (var i = 0; i < min; i++) {\n diag[i] = this.get(i, i);\n }\n return diag;\n }\n\n /**\n * Returns the sum by the argument given, if no argument given,\n * it returns the sum of all elements of the matrix.\n * @param {string} by - sum by 'row' or 'column'.\n * @return {Matrix|number}\n */\n sum(by) {\n switch (by) {\n case 'row':\n return util.sumByRow(this);\n case 'column':\n return util.sumByColumn(this);\n default:\n return util.sumAll(this);\n }\n }\n\n /**\n * Returns the mean of all elements of the matrix\n * @return {number}\n */\n mean() {\n return this.sum() / this.size;\n }\n\n /**\n * Returns the product of all elements of the matrix\n * @return {number}\n */\n prod() {\n var prod = 1;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n prod *= this.get(i, j);\n }\n }\n return prod;\n }\n\n /**\n * Computes the cumulative sum of the matrix elements (in place, row by row)\n * @return {Matrix} this\n */\n cumulativeSum() {\n var sum = 0;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n sum += this.get(i, j);\n this.set(i, j, sum);\n }\n }\n return this;\n }\n\n /**\n * Computes the dot (scalar) product between the matrix and another\n * @param {Matrix} vector2 vector\n * @return {number}\n */\n dot(vector2) {\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n var vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n var dot = 0;\n for (var i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n /**\n * Returns the matrix product between this and other\n * @param {Matrix} other\n * @return {Matrix}\n */\n mmul(other) {\n other = this.constructor.checkMatrix(other);\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n var m = this.rows;\n var n = this.columns;\n var p = other.columns;\n\n var result = new this.constructor[Symbol.species](m, p);\n\n var Bcolj = new Array(n);\n for (var j = 0; j < p; j++) {\n for (var k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (var i = 0; i < m; i++) {\n var s = 0;\n for (k = 0; k < n; k++) {\n s += this.get(i, k) * Bcolj[k];\n }\n\n result.set(i, j, s);\n }\n }\n return result;\n }\n\n strassen2x2(other) {\n var result = new this.constructor[Symbol.species](2, 2);\n const a11 = this.get(0, 0);\n const b11 = other.get(0, 0);\n const a12 = this.get(0, 1);\n const b12 = other.get(0, 1);\n const a21 = this.get(1, 0);\n const b21 = other.get(1, 0);\n const a22 = this.get(1, 1);\n const b22 = other.get(1, 1);\n\n // Compute intermediate values.\n const m1 = (a11 + a22) * (b11 + b22);\n const m2 = (a21 + a22) * b11;\n const m3 = a11 * (b12 - b22);\n const m4 = a22 * (b21 - b11);\n const m5 = (a11 + a12) * b22;\n const m6 = (a21 - a11) * (b11 + b12);\n const m7 = (a12 - a22) * (b21 + b22);\n\n // Combine intermediate values into the output.\n const c00 = m1 + m4 - m5 + m7;\n const c01 = m3 + m5;\n const c10 = m2 + m4;\n const c11 = m1 - m2 + m3 + m6;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n return result;\n }\n\n strassen3x3(other) {\n var result = new this.constructor[Symbol.species](3, 3);\n\n const a00 = this.get(0, 0);\n const a01 = this.get(0, 1);\n const a02 = this.get(0, 2);\n const a10 = this.get(1, 0);\n const a11 = this.get(1, 1);\n const a12 = this.get(1, 2);\n const a20 = this.get(2, 0);\n const a21 = this.get(2, 1);\n const a22 = this.get(2, 2);\n\n const b00 = other.get(0, 0);\n const b01 = other.get(0, 1);\n const b02 = other.get(0, 2);\n const b10 = other.get(1, 0);\n const b11 = other.get(1, 1);\n const b12 = other.get(1, 2);\n const b20 = other.get(2, 0);\n const b21 = other.get(2, 1);\n const b22 = other.get(2, 2);\n\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\n const m2 = (a00 - a10) * (-b01 + b11);\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\n const m5 = (a10 + a11) * (-b00 + b01);\n const m6 = a00 * b00;\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\n const m8 = (-a00 + a20) * (b02 - b12);\n const m9 = (a20 + a21) * (-b00 + b02);\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\n const m13 = (a02 - a22) * (b11 - b21);\n const m14 = a02 * b20;\n const m15 = (a21 + a22) * (-b20 + b21);\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\n const m17 = (a02 - a12) * (b12 - b22);\n const m18 = (a11 + a12) * (-b20 + b22);\n const m19 = a01 * b10;\n const m20 = a12 * b21;\n const m21 = a10 * b02;\n const m22 = a20 * b01;\n const m23 = a22 * b22;\n\n const c00 = m6 + m14 + m19;\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\n const c11 = m2 + m4 + m5 + m6 + m20;\n const c12 = m14 + m16 + m17 + m18 + m21;\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\n const c21 = m12 + m13 + m14 + m15 + m22;\n const c22 = m6 + m7 + m8 + m9 + m23;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(0, 2, c02);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n result.set(1, 2, c12);\n result.set(2, 0, c20);\n result.set(2, 1, c21);\n result.set(2, 2, c22);\n return result;\n }\n\n /**\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\n * @param {Matrix} y\n * @return {Matrix}\n */\n mmulStrassen(y) {\n var x = this.clone();\n var r1 = x.rows;\n var c1 = x.columns;\n var r2 = y.rows;\n var c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\n }\n\n // Put a matrix into the top left of a matrix of zeros.\n // `rows` and `cols` are the dimensions of the output matrix.\n function embed(mat, rows, cols) {\n var r = mat.rows;\n var c = mat.columns;\n if ((r === rows) && (c === cols)) {\n return mat;\n } else {\n var resultat = Matrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\n }\n }\n\n\n // Make sure both matrices are the same size.\n // This is exclusively for simplicity:\n // this algorithm can be implemented with matrices of different sizes.\n\n var r = Math.max(r1, r2);\n var c = Math.max(c1, c2);\n x = embed(x, r, c);\n y = embed(y, r, c);\n\n // Our recursive multiplication function.\n function blockMult(a, b, rows, cols) {\n // For small matrices, resort to naive multiplication.\n if (rows <= 512 || cols <= 512) {\n return a.mmul(b); // a is equivalent to this\n }\n\n // Apply dynamic padding.\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\n a = embed(a, rows + 1, cols + 1);\n b = embed(b, rows + 1, cols + 1);\n } else if (rows % 2 === 1) {\n a = embed(a, rows + 1, cols);\n b = embed(b, rows + 1, cols);\n } else if (cols % 2 === 1) {\n a = embed(a, rows, cols + 1);\n b = embed(b, rows, cols + 1);\n }\n\n var halfRows = parseInt(a.rows / 2);\n var halfCols = parseInt(a.columns / 2);\n // Subdivide input matrices.\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\n\n // Combine intermediate values into the output.\n var c11 = Matrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n var c12 = Matrix.add(m3, m5);\n var c21 = Matrix.add(m2, m4);\n var c22 = Matrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n //Crop output to the desired size (undo dynamic padding).\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\n resultat = resultat.setSubMatrix(c11, 0, 0);\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\n }\n return blockMult(x, y, r, c);\n }\n\n /**\n * Returns a row-by-row scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The scaled matrix\n */\n scaleRows(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.rows; i++) {\n var scaled = scale(this.getRow(i), {min, max});\n newMatrix.setRow(i, scaled);\n }\n return newMatrix;\n }\n\n /**\n * Returns a new column-by-column scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The new scaled matrix\n * @example\n * var matrix = new Matrix([[1,2],[-1,0]]);\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\n */\n scaleColumns(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.columns; i++) {\n var scaled = scale(this.getColumn(i), {\n min: min,\n max: max\n });\n newMatrix.setColumn(i, scaled);\n }\n return newMatrix;\n }\n\n\n /**\n * Returns the Kronecker product (also known as tensor product) between this and other\n * See https://en.wikipedia.org/wiki/Kronecker_product\n * @param {Matrix} other\n * @return {Matrix}\n */\n kroneckerProduct(other) {\n other = this.constructor.checkMatrix(other);\n\n var m = this.rows;\n var n = this.columns;\n var p = other.rows;\n var q = other.columns;\n\n var result = new this.constructor[Symbol.species](m * p, n * q);\n for (var i = 0; i < m; i++) {\n for (var j = 0; j < n; j++) {\n for (var k = 0; k < p; k++) {\n for (var l = 0; l < q; l++) {\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Transposes the matrix and returns a new one containing the result\n * @return {Matrix}\n */\n transpose() {\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n /**\n * Sorts the rows (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortRows(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Sorts the columns (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortColumns(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Returns a subset of the matrix\n * @param {number} startRow - First row index\n * @param {number} endRow - Last row index\n * @param {number} startColumn - First column index\n * @param {number} endColumn - Last column index\n * @return {Matrix}\n */\n subMatrix(startRow, endRow, startColumn, endColumn) {\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\n for (var i = startRow; i <= endRow; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of row indices\n * @param {Array} indices - Array containing the row indices\n * @param {number} [startColumn = 0] - First column index\n * @param {number} [endColumn = this.columns-1] - Last column index\n * @return {Matrix}\n */\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n if (indices[i] < 0 || indices[i] >= this.rows) {\n throw new RangeError('Row index out of range: ' + indices[i]);\n }\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of column indices\n * @param {Array} indices - Array containing the column indices\n * @param {number} [startRow = 0] - First row index\n * @param {number} [endRow = this.rows-1] - Last row index\n * @return {Matrix}\n */\n subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startRow; j <= endRow; j++) {\n if (indices[i] < 0 || indices[i] >= this.columns) {\n throw new RangeError('Column index out of range: ' + indices[i]);\n }\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\n }\n }\n return newMatrix;\n }\n\n /**\n * Set a part of the matrix to the given sub-matrix\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\n * @param {number} startRow - The index of the first row to set\n * @param {number} startColumn - The index of the first column to set\n * @return {Matrix}\n */\n setSubMatrix(matrix, startRow, startColumn) {\n matrix = this.constructor.checkMatrix(matrix);\n var endRow = startRow + matrix.rows - 1;\n var endColumn = startColumn + matrix.columns - 1;\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n this[startRow + i][startColumn + j] = matrix.get(i, j);\n }\n }\n return this;\n }\n\n /**\n * Return a new matrix based on a selection of rows and columns\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\n * @return {Matrix} The new matrix\n */\n selection(rowIndices, columnIndices) {\n var indices = util.checkIndices(this, rowIndices, columnIndices);\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\n for (var i = 0; i < indices.row.length; i++) {\n var rowIndex = indices.row[i];\n for (var j = 0; j < indices.column.length; j++) {\n var columnIndex = indices.column[j];\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns the trace of the matrix (sum of the diagonal elements)\n * @return {number}\n */\n trace() {\n var min = Math.min(this.rows, this.columns);\n var trace = 0;\n for (var i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n /*\n Matrix views\n */\n\n /**\n * Returns a view of the transposition of the matrix\n * @return {MatrixTransposeView}\n */\n transposeView() {\n return new MatrixTransposeView(this);\n }\n\n /**\n * Returns a view of the row vector with the given index\n * @param {number} row - row index of the vector\n * @return {MatrixRowView}\n */\n rowView(row) {\n util.checkRowIndex(this, row);\n return new MatrixRowView(this, row);\n }\n\n /**\n * Returns a view of the column vector with the given index\n * @param {number} column - column index of the vector\n * @return {MatrixColumnView}\n */\n columnView(column) {\n util.checkColumnIndex(this, column);\n return new MatrixColumnView(this, column);\n }\n\n /**\n * Returns a view of the matrix flipped in the row axis\n * @return {MatrixFlipRowView}\n */\n flipRowView() {\n return new MatrixFlipRowView(this);\n }\n\n /**\n * Returns a view of the matrix flipped in the column axis\n * @return {MatrixFlipColumnView}\n */\n flipColumnView() {\n return new MatrixFlipColumnView(this);\n }\n\n /**\n * Returns a view of a submatrix giving the index boundaries\n * @param {number} startRow - first row index of the submatrix\n * @param {number} endRow - last row index of the submatrix\n * @param {number} startColumn - first column index of the submatrix\n * @param {number} endColumn - last column index of the submatrix\n * @return {MatrixSubView}\n */\n subMatrixView(startRow, endRow, startColumn, endColumn) {\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\n }\n\n /**\n * Returns a view of the cross of the row indices and the column indices\n * @example\n * // resulting vector is [[2], [2]]\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\n * @param {Array} rowIndices\n * @param {Array} columnIndices\n * @return {MatrixSelectionView}\n */\n selectionView(rowIndices, columnIndices) {\n return new MatrixSelectionView(this, rowIndices, columnIndices);\n }\n\n\n /**\n * Calculates and returns the determinant of a matrix as a Number\n * @example\n * new Matrix([[1,2,3], [4,5,6]]).det()\n * @return {number}\n */\n det() {\n if (this.isSquare()) {\n var a, b, c, d;\n if (this.columns === 2) {\n // 2 x 2 matrix\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(1, 0);\n d = this.get(1, 1);\n\n return a * d - (b * c);\n } else if (this.columns === 3) {\n // 3 x 3 matrix\n var subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(0, 2);\n\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(this).determinant;\n }\n\n } else {\n throw Error('Determinant can only be calculated for a square matrix.');\n }\n }\n\n /**\n * Returns inverse of a matrix if it exists or the pseudoinverse\n * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)\n * @return {Matrix} the (pseudo)inverted matrix.\n */\n pseudoInverse(threshold) {\n if (threshold === undefined) threshold = Number.EPSILON;\n var svdSolution = new SvDecomposition(this, {autoTranspose: true});\n\n var U = svdSolution.leftSingularVectors;\n var V = svdSolution.rightSingularVectors;\n var s = svdSolution.diagonal;\n\n for (var i = 0; i < s.length; i++) {\n if (Math.abs(s[i]) > threshold) {\n s[i] = 1.0 / s[i];\n } else {\n s[i] = 0.0;\n }\n }\n\n // convert list to diagonal\n s = this.constructor[Symbol.species].diag(s);\n return V.mmul(s.mmul(U.transposeView()));\n }\n }\n\n Matrix.prototype.klass = 'Matrix';\n\n function compareNumbers(a, b) {\n return a - b;\n }\n\n /*\n Synonyms\n */\n\n Matrix.random = Matrix.rand;\n Matrix.diagonal = Matrix.diag;\n Matrix.prototype.diagonal = Matrix.prototype.diag;\n Matrix.identity = Matrix.eye;\n Matrix.prototype.negate = Matrix.prototype.neg;\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\n Matrix.prototype.determinant = Matrix.prototype.det;\n\n /*\n Add dynamically instance and static methods for mathematical operations\n */\n\n var inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var inplaceOperatorScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n`;\n\n var inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n`;\n\n var staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n`;\n\n var inplaceMethod = `\n(function %name%() {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%();\n})\n`;\n\n var inplaceMethodWithArgs = `\n(function %name%(%args%) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), %args%));\n }\n }\n return this;\n})\n`;\n\n var staticMethodWithArgs = `\n(function %name%(matrix, %args%) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(%args%);\n})\n`;\n\n\n var inplaceMethodWithOneArgScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), value));\n }\n }\n return this;\n})\n`;\n var inplaceMethodWithOneArgMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var inplaceMethodWithOneArg = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var staticMethodWithOneArg = staticMethodWithArgs;\n\n var operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n ];\n\n var i;\n var eval2 = eval;\n for (var operator of operators) {\n var inplaceOp = eval2(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]}));\n var inplaceOpS = eval2(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]}));\n var inplaceOpM = eval2(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]}));\n var staticOp = eval2(fillTemplateFunction(staticOperator, {name: operator[1]}));\n for (i = 1; i < operator.length; i++) {\n Matrix.prototype[operator[i]] = inplaceOp;\n Matrix.prototype[operator[i] + 'S'] = inplaceOpS;\n Matrix.prototype[operator[i] + 'M'] = inplaceOpM;\n Matrix[operator[i]] = staticOp;\n }\n }\n\n var methods = [\n ['~', 'not']\n ];\n\n [\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n ].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n });\n\n for (var method of methods) {\n var inplaceMeth = eval2(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]}));\n var staticMeth = eval2(fillTemplateFunction(staticMethod, {name: method[1]}));\n for (i = 1; i < method.length; i++) {\n Matrix.prototype[method[i]] = inplaceMeth;\n Matrix[method[i]] = staticMeth;\n }\n }\n\n var methodsWithArgs = [\n ['Math.pow', 1, 'pow']\n ];\n\n for (var methodWithArg of methodsWithArgs) {\n var args = 'arg0';\n for (i = 1; i < methodWithArg[1]; i++) {\n args += `, arg${i}`;\n }\n if (methodWithArg[1] !== 1) {\n var inplaceMethWithArgs = eval2(fillTemplateFunction(inplaceMethodWithArgs, {\n name: methodWithArg[2],\n method: methodWithArg[0],\n args: args\n }));\n var staticMethWithArgs = eval2(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args}));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\n Matrix[methodWithArg[i]] = staticMethWithArgs;\n }\n } else {\n var tmplVar = {\n name: methodWithArg[2],\n args: args,\n method: methodWithArg[0]\n };\n var inplaceMethod2 = eval2(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\n var inplaceMethodS = eval2(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\n var inplaceMethodM = eval2(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\n var staticMethod2 = eval2(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\n Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM;\n Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS;\n Matrix[methodWithArg[i]] = staticMethod2;\n }\n }\n }\n\n function fillTemplateFunction(template, values) {\n for (var value in values) {\n template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]);\n }\n return template;\n }\n\n return Matrix;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/abstractMatrix.js\n// module id = 35\n// module chunks = 0","import Matrix from '../matrix';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\nfunction LuDecomposition(matrix) {\n if (!(this instanceof LuDecomposition)) {\n return new LuDecomposition(matrix);\n }\n\n matrix = Matrix.checkMatrix(matrix);\n\n var lu = matrix.clone(),\n rows = lu.rows,\n columns = lu.columns,\n pivotVector = new Array(rows),\n pivotSign = 1,\n i, j, k, p, s, t, v,\n LUrowi, LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Array(rows);\n\n for (j = 0; j < columns; j++) {\n\n for (i = 0; i < rows; i++) {\n LUcolj[i] = lu[i][j];\n }\n\n for (i = 0; i < rows; i++) {\n LUrowi = lu[i];\n kmax = Math.min(i, j);\n s = 0;\n for (k = 0; k < kmax; k++) {\n s += LUrowi[k] * LUcolj[k];\n }\n LUrowi[j] = LUcolj[i] -= s;\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[p][k];\n lu[p][k] = lu[j][k];\n lu[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[j][j] !== 0) {\n for (i = j + 1; i < rows; i++) {\n lu[i][j] /= lu[j][j];\n }\n }\n }\n\n this.LU = lu;\n this.pivotVector = pivotVector;\n this.pivotSign = pivotSign;\n}\n\nLuDecomposition.prototype = {\n isSingular: function () {\n var data = this.LU,\n col = data.columns;\n for (var j = 0; j < col; j++) {\n if (data[j][j] === 0) {\n return true;\n }\n }\n return false;\n },\n get determinant() {\n var data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n var determinant = this.pivotSign, col = data.columns;\n for (var j = 0; j < col; j++) {\n determinant *= data[j][j];\n }\n return determinant;\n },\n get lowerTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i > j) {\n X[i][j] = data[i][j];\n } else if (i === j) {\n X[i][j] = 1;\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get upperTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i <= j) {\n X[i][j] = data[i][j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get pivotPermutationVector() {\n return this.pivotVector.slice();\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var lu = this.LU,\n rows = lu.rows;\n\n if (rows !== value.rows) {\n throw new Error('Invalid matrix dimensions');\n }\n if (this.isSingular()) {\n throw new Error('LU matrix is singular');\n }\n\n var count = value.columns;\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n var columns = lu.columns;\n var i, j, k;\n\n for (k = 0; k < columns; k++) {\n for (i = k + 1; i < columns; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= lu[k][k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n return X;\n }\n};\n\nexport default LuDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/dc/lu.js\n// module id = 36\n// module chunks = 0","export function hypotenuse(a, b) {\n var r;\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\n// For use in the decomposition algorithms. With big matrices, access time is\n// too long on elements from array subclass\n// todo check when it is fixed in v8\n// http://jsperf.com/access-and-write-array-subclass\nexport function getEmpty2DArray(rows, columns) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n }\n return array;\n}\n\nexport function getFilled2DArray(rows, columns, value) {\n var array = new Array(rows);\n for (var i = 0; i < rows; i++) {\n array[i] = new Array(columns);\n for (var j = 0; j < columns; j++) {\n array[i][j] = value;\n }\n }\n return array;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/dc/util.js\n// module id = 37\n// module chunks = 0","'use strict';\n\nclass BaseRegression {\n predict(x) {\n var y2;\n if (Array.isArray(x)) {\n y2 = new Array(x.length);\n for (var i = 0; i < x.length; i++) {\n y2[i] = this._predict(x[i]);\n }\n } else if (Number.isFinite(x)) {\n y2 = this._predict(x);\n } else {\n throw new TypeError('x must be a number or array');\n }\n return y2;\n }\n\n _predict() {\n throw new Error('_compute not 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 modelQuality(x, y) {\n let n = x.length;\n var y2 = new Array(n);\n for (let i = 0; i < n; i++) {\n y2[i] = this._predict(x[i]);\n }\n var xSum = 0;\n var ySum = 0;\n var chi2 = 0;\n var rmsd = 0;\n var xSquared = 0;\n var ySquared = 0;\n var xY = 0;\n\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 var r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));\n\n return {\n r: r,\n r2: r * r,\n chi2: chi2,\n rmsd: rmsd * rmsd / n\n };\n }\n\n}\n\nmodule.exports = BaseRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/base-regression.js\n// module id = 38\n// module chunks = 0","module.exports = function(haystack, needle, comparator, low, high) {\n var mid, cmp;\n\n if(low === undefined)\n low = 0;\n\n else {\n low = low|0;\n if(low < 0 || low >= haystack.length)\n throw new RangeError(\"invalid lower bound\");\n }\n\n if(high === undefined)\n high = haystack.length - 1;\n\n else {\n high = high|0;\n if(high < low || high >= haystack.length)\n throw new RangeError(\"invalid upper bound\");\n }\n\n while(low <= high) {\n /* Note that \"(low + high) >>> 1\" may overflow, and results in a typecast\n * to double (which gives the wrong results). */\n mid = low + (high - low >> 1);\n cmp = +comparator(haystack[mid], needle, mid, haystack);\n\n /* Too low. */\n if(cmp < 0.0)\n low = mid + 1;\n\n /* Too high. */\n else if(cmp > 0.0)\n high = mid - 1;\n\n /* Key found. */\n else\n return mid;\n }\n\n /* Key not found. */\n return ~low;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/binary-search/index.js\n// module id = 39\n// module chunks = 0","'use strict';\n\n\n/**\n * Computes a distance/similarity matrix given an array of data and a distance/similarity function.\n * @param {Array} data An array of data\n * @param {function} distanceFn A function that accepts two arguments and computes a distance/similarity between them\n * @return {Array} The similarity matrix. The similarity matrix is square and has a size equal to the length of\n * the data array\n */\nfunction distanceMatrix(data, distanceFn) {\n const length = data.length;\n let result = Array.from({length}).map(() => Array.from({length}));\n\n // Compute upper distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = 0; j <= i; j++) {\n result[i][j] = distanceFn(data[i], data[j]);\n }\n }\n\n // Copy to lower distance matrix\n for (let i = 0; i < length; i++) {\n for (let j = i + 1; j < length; j++) {\n result[i][j] = result[j][i];\n }\n }\n\n return result;\n}\n\nmodule.exports = distanceMatrix;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance-matrix/src/index.js\n// module id = 40\n// module chunks = 0","'use strict';\n\nexports.distance = require('./distances');\nexports.similarity = require('./similarities');\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/index.js\n// module id = 41\n// module chunks = 0","'use strict';\n\nconst newArray = require('new-array');\n\nconst primeFinder = require('./primeFinder');\nconst nextPrime = primeFinder.nextPrime;\nconst largestPrime = primeFinder.largestPrime;\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nclass HashTable {\n constructor(options = {}) {\n if (options instanceof HashTable) {\n this.table = options.table.slice();\n this.values = options.values.slice();\n this.state = options.state.slice();\n this.minLoadFactor = options.minLoadFactor;\n this.maxLoadFactor = options.maxLoadFactor;\n this.distinct = options.distinct;\n this.freeEntries = options.freeEntries;\n this.lowWaterMark = options.lowWaterMark;\n this.highWaterMark = options.maxLoadFactor;\n return;\n }\n\n const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`);\n }\n\n const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor;\n const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor;\n if (minLoadFactor < 0 || minLoadFactor >= 1) {\n throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`);\n }\n if (maxLoadFactor <= 0 || maxLoadFactor >= 1) {\n throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`);\n }\n if (minLoadFactor >= maxLoadFactor) {\n throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`);\n }\n\n let capacity = initialCapacity;\n // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to\n // avoid the need to rehash before this capacity is reached.\n // actualCapacity * maxLoadFactor >= capacity\n capacity = (capacity / maxLoadFactor) | 0;\n capacity = nextPrime(capacity);\n if (capacity === 0) capacity = 1;\n\n this.table = newArray(capacity, 0);\n this.values = newArray(capacity, 0);\n this.state = newArray(capacity, 0);\n\n this.minLoadFactor = minLoadFactor;\n if (capacity === largestPrime) {\n this.maxLoadFactor = 1;\n } else {\n this.maxLoadFactor = maxLoadFactor;\n }\n\n this.distinct = 0;\n this.freeEntries = capacity;\n\n this.lowWaterMark = 0;\n this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor);\n }\n\n clone() {\n return new HashTable(this);\n }\n\n get size() {\n return this.distinct;\n }\n\n get(key) {\n const i = this.indexOfKey(key);\n if (i < 0) return 0;\n return this.values[i];\n }\n\n set(key, value) {\n let i = this.indexOfInsertion(key);\n if (i < 0) {\n i = -i - 1;\n this.values[i] = value;\n return false;\n }\n\n if (this.distinct > this.highWaterMark) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n return this.set(key, value);\n }\n\n this.table[i] = key;\n this.values[i] = value;\n if (this.state[i] === FREE) this.freeEntries--;\n this.state[i] = FULL;\n this.distinct++;\n\n if (this.freeEntries < 1) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n\n return true;\n }\n \n remove(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = REMOVED;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n delete(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = FREE;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n maybeShrinkCapacity() {\n if (this.distinct < this.lowWaterMark) {\n const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n }\n\n containsKey(key) {\n return this.indexOfKey(key) >= 0;\n }\n\n indexOfKey(key) {\n const table = this.table;\n const state = this.state;\n const length = this.table.length;\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === FREE) return -1;\n return i;\n }\n\n containsValue(value) {\n return this.indexOfValue(value) >= 0;\n }\n\n indexOfValue(value) {\n const values = this.values;\n const state = this.state;\n\n for (var i = 0; i < state.length; i++) {\n if (state[i] === FULL && values[i] === value) {\n return i;\n }\n }\n\n return -1;\n }\n\n indexOfInsertion(key) {\n const table = this.table;\n const state = this.state;\n const length = table.length;\n\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] === FULL && table[i] !== key) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === REMOVED) {\n const j = i;\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n if (state[i] === FREE) i = j;\n }\n\n if (state[i] === FULL) {\n return -i - 1;\n }\n\n return i;\n }\n\n ensureCapacity(minCapacity) {\n if (this.table.length < minCapacity) {\n const newCapacity = nextPrime(minCapacity);\n this.rehash(newCapacity);\n }\n }\n\n rehash(newCapacity) {\n const oldCapacity = this.table.length;\n\n if (newCapacity <= this.distinct) throw new Error('Unexpected');\n\n const oldTable = this.table;\n const oldValues = this.values;\n const oldState = this.state;\n\n const newTable = newArray(newCapacity, 0);\n const newValues = newArray(newCapacity, 0);\n const newState = newArray(newCapacity, 0);\n\n this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor);\n this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor);\n\n this.table = newTable;\n this.values = newValues;\n this.state = newState;\n this.freeEntries = newCapacity - this.distinct;\n\n for (var i = 0; i < oldCapacity; i++) {\n if (oldState[i] === FULL) {\n var element = oldTable[i];\n var index = this.indexOfInsertion(element);\n newTable[index] = element;\n newValues[index] = oldValues[i];\n newState[index] = FULL;\n }\n }\n }\n\n forEachKey(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i])) return false;\n }\n }\n return true;\n }\n\n forEachValue(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.values[i])) return false;\n }\n }\n return true;\n }\n\n forEachPair(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i], this.values[i])) return false;\n }\n }\n return true;\n }\n}\n\nmodule.exports = HashTable;\n\nfunction chooseLowWaterMark(capacity, minLoad) {\n return (capacity * minLoad) | 0;\n}\n\nfunction chooseHighWaterMark(capacity, maxLoad) {\n return Math.min(capacity - 2, (capacity * maxLoad) | 0);\n}\n\nfunction chooseGrowCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (3 * minLoad + maxLoad)) | 0));\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (minLoad + 3 * maxLoad)) | 0));\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hash-table/src/HashTable.js\n// module id = 42\n// module chunks = 0","'use strict';\n\nvar extend = require('extend');\n\nvar defaultOptions = {\n size: 1,\n value: 0\n};\n\n/**\n * Case when the entry is an array\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction arrayCase(data, options) {\n var len = data.length;\n if (typeof options.size === 'number')\n options.size = [options.size, options.size];\n\n var cond = len + options.size[0] + options.size[1];\n\n var output;\n if (options.output) {\n if (options.output.length !== cond)\n throw new RangeError('Wrong output size');\n output = options.output;\n }\n else\n output = new Array(cond);\n\n var i;\n\n // circular option\n if (options.value === 'circular') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[((len - (options.size[0] % len)) + i) % len];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[(i - options.size[0]) % len];\n }\n }\n\n // replicate option\n else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[0];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[len - 1];\n }\n }\n\n // symmetric option\n else if (options.value === 'symmetric') {\n if ((options.size[0] > len) || (options.size[1] > len))\n throw new RangeError('expanded value should not be bigger than the data length');\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[options.size[0] - 1 - i];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[2*len + options.size[0] - i - 1];\n }\n }\n\n // default option\n else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = options.value;\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = options.value;\n }\n }\n\n return output;\n}\n\n/**\n * Case when the entry is a matrix\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction matrixCase(data, options) {\n var row = data.length;\n var col = data[0].length;\n if (options.size[0] === undefined)\n options.size = [options.size, options.size, options.size, options.size];\n throw new Error('matrix not supported yet, sorry');\n}\n\n/**\n * Pads and array\n * @param {Array } data\n * @param {object} options\n */\nfunction padArray (data, options) {\n options = extend({}, defaultOptions, options);\n\n if (Array.isArray(data)) {\n if (Array.isArray(data[0]))\n return matrixCase(data, options);\n else\n return arrayCase(data, options);\n }\n else\n throw new TypeError('data should be an array');\n}\n\nmodule.exports = padArray;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pad-array/src/index.js\n// module id = 43\n// module chunks = 0","'use strict';\nvar numberIsNan = require('number-is-nan');\n\nfunction assertNum(x) {\n\tif (typeof x !== 'number' || numberIsNan(x)) {\n\t\tthrow new TypeError('Expected a number');\n\t}\n}\n\nexports.asc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn a - b;\n};\n\nexports.desc = function (a, b) {\n\tassertNum(a);\n\tassertNum(b);\n\treturn b - a;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/num-sort/index.js\n// module id = 44\n// module chunks = 0","module.exports = function dice(a, b) {\n var ii = a.length,\n p = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p + q1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/dice.js\n// module id = 46\n// module chunks = 0","module.exports = function intersection(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.min(a[i], b[i]);\n }\n return 1 - ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/intersection.js\n// module id = 47\n// module chunks = 0","module.exports = function jaccard(a, b) {\n var ii = a.length,\n p1 = 0,\n p2 = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p1 += a[i] * b[i];\n p2 += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p2 + q1 - p1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/jaccard.js\n// module id = 48\n// module chunks = 0","module.exports = function kulczynski(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.min(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kulczynski.js\n// module id = 49\n// module chunks = 0","module.exports = function motyka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 1 - (up / down);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/motyka.js\n// module id = 50\n// module chunks = 0","module.exports = function squaredChord(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/squaredChord.js\n// module id = 51\n// module chunks = 0","module.exports = function cosine(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (Math.sqrt(p2) * Math.sqrt(q2));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/cosine.js\n// module id = 52\n// module chunks = 0","'use strict';\n\nmodule.exports = function czekanowskiSimilarity(a, b) {\n var up = 0;\n var down = 0;\n for (var i = 0; i < a.length; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 2 * up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/czekanowski.js\n// module id = 53\n// module chunks = 0","module.exports = function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0,\n union = 0;\n for (var j = 0; j < a.length; j++) {\n inter += a[j] && b[j];\n union += a[j] || b[j];\n }\n if (union === 0)\n return 1;\n return inter / union;\n }\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return 1 - (p + q - 2 * m) / (p + q - m);\n }\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/tanimoto.js\n// module id = 54\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\n\nvar Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass Layer {\n /**\n * Create a new layer with the given options\n * @param {object} options\n * @param {number} [options.inputSize] - Number of conections that enter the neurons.\n * @param {number} [options.outputSize] - Number of conections that leave the neurons.\n * @param {number} [options.regularization] - Regularization parameter.\n * @param {number} [options.epsilon] - Learning rate parameter.\n * @param {string} [options.activation] - Activation function parameter from the FeedForwardNeuralNetwork class.\n * @param {number} [options.activationParam] - Activation parameter if needed.\n */\n constructor(options) {\n this.inputSize = options.inputSize;\n this.outputSize = options.outputSize;\n this.regularization = options.regularization;\n this.epsilon = options.epsilon;\n this.activation = options.activation;\n this.activationParam = options.activationParam;\n\n var selectedFunction = ACTIVATION_FUNCTIONS[options.activation];\n var params = selectedFunction.activation.length;\n\n var actFunction = params > 1 ? val => selectedFunction.activation(val, options.activationParam) : selectedFunction.activation;\n var derFunction = params > 1 ? val => selectedFunction.derivate(val, options.activationParam) : selectedFunction.derivate;\n\n this.activationFunction = function (i, j) {\n this[i][j] = actFunction(this[i][j]);\n };\n this.derivate = function (i, j) {\n this[i][j] = derFunction(this[i][j]);\n };\n\n if (options.model) {\n // load model\n this.W = Matrix.checkMatrix(options.W);\n this.b = Matrix.checkMatrix(options.b);\n\n } else {\n // default constructor\n\n this.W = Matrix.rand(this.inputSize, this.outputSize);\n this.b = Matrix.zeros(1, this.outputSize);\n\n this.W.apply(function (i, j) {\n this[i][j] /= Math.sqrt(options.inputSize);\n });\n }\n }\n\n /**\n * 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 * apply backpropagation algorithm at the current layer\n * @param {Matrix} delta - delta values estimated at the following layer.\n * @param {Matrix} a - 'a' values from the following layer.\n * @return {Matrix} the new delta values for the next layer.\n */\n backpropagation(delta, a) {\n this.dW = a.transposeView().mmul(delta);\n this.db = Utils.sumCol(delta);\n\n var aCopy = a.clone();\n return delta.mmul(this.W.transposeView()).mul(aCopy.apply(this.derivate));\n }\n\n /**\n * 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 * 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 * Creates a new Layer with the given model.\n * @param {object} model\n * @return {Layer}\n */\n static load(model) {\n if (model.model !== 'Layer') {\n throw new RangeError('the current model is not a Layer model');\n }\n return new Layer(model);\n }\n\n}\n\nmodule.exports = Layer;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-fnn/src/Layer.js\n// module id = 55\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\n\n/**\n * Retrieves the sum at each row of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumRow(matrix) {\n var sum = Matrix.zeros(matrix.rows, 1);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[i][0] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * Retrieves the sum at each column of the given matrix.\n * @param {Matrix} matrix\n * @return {Matrix}\n */\nfunction sumCol(matrix) {\n var sum = Matrix.zeros(1, matrix.columns);\n for (var i = 0; i < matrix.rows; ++i) {\n for (var j = 0; j < matrix.columns; ++j) {\n sum[0][j] += matrix[i][j];\n }\n }\n return sum;\n}\n\n/**\n * 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 = {}, outputs = {}, l = array.length, index = 0;\n for (var i = 0; i < l; i += 1) {\n if (inputs[array[i]] === undefined) {\n inputs[array[i]] = index;\n outputs[index] = array[i];\n index++;\n }\n }\n\n return {\n inputs: inputs,\n outputs: outputs\n };\n}\n\nmodule.exports = {\n dictOutputs: dictOutputs,\n sumCol: sumCol,\n sumRow: sumRow\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-fnn/src/utils.js\n// module id = 57\n// module chunks = 0","'use strict';\n\nconst Cluster = require('./Cluster');\nconst util = require('util');\n\nfunction ClusterLeaf(index) {\n Cluster.call(this);\n this.index = index;\n this.distance = 0;\n this.children = [];\n}\n\nutil.inherits(ClusterLeaf, Cluster);\n\nmodule.exports = ClusterLeaf;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/ClusterLeaf.js\n// module id = 58\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse} from './util';\n\n//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\nfunction QrDecomposition(value) {\n if (!(this instanceof QrDecomposition)) {\n return new QrDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n\n var qr = value.clone(),\n m = value.rows,\n n = value.columns,\n rdiag = new Array(n),\n i, j, k, s;\n\n for (k = 0; k < n; k++) {\n var nrm = 0;\n for (i = k; i < m; i++) {\n nrm = hypotenuse(nrm, qr[i][k]);\n }\n if (nrm !== 0) {\n if (qr[k][k] < 0) {\n nrm = -nrm;\n }\n for (i = k; i < m; i++) {\n qr[i][k] /= nrm;\n }\n qr[k][k] += 1;\n for (j = k + 1; j < n; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * qr[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n qr[i][j] += s * qr[i][k];\n }\n }\n }\n rdiag[k] = -nrm;\n }\n\n this.QR = qr;\n this.Rdiag = rdiag;\n}\n\nQrDecomposition.prototype = {\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var qr = this.QR,\n m = qr.rows;\n\n if (value.rows !== m) {\n throw new Error('Matrix row dimensions must agree');\n }\n if (!this.isFullRank()) {\n throw new Error('Matrix is rank deficient');\n }\n\n var count = value.columns;\n var X = value.clone();\n var n = qr.columns;\n var i, j, k, s;\n\n for (k = 0; k < n; k++) {\n for (j = 0; j < count; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * X[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= this.Rdiag[k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * qr[i][k];\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n },\n isFullRank: function () {\n var columns = this.QR.columns;\n for (var i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n },\n get upperTriangularMatrix() {\n var qr = this.QR,\n n = qr.columns,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X[i][j] = qr[i][j];\n } else if (i === j) {\n X[i][j] = this.Rdiag[i];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get orthogonalMatrix() {\n var qr = this.QR,\n rows = qr.rows,\n columns = qr.columns,\n X = new Matrix(rows, columns),\n i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X[i][k] = 0;\n }\n X[k][k] = 1;\n for (j = k; j < columns; j++) {\n if (qr[k][k] !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr[i][k] * X[i][j];\n }\n\n s = -s / qr[k][k];\n\n for (i = k; i < rows; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n }\n return X;\n }\n};\n\nexport default QrDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/dc/qr.js\n// module id = 59\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse, getFilled2DArray} from './util';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs\nfunction SingularValueDecomposition(value, options) {\n if (!(this instanceof SingularValueDecomposition)) {\n return new SingularValueDecomposition(value, options);\n }\n value = Matrix.checkMatrix(value);\n\n options = options || {};\n\n var m = value.rows,\n n = value.columns,\n nu = Math.min(m, n);\n\n var wantu = true, wantv = true;\n if (options.computeLeftSingularVectors === false) wantu = false;\n if (options.computeRightSingularVectors === false) wantv = false;\n var autoTranspose = options.autoTranspose === true;\n\n var swapped = false;\n var a;\n if (m < n) {\n if (!autoTranspose) {\n a = value.clone();\n // eslint-disable-next-line no-console\n console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose');\n } else {\n a = value.transpose();\n m = a.rows;\n n = a.columns;\n swapped = true;\n var aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n var s = new Array(Math.min(m + 1, n)),\n U = getFilled2DArray(m, nu, 0),\n V = getFilled2DArray(n, n, 0),\n e = new Array(n),\n work = new Array(m);\n\n var nct = Math.min(m - 1, n);\n var nrt = Math.max(0, Math.min(n - 2, m));\n\n var i, j, k, p, t, ks, f, cs, sn, max, kase,\n scale, sp, spm1, epm1, sk, ek, b, c, shift, g;\n\n for (k = 0, max = Math.max(nct, nrt); k < max; k++) {\n if (k < nct) {\n s[k] = 0;\n for (i = k; i < m; i++) {\n s[k] = hypotenuse(s[k], a[i][k]);\n }\n if (s[k] !== 0) {\n if (a[k][k] < 0) {\n s[k] = -s[k];\n }\n for (i = k; i < m; i++) {\n a[i][k] /= s[k];\n }\n a[k][k] += 1;\n }\n s[k] = -s[k];\n }\n\n for (j = k + 1; j < n; j++) {\n if ((k < nct) && (s[k] !== 0)) {\n t = 0;\n for (i = k; i < m; i++) {\n t += a[i][k] * a[i][j];\n }\n t = -t / a[k][k];\n for (i = k; i < m; i++) {\n a[i][j] += t * a[i][k];\n }\n }\n e[j] = a[k][j];\n }\n\n if (wantu && (k < nct)) {\n for (i = k; i < m; i++) {\n U[i][k] = a[i][k];\n }\n }\n\n if (k < nrt) {\n e[k] = 0;\n for (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 (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 (i = k + 1; i < m; i++) {\n work[i] = 0;\n }\n for (j = k + 1; j < n; j++) {\n for (i = k + 1; i < m; i++) {\n work[i] += e[j] * a[i][j];\n }\n }\n for (j = k + 1; j < n; j++) {\n t = -e[j] / e[k + 1];\n for (i = k + 1; i < m; i++) {\n a[i][j] += t * work[i];\n }\n }\n }\n if (wantv) {\n for (i = k + 1; i < n; i++) {\n V[i][k] = e[i];\n }\n }\n }\n }\n\n p = Math.min(n, m + 1);\n if (nct < n) {\n s[nct] = a[nct][nct];\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a[nrt][p - 1];\n }\n e[p - 1] = 0;\n\n if (wantu) {\n for (j = nct; j < nu; j++) {\n for (i = 0; i < m; i++) {\n U[i][j] = 0;\n }\n U[j][j] = 1;\n }\n for (k = nct - 1; k >= 0; k--) {\n if (s[k] !== 0) {\n for (j = k + 1; j < nu; j++) {\n t = 0;\n for (i = k; i < m; i++) {\n t += U[i][k] * U[i][j];\n }\n t = -t / U[k][k];\n for (i = k; i < m; i++) {\n U[i][j] += t * U[i][k];\n }\n }\n for (i = k; i < m; i++) {\n U[i][k] = -U[i][k];\n }\n U[k][k] = 1 + U[k][k];\n for (i = 0; i < k - 1; i++) {\n U[i][k] = 0;\n }\n } else {\n for (i = 0; i < m; i++) {\n U[i][k] = 0;\n }\n U[k][k] = 1;\n }\n }\n }\n\n if (wantv) {\n for (k = n - 1; k >= 0; k--) {\n if ((k < nrt) && (e[k] !== 0)) {\n for (j = k + 1; j < n; j++) {\n t = 0;\n for (i = k + 1; i < n; i++) {\n t += V[i][k] * V[i][j];\n }\n t = -t / V[k + 1][k];\n for (i = k + 1; i < n; i++) {\n V[i][j] += t * V[i][k];\n }\n }\n }\n for (i = 0; i < n; i++) {\n V[i][k] = 0;\n }\n V[k][k] = 1;\n }\n }\n\n var pp = p - 1,\n iter = 0,\n eps = Math.pow(2, -52);\n while (p > 0) {\n for (k = p - 2; k >= -1; k--) {\n if (k === -1) {\n break;\n }\n if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) {\n e[k] = 0;\n break;\n }\n }\n if (k === p - 2) {\n kase = 4;\n } else {\n for (ks = p - 1; ks >= k; ks--) {\n if (ks === k) {\n break;\n }\n t = (ks !== p ? Math.abs(e[ks]) : 0) + (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 f = e[p - 2];\n e[p - 2] = 0;\n for (j = p - 2; j >= k; j--) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][p - 1];\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\n V[i][j] = t;\n }\n }\n }\n break;\n }\n case 2 : {\n f = e[k - 1];\n e[k - 1] = 0;\n for (j = k; j < p; j++) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n sn = f / t;\n s[j] = t;\n f = -sn * e[j];\n e[j] = cs * e[j];\n if (wantu) {\n for (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][k - 1];\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\n U[i][j] = t;\n }\n }\n }\n break;\n }\n case 3 : {\n scale = Math.max(Math.max(Math.max(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]));\n sp = s[p - 1] / scale;\n spm1 = s[p - 2] / scale;\n epm1 = e[p - 2] / scale;\n sk = s[k] / scale;\n ek = e[k] / scale;\n b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\n c = (sp * epm1) * (sp * epm1);\n shift = 0;\n if ((b !== 0) || (c !== 0)) {\n shift = Math.sqrt(b * b + c);\n if (b < 0) {\n shift = -shift;\n }\n shift = c / (b + shift);\n }\n f = (sk + sp) * (sk - sp) + shift;\n g = sk * ek;\n for (j = k; j < p - 1; j++) {\n t = hypotenuse(f, g);\n cs = f / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][j + 1];\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\n V[i][j] = t;\n }\n }\n t = hypotenuse(f, g);\n 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 (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][j + 1];\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\n U[i][j] = t;\n }\n }\n }\n e[p - 2] = f;\n iter = iter + 1;\n break;\n }\n case 4: {\n if (s[k] <= 0) {\n s[k] = (s[k] < 0 ? -s[k] : 0);\n if (wantv) {\n for (i = 0; i <= pp; i++) {\n V[i][k] = -V[i][k];\n }\n }\n }\n while (k < pp) {\n if (s[k] >= s[k + 1]) {\n break;\n }\n t = s[k];\n s[k] = s[k + 1];\n s[k + 1] = t;\n if (wantv && (k < n - 1)) {\n for (i = 0; i < n; i++) {\n t = V[i][k + 1];\n V[i][k + 1] = V[i][k];\n V[i][k] = t;\n }\n }\n if (wantu && (k < m - 1)) {\n for (i = 0; i < m; i++) {\n t = U[i][k + 1];\n U[i][k + 1] = U[i][k];\n U[i][k] = t;\n }\n }\n k++;\n }\n iter = 0;\n p--;\n break;\n }\n // no default\n }\n }\n\n if (swapped) {\n var tmp = V;\n V = U;\n U = tmp;\n }\n\n this.m = m;\n this.n = n;\n this.s = s;\n this.U = U;\n this.V = V;\n}\n\nSingularValueDecomposition.prototype = {\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n },\n get norm2() {\n return this.s[0];\n },\n get rank() {\n var eps = Math.pow(2, -52),\n tol = Math.max(this.m, this.n) * this.s[0] * eps,\n r = 0,\n s = this.s;\n for (var i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n },\n get diagonal() {\n return this.s;\n },\n // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\n get threshold() {\n return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0];\n },\n get leftSingularVectors() {\n if (!Matrix.isMatrix(this.U)) {\n this.U = new Matrix(this.U);\n }\n return this.U;\n },\n get rightSingularVectors() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n },\n solve: function (value) {\n\n var Y = value,\n e = this.threshold,\n scols = this.s.length,\n Ls = Matrix.zeros(scols, scols),\n i;\n\n for (i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls[i][i] = 0;\n } else {\n Ls[i][i] = 1 / this.s[i];\n }\n }\n\n var U = this.U;\n var V = this.rightSingularVectors;\n\n var VL = V.mmul(Ls),\n vrows = V.rows,\n urows = U.length,\n VLU = Matrix.zeros(vrows, urows),\n j, k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < scols; k++) {\n sum += VL[i][k] * U[j][k];\n }\n VLU[i][j] = sum;\n }\n }\n\n return VLU.mmul(Y);\n },\n solveForDiagonal: function (value) {\n return this.solve(Matrix.diag(value));\n },\n inverse: function () {\n var V = this.V;\n var e = this.threshold,\n vrows = V.length,\n vcols = V[0].length,\n X = new Matrix(vrows, this.s.length),\n i, j;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < vcols; j++) {\n if (Math.abs(this.s[j]) > e) {\n X[i][j] = V[i][j] / this.s[j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n\n var U = this.U;\n\n var urows = U.length,\n ucols = U[0].length,\n Y = new Matrix(vrows, urows),\n k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < ucols; k++) {\n sum += X[i][k] * U[j][k];\n }\n Y[i][j] = sum;\n }\n }\n\n return Y;\n }\n};\n\nexport default SingularValueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/dc/svd.js\n// module id = 60\n// module chunks = 0","'use strict';\n\nconst nearestVector = require('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 */\nfunction 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 * @returns {Array} the cluster identifier for each data dot\n */\nfunction updateClusterID(data, centers, clusterID, distance) {\n for (var i = 0; i < data.length; i++) {\n clusterID[i] = nearestVector(centers, data[i], {distanceFunction: distance});\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 >} 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 * @returns {Array} he K centers in format [x,y,z,...]\n */\nfunction updateCenters(data, clusterID, K) {\n const nDim = data[0].length;\n\n // creates empty centers with 0 size\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 centers[id][d] /= centersLen[id];\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 */\nfunction converged(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\nexports.updateClusterID = updateClusterID;\nexports.updateCenters = updateCenters;\nexports.calculateDistanceMatrix = calculateDistanceMatrix;\nexports.converged = converged;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kmeans/src/utils.js\n// module id = 61\n// module chunks = 0","'use strict';\n\nmodule.exports = abstractMatrix;\n\nvar LuDecomposition = require('./dc/lu');\nvar SvDecomposition = require('./dc/svd');\nvar arrayUtils = require('ml-array-utils');\nvar util = require('./util');\nvar MatrixTransposeView = require('./views/transpose');\nvar MatrixRowView = require('./views/row');\nvar MatrixSubView = require('./views/sub');\nvar MatrixSelectionView = require('./views/selection');\nvar MatrixColumnView = require('./views/column');\nvar MatrixFlipRowView = require('./views/flipRow');\nvar MatrixFlipColumnView = require('./views/flipColumn');\n\nfunction abstractMatrix(superCtor) {\n if (superCtor === undefined) superCtor = Object;\n\n /**\n * Real matrix\n * @class Matrix\n * @param {number|Array|Matrix} nRows - Number of rows of the new matrix,\n * 2D array containing the data or Matrix instance to clone\n * @param {number} [nColumns] - Number of columns of the new matrix\n */\n class Matrix extends superCtor {\n static get [Symbol.species]() {\n return this;\n }\n\n /**\n * Constructs a Matrix with the chosen dimensions from a 1D array\n * @param {number} newRows - Number of rows\n * @param {number} newColumns - Number of columns\n * @param {Array} newData - A 1D array containing data for the matrix\n * @return {Matrix} - The new matrix\n */\n static from1DArray(newRows, newColumns, newData) {\n var length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('Data length does not match given dimensions');\n }\n var newMatrix = new this(newRows, newColumns);\n for (var row = 0; row < newRows; row++) {\n for (var column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n /**\n * Creates a row vector, a matrix with only one row.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static rowVector(newData) {\n var vector = new this(1, newData.length);\n for (var i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates a column vector, a matrix with only one column.\n * @param {Array} newData - A 1D array containing data for the vector\n * @return {Matrix} - The new matrix\n */\n static columnVector(newData) {\n var vector = new this(newData.length, 1);\n for (var i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n /**\n * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static empty(rows, columns) {\n return new this(rows, columns);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to zero.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static zeros(rows, columns) {\n return this.empty(rows, columns).fill(0);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be set to one.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @return {Matrix} - The new matrix\n */\n static ones(rows, columns) {\n return this.empty(rows, columns).fill(1);\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be randomly set.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static rand(rows, columns, rng) {\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n matrix.set(i, j, rng());\n }\n }\n return matrix;\n }\n\n /**\n * Creates a matrix with the given dimensions. Values will be random integers.\n * @param {number} rows - Number of rows\n * @param {number} columns - Number of columns\n * @param {number} [maxValue=1000] - Maximum value\n * @param {function} [rng=Math.random] - Random number generator\n * @return {Matrix} The new matrix\n */\n static randInt(rows, columns, maxValue, rng) {\n if (maxValue === undefined) maxValue = 1000;\n if (rng === undefined) rng = Math.random;\n var matrix = this.empty(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = Math.floor(rng() * maxValue);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n /**\n * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.\n * @param {number} rows - Number of rows\n * @param {number} [columns=rows] - Number of columns\n * @param {number} [value=1] - Value to fill the diagonal with\n * @return {Matrix} - The new identity matrix\n */\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n var min = Math.min(rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n /**\n * Creates a diagonal matrix based on the given array.\n * @param {Array} data - Array containing the data for the diagonal\n * @param {number} [rows] - Number of rows (Default: data.length)\n * @param {number} [columns] - Number of columns (Default: rows)\n * @return {Matrix} - The new diagonal matrix\n */\n static diag(data, rows, columns) {\n var l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n var min = Math.min(l, rows, columns);\n var matrix = this.zeros(rows, columns);\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n /**\n * Returns a matrix whose elements are the minimum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Returns a matrix whose elements are the maximum between matrix1 and matrix2\n * @param {Matrix} matrix1\n * @param {Matrix} matrix2\n * @return {Matrix}\n */\n static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n var rows = matrix1.rows;\n var columns = matrix1.columns;\n var result = new this(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n /**\n * Check that the provided value is a Matrix and tries to instantiate one if not\n * @param {*} value - The value to check\n * @return {Matrix}\n */\n static checkMatrix(value) {\n return Matrix.isMatrix(value) ? value : new this(value);\n }\n\n /**\n * Returns true if the argument is a Matrix, false otherwise\n * @param {*} value - The value to check\n * @return {boolean}\n */\n static isMatrix(value) {\n return (value != null) && (value.klass === 'Matrix');\n }\n\n /**\n * @prop {number} size - The number of elements in the matrix.\n */\n get size() {\n return this.rows * this.columns;\n }\n\n /**\n * Applies a callback for each element of the matrix. The function is called in the matrix (this) context.\n * @param {function} callback - Function that will be called with two parameters : i (row) and j (column)\n * @return {Matrix} this\n */\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n var ii = this.rows;\n var jj = this.columns;\n for (var i = 0; i < ii; i++) {\n for (var j = 0; j < jj; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n /**\n * Returns a new 1D array filled row by row with the matrix values\n * @return {Array}\n */\n to1DArray() {\n var array = new Array(this.size);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n array[i * this.columns + j] = this.get(i, j);\n }\n }\n return array;\n }\n\n /**\n * Returns a 2D array containing a copy of the data\n * @return {Array}\n */\n to2DArray() {\n var copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n /**\n * @return {boolean} true if the matrix has one row\n */\n isRowVector() {\n return this.rows === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one column\n */\n isColumnVector() {\n return this.columns === 1;\n }\n\n /**\n * @return {boolean} true if the matrix has one row or one column\n */\n isVector() {\n return (this.rows === 1) || (this.columns === 1);\n }\n\n /**\n * @return {boolean} true if the matrix has the same number of rows and columns\n */\n isSquare() {\n return this.rows === this.columns;\n }\n\n /**\n * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal\n */\n isSymmetric() {\n if (this.isSquare()) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j <= i; j++) {\n if (this.get(i, j) !== this.get(j, i)) {\n return false;\n }\n }\n }\n return true;\n }\n return false;\n }\n\n /**\n * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @param {number} value - The new value for the element\n * @return {Matrix} this\n */\n set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars\n throw new Error('set method is unimplemented');\n }\n\n /**\n * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]\n * @abstract\n * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @return {number}\n */\n get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars\n throw new Error('get method is unimplemented');\n }\n\n /**\n * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of\n * rows of the matrix, and colRep times the number of columns of the matrix\n * @param {number} rowRep - Number of times the rows should be repeated\n * @param {number} colRep - Number of times the columns should be re\n * @return {Matrix}\n * @example\n * var matrix = new Matrix([[1,2]]);\n * matrix.repeat(2); // [[1,2],[1,2]]\n */\n repeat(rowRep, colRep) {\n rowRep = rowRep || 1;\n colRep = colRep || 1;\n var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);\n for (var i = 0; i < rowRep; i++) {\n for (var j = 0; j < colRep; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n /**\n * Fills the matrix with a given value. All elements will be set to this value.\n * @param {number} value - New value\n * @return {Matrix} this\n */\n fill(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n /**\n * Negates the matrix. All elements will be multiplied by (-1)\n * @return {Matrix} this\n */\n neg() {\n return this.mulS(-1);\n }\n\n /**\n * Returns a new array from the given row index\n * @param {number} index - Row index\n * @return {Array}\n */\n getRow(index) {\n util.checkRowIndex(this, index);\n var row = new Array(this.columns);\n for (var i = 0; i < this.columns; i++) {\n row[i] = this.get(index, i);\n }\n return row;\n }\n\n /**\n * Returns a new row vector from the given row index\n * @param {number} index - Row index\n * @return {Matrix}\n */\n getRowVector(index) {\n return this.constructor.rowVector(this.getRow(index));\n }\n\n /**\n * Sets a row at the given index\n * @param {number} index - Row index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setRow(index, array) {\n util.checkRowIndex(this, index);\n array = util.checkRowVector(this, array);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two rows\n * @param {number} row1 - First row index\n * @param {number} row2 - Second row index\n * @return {Matrix} this\n */\n swapRows(row1, row2) {\n util.checkRowIndex(this, row1);\n util.checkRowIndex(this, row2);\n for (var i = 0; i < this.columns; i++) {\n var temp = this.get(row1, i);\n this.set(row1, i, this.get(row2, i));\n this.set(row2, i, temp);\n }\n return this;\n }\n\n /**\n * Returns a new array from the given column index\n * @param {number} index - Column index\n * @return {Array}\n */\n getColumn(index) {\n util.checkColumnIndex(this, index);\n var column = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n column[i] = this.get(i, index);\n }\n return column;\n }\n\n /**\n * Returns a new column vector from the given column index\n * @param {number} index - Column index\n * @return {Matrix}\n */\n getColumnVector(index) {\n return this.constructor.columnVector(this.getColumn(index));\n }\n\n /**\n * Sets a column at the given index\n * @param {number} index - Column index\n * @param {Array|Matrix} array - Array or vector\n * @return {Matrix} this\n */\n setColumn(index, array) {\n util.checkColumnIndex(this, index);\n array = util.checkColumnVector(this, array);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n /**\n * Swaps two columns\n * @param {number} column1 - First column index\n * @param {number} column2 - Second column index\n * @return {Matrix} this\n */\n swapColumns(column1, column2) {\n util.checkColumnIndex(this, column1);\n util.checkColumnIndex(this, column2);\n for (var i = 0; i < this.rows; i++) {\n var temp = this.get(i, column1);\n this.set(i, column1, this.get(i, column2));\n this.set(i, column2, temp);\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each row\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each row by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divRowVector(vector) {\n vector = util.checkRowVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[j]);\n }\n }\n return this;\n }\n\n /**\n * Adds the values of a vector to each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n addColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Subtracts the values of a vector from each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n subColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a vector with each column\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n mulColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Divides the values of each column by those of a vector\n * @param {Array|Matrix} vector - Array or vector\n * @return {Matrix} this\n */\n divColumnVector(vector) {\n vector = util.checkColumnVector(this, vector);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[i]);\n }\n }\n return this;\n }\n\n /**\n * Multiplies the values of a row with a scalar\n * @param {number} index - Row index\n * @param {number} value\n * @return {Matrix} this\n */\n mulRow(index, value) {\n util.checkRowIndex(this, index);\n for (var i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n /**\n * Multiplies the values of a column with a scalar\n * @param {number} index - Column index\n * @param {number} value\n * @return {Matrix} this\n */\n mulColumn(index, value) {\n util.checkColumnIndex(this, index);\n for (var i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n /**\n * Returns the maximum value of the matrix\n * @return {number}\n */\n max() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value\n * @return {Array}\n */\n maxIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of the matrix\n * @return {number}\n */\n min() {\n var v = this.get(0, 0);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value\n * @return {Array}\n */\n minIndex() {\n var v = this.get(0, 0);\n var idx = [0, 0];\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n maxRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n maxRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one row\n * @param {number} row - Row index\n * @return {number}\n */\n minRow(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one row\n * @param {number} row - Row index\n * @return {Array}\n */\n minRowIndex(row) {\n util.checkRowIndex(this, row);\n var v = this.get(row, 0);\n var idx = [row, 0];\n for (var i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the maximum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n maxColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the maximum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n maxColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns the minimum value of one column\n * @param {number} column - Column index\n * @return {number}\n */\n minColumn(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n /**\n * Returns the index of the minimum value of one column\n * @param {number} column - Column index\n * @return {Array}\n */\n minColumnIndex(column) {\n util.checkColumnIndex(this, column);\n var v = this.get(0, column);\n var idx = [0, column];\n for (var i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n /**\n * Returns an array containing the diagonal values of the matrix\n * @return {Array}\n */\n diag() {\n var min = Math.min(this.rows, this.columns);\n var diag = new Array(min);\n for (var i = 0; i < min; i++) {\n diag[i] = this.get(i, i);\n }\n return diag;\n }\n\n /**\n * Returns the sum by the argument given, if no argument given,\n * it returns the sum of all elements of the matrix.\n * @param {string} by - sum by 'row' or 'column'.\n * @return {Matrix|number}\n */\n sum(by) {\n switch (by) {\n case 'row':\n return util.sumByRow(this);\n case 'column':\n return util.sumByColumn(this);\n default:\n return util.sumAll(this);\n }\n }\n\n /**\n * Returns the mean of all elements of the matrix\n * @return {number}\n */\n mean() {\n return this.sum() / this.size;\n }\n\n /**\n * Returns the product of all elements of the matrix\n * @return {number}\n */\n prod() {\n var prod = 1;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n prod *= this.get(i, j);\n }\n }\n return prod;\n }\n\n /**\n * Computes the cumulative sum of the matrix elements (in place, row by row)\n * @return {Matrix} this\n */\n cumulativeSum() {\n var sum = 0;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n sum += this.get(i, j);\n this.set(i, j, sum);\n }\n }\n return this;\n }\n\n /**\n * Computes the dot (scalar) product between the matrix and another\n * @param {Matrix} vector2 vector\n * @return {number}\n */\n dot(vector2) {\n if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n var vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n var dot = 0;\n for (var i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n /**\n * Returns the matrix product between this and other\n * @param {Matrix} other\n * @return {Matrix}\n */\n mmul(other) {\n other = this.constructor.checkMatrix(other);\n if (this.columns !== other.rows) {\n // eslint-disable-next-line no-console\n console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\n }\n\n var m = this.rows;\n var n = this.columns;\n var p = other.columns;\n\n var result = new this.constructor[Symbol.species](m, p);\n\n var Bcolj = new Array(n);\n for (var j = 0; j < p; j++) {\n for (var k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (var i = 0; i < m; i++) {\n var s = 0;\n for (k = 0; k < n; k++) {\n s += this.get(i, k) * Bcolj[k];\n }\n\n result.set(i, j, s);\n }\n }\n return result;\n }\n\n strassen2x2(other) {\n var result = new this.constructor[Symbol.species](2, 2);\n const a11 = this.get(0, 0);\n const b11 = other.get(0, 0);\n const a12 = this.get(0, 1);\n const b12 = other.get(0, 1);\n const a21 = this.get(1, 0);\n const b21 = other.get(1, 0);\n const a22 = this.get(1, 1);\n const b22 = other.get(1, 1);\n\n // Compute intermediate values.\n const m1 = (a11 + a22) * (b11 + b22);\n const m2 = (a21 + a22) * b11;\n const m3 = a11 * (b12 - b22);\n const m4 = a22 * (b21 - b11);\n const m5 = (a11 + a12) * b22;\n const m6 = (a21 - a11) * (b11 + b12);\n const m7 = (a12 - a22) * (b21 + b22);\n\n // Combine intermediate values into the output.\n const c00 = m1 + m4 - m5 + m7;\n const c01 = m3 + m5;\n const c10 = m2 + m4;\n const c11 = m1 - m2 + m3 + m6;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n return result;\n }\n\n strassen3x3(other) {\n var result = new this.constructor[Symbol.species](3, 3);\n\n const a00 = this.get(0, 0);\n const a01 = this.get(0, 1);\n const a02 = this.get(0, 2);\n const a10 = this.get(1, 0);\n const a11 = this.get(1, 1);\n const a12 = this.get(1, 2);\n const a20 = this.get(2, 0);\n const a21 = this.get(2, 1);\n const a22 = this.get(2, 2);\n\n const b00 = other.get(0, 0);\n const b01 = other.get(0, 1);\n const b02 = other.get(0, 2);\n const b10 = other.get(1, 0);\n const b11 = other.get(1, 1);\n const b12 = other.get(1, 2);\n const b20 = other.get(2, 0);\n const b21 = other.get(2, 1);\n const b22 = other.get(2, 2);\n\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\n const m2 = (a00 - a10) * (-b01 + b11);\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\n const m5 = (a10 + a11) * (-b00 + b01);\n const m6 = a00 * b00;\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\n const m8 = (-a00 + a20) * (b02 - b12);\n const m9 = (a20 + a21) * (-b00 + b02);\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\n const m13 = (a02 - a22) * (b11 - b21);\n const m14 = a02 * b20;\n const m15 = (a21 + a22) * (-b20 + b21);\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\n const m17 = (a02 - a12) * (b12 - b22);\n const m18 = (a11 + a12) * (-b20 + b22);\n const m19 = a01 * b10;\n const m20 = a12 * b21;\n const m21 = a10 * b02;\n const m22 = a20 * b01;\n const m23 = a22 * b22;\n\n const c00 = m6 + m14 + m19;\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\n const c11 = m2 + m4 + m5 + m6 + m20;\n const c12 = m14 + m16 + m17 + m18 + m21;\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\n const c21 = m12 + m13 + m14 + m15 + m22;\n const c22 = m6 + m7 + m8 + m9 + m23;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(0, 2, c02);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n result.set(1, 2, c12);\n result.set(2, 0, c20);\n result.set(2, 1, c21);\n result.set(2, 2, c22);\n return result;\n }\n\n /**\n * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.\n * @param {Matrix} y\n * @return {Matrix}\n */\n mmulStrassen(y) {\n var x = this.clone();\n var r1 = x.rows;\n var c1 = x.columns;\n var r2 = y.rows;\n var c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);\n }\n\n // Put a matrix into the top left of a matrix of zeros.\n // `rows` and `cols` are the dimensions of the output matrix.\n function embed(mat, rows, cols) {\n var r = mat.rows;\n var c = mat.columns;\n if ((r === rows) && (c === cols)) {\n return mat;\n } else {\n var resultat = Matrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\n }\n }\n\n\n // Make sure both matrices are the same size.\n // This is exclusively for simplicity:\n // this algorithm can be implemented with matrices of different sizes.\n\n var r = Math.max(r1, r2);\n var c = Math.max(c1, c2);\n x = embed(x, r, c);\n y = embed(y, r, c);\n\n // Our recursive multiplication function.\n function blockMult(a, b, rows, cols) {\n // For small matrices, resort to naive multiplication.\n if (rows <= 512 || cols <= 512) {\n return a.mmul(b); // a is equivalent to this\n }\n\n // Apply dynamic padding.\n if ((rows % 2 === 1) && (cols % 2 === 1)) {\n a = embed(a, rows + 1, cols + 1);\n b = embed(b, rows + 1, cols + 1);\n } else if (rows % 2 === 1) {\n a = embed(a, rows + 1, cols);\n b = embed(b, rows + 1, cols);\n } else if (cols % 2 === 1) {\n a = embed(a, rows, cols + 1);\n b = embed(b, rows, cols + 1);\n }\n\n var halfRows = parseInt(a.rows / 2);\n var halfCols = parseInt(a.columns / 2);\n // Subdivide input matrices.\n var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);\n var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);\n var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);\n var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);\n var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);\n var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);\n var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols);\n\n // Combine intermediate values into the output.\n var c11 = Matrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n var c12 = Matrix.add(m3, m5);\n var c21 = Matrix.add(m2, m4);\n var c22 = Matrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n //Crop output to the desired size (undo dynamic padding).\n var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);\n resultat = resultat.setSubMatrix(c11, 0, 0);\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\n }\n return blockMult(x, y, r, c);\n }\n\n /**\n * Returns a row-by-row scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The scaled matrix\n */\n scaleRows(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.rows; i++) {\n var scaled = arrayUtils.scale(this.getRow(i), {min, max});\n newMatrix.setRow(i, scaled);\n }\n return newMatrix;\n }\n\n /**\n * Returns a new column-by-column scaled matrix\n * @param {number} [min=0] - Minimum scaled value\n * @param {number} [max=1] - Maximum scaled value\n * @return {Matrix} - The new scaled matrix\n * @example\n * var matrix = new Matrix([[1,2],[-1,0]]);\n * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]\n */\n scaleColumns(min, max) {\n min = min === undefined ? 0 : min;\n max = max === undefined ? 1 : max;\n if (min >= max) {\n throw new RangeError('min should be strictly smaller than max');\n }\n var newMatrix = this.constructor.empty(this.rows, this.columns);\n for (var i = 0; i < this.columns; i++) {\n var scaled = arrayUtils.scale(this.getColumn(i), {\n min: min,\n max: max\n });\n newMatrix.setColumn(i, scaled);\n }\n return newMatrix;\n }\n\n\n /**\n * Returns the Kronecker product (also known as tensor product) between this and other\n * See https://en.wikipedia.org/wiki/Kronecker_product\n * @param {Matrix} other\n * @return {Matrix}\n */\n kroneckerProduct(other) {\n other = this.constructor.checkMatrix(other);\n\n var m = this.rows;\n var n = this.columns;\n var p = other.rows;\n var q = other.columns;\n\n var result = new this.constructor[Symbol.species](m * p, n * q);\n for (var i = 0; i < m; i++) {\n for (var j = 0; j < n; j++) {\n for (var k = 0; k < p; k++) {\n for (var l = 0; l < q; l++) {\n result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Transposes the matrix and returns a new one containing the result\n * @return {Matrix}\n */\n transpose() {\n var result = new this.constructor[Symbol.species](this.columns, this.rows);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n /**\n * Sorts the rows (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortRows(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Sorts the columns (in place)\n * @param {function} compareFunction - usual Array.prototype.sort comparison function\n * @return {Matrix} this\n */\n sortColumns(compareFunction) {\n if (compareFunction === undefined) compareFunction = compareNumbers;\n for (var i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n /**\n * Returns a subset of the matrix\n * @param {number} startRow - First row index\n * @param {number} endRow - Last row index\n * @param {number} startColumn - First column index\n * @param {number} endColumn - Last column index\n * @return {Matrix}\n */\n subMatrix(startRow, endRow, startColumn, endColumn) {\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);\n for (var i = startRow; i <= endRow; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n newMatrix[i - startRow][j - startColumn] = this.get(i, j);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of row indices\n * @param {Array} indices - Array containing the row indices\n * @param {number} [startColumn = 0] - First column index\n * @param {number} [endColumn = this.columns-1] - Last column index\n * @return {Matrix}\n */\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if ((startColumn > endColumn) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startColumn; j <= endColumn; j++) {\n if (indices[i] < 0 || indices[i] >= this.rows) {\n throw new RangeError('Row index out of range: ' + indices[i]);\n }\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns a subset of the matrix based on an array of column indices\n * @param {Array} indices - Array containing the column indices\n * @param {number} [startRow = 0] - First row index\n * @param {number} [endRow = this.rows-1] - Last row index\n * @return {Matrix}\n */\n subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if ((startRow > endRow) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows)) {\n throw new RangeError('Argument out of range');\n }\n\n var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);\n for (var i = 0; i < indices.length; i++) {\n for (var j = startRow; j <= endRow; j++) {\n if (indices[i] < 0 || indices[i] >= this.columns) {\n throw new RangeError('Column index out of range: ' + indices[i]);\n }\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\n }\n }\n return newMatrix;\n }\n\n /**\n * Set a part of the matrix to the given sub-matrix\n * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.\n * @param {number} startRow - The index of the first row to set\n * @param {number} startColumn - The index of the first column to set\n * @return {Matrix}\n */\n setSubMatrix(matrix, startRow, startColumn) {\n matrix = this.constructor.checkMatrix(matrix);\n var endRow = startRow + matrix.rows - 1;\n var endColumn = startColumn + matrix.columns - 1;\n util.checkRange(this, startRow, endRow, startColumn, endColumn);\n for (var i = 0; i < matrix.rows; i++) {\n for (var j = 0; j < matrix.columns; j++) {\n this[startRow + i][startColumn + j] = matrix.get(i, j);\n }\n }\n return this;\n }\n\n /**\n * Return a new matrix based on a selection of rows and columns\n * @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.\n * @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.\n * @return {Matrix} The new matrix\n */\n selection(rowIndices, columnIndices) {\n var indices = util.checkIndices(this, rowIndices, columnIndices);\n var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);\n for (var i = 0; i < indices.row.length; i++) {\n var rowIndex = indices.row[i];\n for (var j = 0; j < indices.column.length; j++) {\n var columnIndex = indices.column[j];\n newMatrix[i][j] = this.get(rowIndex, columnIndex);\n }\n }\n return newMatrix;\n }\n\n /**\n * Returns the trace of the matrix (sum of the diagonal elements)\n * @return {number}\n */\n trace() {\n var min = Math.min(this.rows, this.columns);\n var trace = 0;\n for (var i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n /*\n Matrix views\n */\n\n /**\n * Returns a view of the transposition of the matrix\n * @return {MatrixTransposeView}\n */\n transposeView() {\n return new MatrixTransposeView(this);\n }\n\n /**\n * Returns a view of the row vector with the given index\n * @param {number} row - row index of the vector\n * @return {MatrixRowView}\n */\n rowView(row) {\n util.checkRowIndex(this, row);\n return new MatrixRowView(this, row);\n }\n\n /**\n * Returns a view of the column vector with the given index\n * @param {number} column - column index of the vector\n * @return {MatrixColumnView}\n */\n columnView(column) {\n util.checkColumnIndex(this, column);\n return new MatrixColumnView(this, column);\n }\n\n /**\n * Returns a view of the matrix flipped in the row axis\n * @return {MatrixFlipRowView}\n */\n flipRowView() {\n return new MatrixFlipRowView(this);\n }\n\n /**\n * Returns a view of the matrix flipped in the column axis\n * @return {MatrixFlipColumnView}\n */\n flipColumnView() {\n return new MatrixFlipColumnView(this);\n }\n\n /**\n * Returns a view of a submatrix giving the index boundaries\n * @param {number} startRow - first row index of the submatrix\n * @param {number} endRow - last row index of the submatrix\n * @param {number} startColumn - first column index of the submatrix\n * @param {number} endColumn - last column index of the submatrix\n * @return {MatrixSubView}\n */\n subMatrixView(startRow, endRow, startColumn, endColumn) {\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\n }\n\n /**\n * Returns a view of the cross of the row indices and the column indices\n * @example\n * // resulting vector is [[2], [2]]\n * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])\n * @param {Array} rowIndices\n * @param {Array} columnIndices\n * @return {MatrixSelectionView}\n */\n selectionView(rowIndices, columnIndices) {\n return new MatrixSelectionView(this, rowIndices, columnIndices);\n }\n\n\n /**\n * Calculates and returns the determinant of a matrix as a Number\n * @example\n * new Matrix([[1,2,3], [4,5,6]]).det()\n * @return {number}\n */\n det() {\n if (this.isSquare()) {\n var a, b, c, d;\n if (this.columns === 2) {\n // 2 x 2 matrix\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(1, 0);\n d = this.get(1, 1);\n\n return a * d - (b * c);\n } else if (this.columns === 3) {\n // 3 x 3 matrix\n var subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = this.selectionView([1, 2], [1, 2]);\n subMatrix1 = this.selectionView([1, 2], [0, 2]);\n subMatrix2 = this.selectionView([1, 2], [0, 1]);\n a = this.get(0, 0);\n b = this.get(0, 1);\n c = this.get(0, 2);\n\n return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(this).determinant;\n }\n\n } else {\n throw Error('Determinant can only be calculated for a square matrix.');\n }\n }\n\n /**\n * Returns inverse of a matrix if it exists or the pseudoinverse\n * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)\n * @return {Matrix} the (pseudo)inverted matrix.\n */\n pseudoInverse(threshold) {\n if (threshold === undefined) threshold = Number.EPSILON;\n var svdSolution = new SvDecomposition(this, {autoTranspose: true});\n\n var U = svdSolution.leftSingularVectors;\n var V = svdSolution.rightSingularVectors;\n var s = svdSolution.diagonal;\n\n for (var i = 0; i < s.length; i++) {\n if (Math.abs(s[i]) > threshold) {\n s[i] = 1.0 / s[i];\n } else {\n s[i] = 0.0;\n }\n }\n\n // convert list to diagonal\n s = this.constructor[Symbol.species].diag(s);\n return V.mmul(s.mmul(U.transposeView()));\n }\n }\n\n Matrix.prototype.klass = 'Matrix';\n\n /**\n * @private\n * Check that two matrices have the same dimensions\n * @param {Matrix} matrix\n * @param {Matrix} otherMatrix\n */\n function checkDimensions(matrix, otherMatrix) { // eslint-disable-line no-unused-vars\n if (matrix.rows !== otherMatrix.rows ||\n matrix.columns !== otherMatrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n }\n\n function compareNumbers(a, b) {\n return a - b;\n }\n\n /*\n Synonyms\n */\n\n Matrix.random = Matrix.rand;\n Matrix.diagonal = Matrix.diag;\n Matrix.prototype.diagonal = Matrix.prototype.diag;\n Matrix.identity = Matrix.eye;\n Matrix.prototype.negate = Matrix.prototype.neg;\n Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;\n Matrix.prototype.determinant = Matrix.prototype.det;\n\n /*\n Add dynamically instance and static methods for mathematical operations\n */\n\n var inplaceOperator = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var inplaceOperatorScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% value);\n }\n }\n return this;\n})\n`;\n\n var inplaceOperatorMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n checkDimensions(this, matrix);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) %op% matrix.get(i, j));\n }\n }\n return this;\n})\n`;\n\n var staticOperator = `\n(function %name%(matrix, value) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(value);\n})\n`;\n\n var inplaceMethod = `\n(function %name%() {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var staticMethod = `\n(function %name%(matrix) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%();\n})\n`;\n\n var inplaceMethodWithArgs = `\n(function %name%(%args%) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), %args%));\n }\n }\n return this;\n})\n`;\n\n var staticMethodWithArgs = `\n(function %name%(matrix, %args%) {\n var newMatrix = new this[Symbol.species](matrix);\n return newMatrix.%name%(%args%);\n})\n`;\n\n\n var inplaceMethodWithOneArgScalar = `\n(function %name%S(value) {\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), value));\n }\n }\n return this;\n})\n`;\n var inplaceMethodWithOneArgMatrix = `\n(function %name%M(matrix) {\n matrix = this.constructor.checkMatrix(matrix);\n checkDimensions(this, matrix);\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n})\n`;\n\n var inplaceMethodWithOneArg = `\n(function %name%(value) {\n if (typeof value === 'number') return this.%name%S(value);\n return this.%name%M(value);\n})\n`;\n\n var staticMethodWithOneArg = staticMethodWithArgs;\n\n var operators = [\n // Arithmetic operators\n ['+', 'add'],\n ['-', 'sub', 'subtract'],\n ['*', 'mul', 'multiply'],\n ['/', 'div', 'divide'],\n ['%', 'mod', 'modulus'],\n // Bitwise operators\n ['&', 'and'],\n ['|', 'or'],\n ['^', 'xor'],\n ['<<', 'leftShift'],\n ['>>', 'signPropagatingRightShift'],\n ['>>>', 'rightShift', 'zeroFillRightShift']\n ];\n\n var i;\n\n for (var operator of operators) {\n var inplaceOp = eval(fillTemplateFunction(inplaceOperator, {name: operator[1], op: operator[0]}));\n var inplaceOpS = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[1] + 'S', op: operator[0]}));\n var inplaceOpM = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[1] + 'M', op: operator[0]}));\n var staticOp = eval(fillTemplateFunction(staticOperator, {name: operator[1]}));\n for (i = 1; i < operator.length; i++) {\n Matrix.prototype[operator[i]] = inplaceOp;\n Matrix.prototype[operator[i] + 'S'] = inplaceOpS;\n Matrix.prototype[operator[i] + 'M'] = inplaceOpM;\n Matrix[operator[i]] = staticOp;\n }\n }\n\n var methods = [\n ['~', 'not']\n ];\n\n [\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n ].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n });\n\n for (var method of methods) {\n var inplaceMeth = eval(fillTemplateFunction(inplaceMethod, {name: method[1], method: method[0]}));\n var staticMeth = eval(fillTemplateFunction(staticMethod, {name: method[1]}));\n for (i = 1; i < method.length; i++) {\n Matrix.prototype[method[i]] = inplaceMeth;\n Matrix[method[i]] = staticMeth;\n }\n }\n\n var methodsWithArgs = [\n ['Math.pow', 1, 'pow']\n ];\n\n for (var methodWithArg of methodsWithArgs) {\n var args = 'arg0';\n for (i = 1; i < methodWithArg[1]; i++) {\n args += `, arg${i}`;\n }\n if (methodWithArg[1] !== 1) {\n var inplaceMethWithArgs = eval(fillTemplateFunction(inplaceMethodWithArgs, {\n name: methodWithArg[2],\n method: methodWithArg[0],\n args: args\n }));\n var staticMethWithArgs = eval(fillTemplateFunction(staticMethodWithArgs, {name: methodWithArg[2], args: args}));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;\n Matrix[methodWithArg[i]] = staticMethWithArgs;\n }\n } else {\n var tmplVar = {\n name: methodWithArg[2],\n args: args,\n method: methodWithArg[0]\n };\n var inplaceMethod2 = eval(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\n var inplaceMethodS = eval(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\n var inplaceMethodM = eval(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\n var staticMethod2 = eval(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\n for (i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethod2;\n Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM;\n Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS;\n Matrix[methodWithArg[i]] = staticMethod2;\n }\n }\n }\n\n function fillTemplateFunction(template, values) {\n for (var value in values) {\n template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]);\n }\n return template;\n }\n\n return Matrix;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/abstractMatrix.js\n// module id = 62\n// module chunks = 0","'use strict';\n\nvar Matrix = require('../matrix');\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs\nfunction LuDecomposition(matrix) {\n if (!(this instanceof LuDecomposition)) {\n return new LuDecomposition(matrix);\n }\n\n matrix = Matrix.Matrix.checkMatrix(matrix);\n\n var lu = matrix.clone(),\n rows = lu.rows,\n columns = lu.columns,\n pivotVector = new Array(rows),\n pivotSign = 1,\n i, j, k, p, s, t, v,\n LUrowi, LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Array(rows);\n\n for (j = 0; j < columns; j++) {\n\n for (i = 0; i < rows; i++) {\n LUcolj[i] = lu[i][j];\n }\n\n for (i = 0; i < rows; i++) {\n LUrowi = lu[i];\n kmax = Math.min(i, j);\n s = 0;\n for (k = 0; k < kmax; k++) {\n s += LUrowi[k] * LUcolj[k];\n }\n LUrowi[j] = LUcolj[i] -= s;\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[p][k];\n lu[p][k] = lu[j][k];\n lu[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[j][j] !== 0) {\n for (i = j + 1; i < rows; i++) {\n lu[i][j] /= lu[j][j];\n }\n }\n }\n\n this.LU = lu;\n this.pivotVector = pivotVector;\n this.pivotSign = pivotSign;\n}\n\nLuDecomposition.prototype = {\n isSingular: function () {\n var data = this.LU,\n col = data.columns;\n for (var j = 0; j < col; j++) {\n if (data[j][j] === 0) {\n return true;\n }\n }\n return false;\n },\n get determinant() {\n var data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n var determinant = this.pivotSign, col = data.columns;\n for (var j = 0; j < col; j++) {\n determinant *= data[j][j];\n }\n return determinant;\n },\n get lowerTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix.Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i > j) {\n X[i][j] = data[i][j];\n } else if (i === j) {\n X[i][j] = 1;\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get upperTriangularMatrix() {\n var data = this.LU,\n rows = data.rows,\n columns = data.columns,\n X = new Matrix.Matrix(rows, columns);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n if (i <= j) {\n X[i][j] = data[i][j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get pivotPermutationVector() {\n return this.pivotVector.slice();\n },\n solve: function (value) {\n value = Matrix.Matrix.checkMatrix(value);\n\n var lu = this.LU,\n rows = lu.rows;\n\n if (rows !== value.rows) {\n throw new Error('Invalid matrix dimensions');\n }\n if (this.isSingular()) {\n throw new Error('LU matrix is singular');\n }\n\n var count = value.columns;\n var X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n var columns = lu.columns;\n var i, j, k;\n\n for (k = 0; k < columns; k++) {\n for (i = k + 1; i < columns; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= lu[k][k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * lu[i][k];\n }\n }\n }\n return X;\n }\n};\n\nmodule.exports = LuDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/lu.js\n// module id = 63\n// module chunks = 0","'use strict';\n\nvar Matrix = require('../matrix');\nvar util = require('./util');\nvar hypotenuse = util.hypotenuse;\nvar getFilled2DArray = util.getFilled2DArray;\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs\nfunction SingularValueDecomposition(value, options) {\n if (!(this instanceof SingularValueDecomposition)) {\n return new SingularValueDecomposition(value, options);\n }\n value = Matrix.Matrix.checkMatrix(value);\n\n options = options || {};\n\n var m = value.rows,\n n = value.columns,\n nu = Math.min(m, n);\n\n var wantu = true, wantv = true;\n if (options.computeLeftSingularVectors === false) wantu = false;\n if (options.computeRightSingularVectors === false) wantv = false;\n var autoTranspose = options.autoTranspose === true;\n\n var swapped = false;\n var a;\n if (m < n) {\n if (!autoTranspose) {\n a = value.clone();\n // eslint-disable-next-line no-console\n console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose');\n } else {\n a = value.transpose();\n m = a.rows;\n n = a.columns;\n swapped = true;\n var aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n var s = new Array(Math.min(m + 1, n)),\n U = getFilled2DArray(m, nu, 0),\n V = getFilled2DArray(n, n, 0),\n e = new Array(n),\n work = new Array(m);\n\n var nct = Math.min(m - 1, n);\n var nrt = Math.max(0, Math.min(n - 2, m));\n\n var i, j, k, p, t, ks, f, cs, sn, max, kase,\n scale, sp, spm1, epm1, sk, ek, b, c, shift, g;\n\n for (k = 0, max = Math.max(nct, nrt); k < max; k++) {\n if (k < nct) {\n s[k] = 0;\n for (i = k; i < m; i++) {\n s[k] = hypotenuse(s[k], a[i][k]);\n }\n if (s[k] !== 0) {\n if (a[k][k] < 0) {\n s[k] = -s[k];\n }\n for (i = k; i < m; i++) {\n a[i][k] /= s[k];\n }\n a[k][k] += 1;\n }\n s[k] = -s[k];\n }\n\n for (j = k + 1; j < n; j++) {\n if ((k < nct) && (s[k] !== 0)) {\n t = 0;\n for (i = k; i < m; i++) {\n t += a[i][k] * a[i][j];\n }\n t = -t / a[k][k];\n for (i = k; i < m; i++) {\n a[i][j] += t * a[i][k];\n }\n }\n e[j] = a[k][j];\n }\n\n if (wantu && (k < nct)) {\n for (i = k; i < m; i++) {\n U[i][k] = a[i][k];\n }\n }\n\n if (k < nrt) {\n e[k] = 0;\n for (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 (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 (i = k + 1; i < m; i++) {\n work[i] = 0;\n }\n for (j = k + 1; j < n; j++) {\n for (i = k + 1; i < m; i++) {\n work[i] += e[j] * a[i][j];\n }\n }\n for (j = k + 1; j < n; j++) {\n t = -e[j] / e[k + 1];\n for (i = k + 1; i < m; i++) {\n a[i][j] += t * work[i];\n }\n }\n }\n if (wantv) {\n for (i = k + 1; i < n; i++) {\n V[i][k] = e[i];\n }\n }\n }\n }\n\n p = Math.min(n, m + 1);\n if (nct < n) {\n s[nct] = a[nct][nct];\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a[nrt][p - 1];\n }\n e[p - 1] = 0;\n\n if (wantu) {\n for (j = nct; j < nu; j++) {\n for (i = 0; i < m; i++) {\n U[i][j] = 0;\n }\n U[j][j] = 1;\n }\n for (k = nct - 1; k >= 0; k--) {\n if (s[k] !== 0) {\n for (j = k + 1; j < nu; j++) {\n t = 0;\n for (i = k; i < m; i++) {\n t += U[i][k] * U[i][j];\n }\n t = -t / U[k][k];\n for (i = k; i < m; i++) {\n U[i][j] += t * U[i][k];\n }\n }\n for (i = k; i < m; i++) {\n U[i][k] = -U[i][k];\n }\n U[k][k] = 1 + U[k][k];\n for (i = 0; i < k - 1; i++) {\n U[i][k] = 0;\n }\n } else {\n for (i = 0; i < m; i++) {\n U[i][k] = 0;\n }\n U[k][k] = 1;\n }\n }\n }\n\n if (wantv) {\n for (k = n - 1; k >= 0; k--) {\n if ((k < nrt) && (e[k] !== 0)) {\n for (j = k + 1; j < n; j++) {\n t = 0;\n for (i = k + 1; i < n; i++) {\n t += V[i][k] * V[i][j];\n }\n t = -t / V[k + 1][k];\n for (i = k + 1; i < n; i++) {\n V[i][j] += t * V[i][k];\n }\n }\n }\n for (i = 0; i < n; i++) {\n V[i][k] = 0;\n }\n V[k][k] = 1;\n }\n }\n\n var pp = p - 1,\n iter = 0,\n eps = Math.pow(2, -52);\n while (p > 0) {\n for (k = p - 2; k >= -1; k--) {\n if (k === -1) {\n break;\n }\n if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) {\n e[k] = 0;\n break;\n }\n }\n if (k === p - 2) {\n kase = 4;\n } else {\n for (ks = p - 1; ks >= k; ks--) {\n if (ks === k) {\n break;\n }\n t = (ks !== p ? Math.abs(e[ks]) : 0) + (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 f = e[p - 2];\n e[p - 2] = 0;\n for (j = p - 2; j >= k; j--) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][p - 1];\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\n V[i][j] = t;\n }\n }\n }\n break;\n }\n case 2 : {\n f = e[k - 1];\n e[k - 1] = 0;\n for (j = k; j < p; j++) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n sn = f / t;\n s[j] = t;\n f = -sn * e[j];\n e[j] = cs * e[j];\n if (wantu) {\n for (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][k - 1];\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\n U[i][j] = t;\n }\n }\n }\n break;\n }\n case 3 : {\n scale = Math.max(Math.max(Math.max(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]));\n sp = s[p - 1] / scale;\n spm1 = s[p - 2] / scale;\n epm1 = e[p - 2] / scale;\n sk = s[k] / scale;\n ek = e[k] / scale;\n b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\n c = (sp * epm1) * (sp * epm1);\n shift = 0;\n if ((b !== 0) || (c !== 0)) {\n shift = Math.sqrt(b * b + c);\n if (b < 0) {\n shift = -shift;\n }\n shift = c / (b + shift);\n }\n f = (sk + sp) * (sk - sp) + shift;\n g = sk * ek;\n for (j = k; j < p - 1; j++) {\n t = hypotenuse(f, g);\n cs = f / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][j + 1];\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\n V[i][j] = t;\n }\n }\n t = hypotenuse(f, g);\n 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 (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][j + 1];\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\n U[i][j] = t;\n }\n }\n }\n e[p - 2] = f;\n iter = iter + 1;\n break;\n }\n case 4: {\n if (s[k] <= 0) {\n s[k] = (s[k] < 0 ? -s[k] : 0);\n if (wantv) {\n for (i = 0; i <= pp; i++) {\n V[i][k] = -V[i][k];\n }\n }\n }\n while (k < pp) {\n if (s[k] >= s[k + 1]) {\n break;\n }\n t = s[k];\n s[k] = s[k + 1];\n s[k + 1] = t;\n if (wantv && (k < n - 1)) {\n for (i = 0; i < n; i++) {\n t = V[i][k + 1];\n V[i][k + 1] = V[i][k];\n V[i][k] = t;\n }\n }\n if (wantu && (k < m - 1)) {\n for (i = 0; i < m; i++) {\n t = U[i][k + 1];\n U[i][k + 1] = U[i][k];\n U[i][k] = t;\n }\n }\n k++;\n }\n iter = 0;\n p--;\n break;\n }\n // no default\n }\n }\n\n if (swapped) {\n var tmp = V;\n V = U;\n U = tmp;\n }\n\n this.m = m;\n this.n = n;\n this.s = s;\n this.U = U;\n this.V = V;\n}\n\nSingularValueDecomposition.prototype = {\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n },\n get norm2() {\n return this.s[0];\n },\n get rank() {\n var eps = Math.pow(2, -52),\n tol = Math.max(this.m, this.n) * this.s[0] * eps,\n r = 0,\n s = this.s;\n for (var i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n },\n get diagonal() {\n return this.s;\n },\n // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\n get threshold() {\n return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0];\n },\n get leftSingularVectors() {\n if (!Matrix.Matrix.isMatrix(this.U)) {\n this.U = new Matrix.Matrix(this.U);\n }\n return this.U;\n },\n get rightSingularVectors() {\n if (!Matrix.Matrix.isMatrix(this.V)) {\n this.V = new Matrix.Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n return Matrix.Matrix.diag(this.s);\n },\n solve: function (value) {\n\n var Y = value,\n e = this.threshold,\n scols = this.s.length,\n Ls = Matrix.Matrix.zeros(scols, scols),\n i;\n\n for (i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls[i][i] = 0;\n } else {\n Ls[i][i] = 1 / this.s[i];\n }\n }\n\n var U = this.U;\n var V = this.rightSingularVectors;\n\n var VL = V.mmul(Ls),\n vrows = V.rows,\n urows = U.length,\n VLU = Matrix.Matrix.zeros(vrows, urows),\n j, k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < scols; k++) {\n sum += VL[i][k] * U[j][k];\n }\n VLU[i][j] = sum;\n }\n }\n\n return VLU.mmul(Y);\n },\n solveForDiagonal: function (value) {\n return this.solve(Matrix.Matrix.diag(value));\n },\n inverse: function () {\n var V = this.V;\n var e = this.threshold,\n vrows = V.length,\n vcols = V[0].length,\n X = new Matrix.Matrix(vrows, this.s.length),\n i, j;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < vcols; j++) {\n if (Math.abs(this.s[j]) > e) {\n X[i][j] = V[i][j] / this.s[j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n\n var U = this.U;\n\n var urows = U.length,\n ucols = U[0].length,\n Y = new Matrix.Matrix(vrows, urows),\n k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < ucols; k++) {\n sum += X[i][k] * U[j][k];\n }\n Y[i][j] = sum;\n }\n }\n\n return Y;\n }\n};\n\nmodule.exports = SingularValueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/svd.js\n// module id = 64\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\nvar Stat = require('ml-stat');\n\nmodule.exports.NaiveBayes = NaiveBayes;\nmodule.exports.separateClasses = separateClasses;\n\n/**\n * Constructor for the Naive Bayes classifier, the parameters here is just for loading purposes.\n *\n * @param reload\n * @param model\n * @constructor\n */\nfunction NaiveBayes(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 trainingSet\n * @param trainingLabels\n */\nNaiveBayes.prototype.train = function (trainingSet, trainingLabels) {\n var C1 = Math.sqrt(2*Math.PI); // constant to precalculate the squared root\n if(!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet);\n else trainingSet = trainingSet.clone();\n\n if(trainingSet.rows !== trainingLabels.length)\n throw new RangeError(\"the size of the training set and the training labels must be the same.\");\n\n var separatedClasses = separateClasses(trainingSet, trainingLabels);\n var calculateProbabilities = new Array(separatedClasses.length);\n this.means = new Array(separatedClasses.length);\n for(var i = 0; i < separatedClasses.length; ++i) {\n var means = Stat.matrix.mean(separatedClasses[i]);\n var std = Stat.matrix.standardDeviation(separatedClasses[i], means);\n\n var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows);\n calculateProbabilities[i] = new Array(means.length + 1);\n\n calculateProbabilities[i][0] = logPriorProbability;\n for(var j = 1; j < means.length + 1; ++j) {\n var currentStd = std[j - 1];\n calculateProbabilities[i][j] = [(1 / (C1 * currentStd)), -2*currentStd*currentStd];\n }\n\n this.means[i] = means;\n }\n\n this.calculateProbabilities = calculateProbabilities;\n};\n\n/**\n * function that predicts each row of the dataset (must be a matrix).\n *\n * @param dataset\n * @returns {Array}\n */\nNaiveBayes.prototype.predict = function (dataset) {\n if(dataset[0].length === this.calculateProbabilities[0].length)\n throw new RangeError('the dataset must have the same features as the training set');\n\n var predictions = new Array(dataset.length);\n\n for(var i = 0; i < predictions.length; ++i) {\n predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities);\n }\n\n return predictions;\n};\n\n/**\n * Function the retrieves a prediction with one case.\n *\n * @param currentCase\n * @param mean - Precalculated means of each class trained\n * @param classes - Precalculated value of each class (Prior probability and probability function of each feature)\n * @returns {number}\n */\nfunction getCurrentClass(currentCase, mean, classes) {\n var maxProbability = 0;\n var predictedClass = -1;\n\n // going through all precalculated values for the classes\n for(var i = 0; i < classes.length; ++i) {\n var currentProbability = classes[i][0]; // initialize with the prior probability\n for(var j = 1; j < classes[0][1].length + 1; ++j) {\n currentProbability += calculateLogProbability(currentCase[j - 1], mean[i][j - 1], classes[i][j][0], classes[i][j][1]);\n }\n\n currentProbability = Math.exp(currentProbability);\n if(currentProbability > maxProbability) {\n maxProbability = currentProbability;\n predictedClass = i;\n }\n }\n\n return predictedClass;\n}\n\n/**\n * Function that export the NaiveBayes model.\n * @returns {{modelName: string, means: *, calculateProbabilities: *}}\n */\nNaiveBayes.prototype.export = function () {\n return {\n modelName: \"NaiveBayes\",\n means: this.means,\n calculateProbabilities: this.calculateProbabilities\n };\n};\n\n/**\n * Function that create a Naive Bayes classifier with the given model.\n * @param model\n * @returns {NaiveBayes}\n */\nNaiveBayes.load = function (model) {\n if(model.modelName !== 'NaiveBayes')\n throw new RangeError(\"The given model is invalid!\");\n\n return new NaiveBayes(true, model);\n};\n\n/**\n * function that retrieves the probability of the feature given the class.\n * @param value - value of the feature.\n * @param mean - mean of the feature for the given class.\n * @param C1 - precalculated value of (1 / (sqrt(2*pi) * std)).\n * @param C2 - precalculated value of (2 * std^2) for the denominator of the exponential.\n * @returns {number}\n */\nfunction calculateLogProbability(value, mean, C1, C2) {\n var value = value - mean;\n return Math.log(C1 * Math.exp((value * value) / C2))\n}\n\n/**\n * Function that retuns an array of matrices of the cases that belong to each class.\n * @param X - dataset\n * @param y - predictions\n * @returns {Array}\n */\nfunction separateClasses(X, y) {\n var features = X.columns;\n\n var classes = 0;\n var totalPerClasses = new Array(100); // max upperbound of classes\n for (var i = 0; i < y.length; i++) {\n if(totalPerClasses[y[i]] === undefined) {\n totalPerClasses[y[i]] = 0;\n classes++;\n }\n totalPerClasses[y[i]]++;\n }\n var separatedClasses = new Array(classes);\n var currentIndex = new Array(classes);\n for(i = 0; i < classes; ++i) {\n separatedClasses[i] = new Matrix(totalPerClasses[i], features);\n currentIndex[i] = 0;\n }\n for(i = 0; i < X.rows; ++i) {\n separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i));\n currentIndex[y[i]]++;\n }\n return separatedClasses;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-naivebayes/src/naiveBayes.js\n// module id = 65\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse} from './util';\n\n//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\nfunction QrDecomposition(value) {\n if (!(this instanceof QrDecomposition)) {\n return new QrDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n\n var qr = value.clone(),\n m = value.rows,\n n = value.columns,\n rdiag = new Array(n),\n i, j, k, s;\n\n for (k = 0; k < n; k++) {\n var nrm = 0;\n for (i = k; i < m; i++) {\n nrm = hypotenuse(nrm, qr[i][k]);\n }\n if (nrm !== 0) {\n if (qr[k][k] < 0) {\n nrm = -nrm;\n }\n for (i = k; i < m; i++) {\n qr[i][k] /= nrm;\n }\n qr[k][k] += 1;\n for (j = k + 1; j < n; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * qr[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n qr[i][j] += s * qr[i][k];\n }\n }\n }\n rdiag[k] = -nrm;\n }\n\n this.QR = qr;\n this.Rdiag = rdiag;\n}\n\nQrDecomposition.prototype = {\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var qr = this.QR,\n m = qr.rows;\n\n if (value.rows !== m) {\n throw new Error('Matrix row dimensions must agree');\n }\n if (!this.isFullRank()) {\n throw new Error('Matrix is rank deficient');\n }\n\n var count = value.columns;\n var X = value.clone();\n var n = qr.columns;\n var i, j, k, s;\n\n for (k = 0; k < n; k++) {\n for (j = 0; j < count; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * X[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= this.Rdiag[k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * qr[i][k];\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n },\n isFullRank: function () {\n var columns = this.QR.columns;\n for (var i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n },\n get upperTriangularMatrix() {\n var qr = this.QR,\n n = qr.columns,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X[i][j] = qr[i][j];\n } else if (i === j) {\n X[i][j] = this.Rdiag[i];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get orthogonalMatrix() {\n var qr = this.QR,\n rows = qr.rows,\n columns = qr.columns,\n X = new Matrix(rows, columns),\n i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X[i][k] = 0;\n }\n X[k][k] = 1;\n for (j = k; j < columns; j++) {\n if (qr[k][k] !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr[i][k] * X[i][j];\n }\n\n s = -s / qr[k][k];\n\n for (i = k; i < rows; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n }\n return X;\n }\n};\n\nexport default QrDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/dc/qr.js\n// module id = 66\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse, getFilled2DArray} from './util';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs\nfunction SingularValueDecomposition(value, options) {\n if (!(this instanceof SingularValueDecomposition)) {\n return new SingularValueDecomposition(value, options);\n }\n value = Matrix.checkMatrix(value);\n\n options = options || {};\n\n var m = value.rows,\n n = value.columns,\n nu = Math.min(m, n);\n\n var wantu = true, wantv = true;\n if (options.computeLeftSingularVectors === false) wantu = false;\n if (options.computeRightSingularVectors === false) wantv = false;\n var autoTranspose = options.autoTranspose === true;\n\n var swapped = false;\n var a;\n if (m < n) {\n if (!autoTranspose) {\n a = value.clone();\n // eslint-disable-next-line no-console\n console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose');\n } else {\n a = value.transpose();\n m = a.rows;\n n = a.columns;\n swapped = true;\n var aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n var s = new Array(Math.min(m + 1, n)),\n U = getFilled2DArray(m, nu, 0),\n V = getFilled2DArray(n, n, 0),\n e = new Array(n),\n work = new Array(m);\n\n var nct = Math.min(m - 1, n);\n var nrt = Math.max(0, Math.min(n - 2, m));\n\n var i, j, k, p, t, ks, f, cs, sn, max, kase,\n scale, sp, spm1, epm1, sk, ek, b, c, shift, g;\n\n for (k = 0, max = Math.max(nct, nrt); k < max; k++) {\n if (k < nct) {\n s[k] = 0;\n for (i = k; i < m; i++) {\n s[k] = hypotenuse(s[k], a[i][k]);\n }\n if (s[k] !== 0) {\n if (a[k][k] < 0) {\n s[k] = -s[k];\n }\n for (i = k; i < m; i++) {\n a[i][k] /= s[k];\n }\n a[k][k] += 1;\n }\n s[k] = -s[k];\n }\n\n for (j = k + 1; j < n; j++) {\n if ((k < nct) && (s[k] !== 0)) {\n t = 0;\n for (i = k; i < m; i++) {\n t += a[i][k] * a[i][j];\n }\n t = -t / a[k][k];\n for (i = k; i < m; i++) {\n a[i][j] += t * a[i][k];\n }\n }\n e[j] = a[k][j];\n }\n\n if (wantu && (k < nct)) {\n for (i = k; i < m; i++) {\n U[i][k] = a[i][k];\n }\n }\n\n if (k < nrt) {\n e[k] = 0;\n for (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 (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 (i = k + 1; i < m; i++) {\n work[i] = 0;\n }\n for (j = k + 1; j < n; j++) {\n for (i = k + 1; i < m; i++) {\n work[i] += e[j] * a[i][j];\n }\n }\n for (j = k + 1; j < n; j++) {\n t = -e[j] / e[k + 1];\n for (i = k + 1; i < m; i++) {\n a[i][j] += t * work[i];\n }\n }\n }\n if (wantv) {\n for (i = k + 1; i < n; i++) {\n V[i][k] = e[i];\n }\n }\n }\n }\n\n p = Math.min(n, m + 1);\n if (nct < n) {\n s[nct] = a[nct][nct];\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a[nrt][p - 1];\n }\n e[p - 1] = 0;\n\n if (wantu) {\n for (j = nct; j < nu; j++) {\n for (i = 0; i < m; i++) {\n U[i][j] = 0;\n }\n U[j][j] = 1;\n }\n for (k = nct - 1; k >= 0; k--) {\n if (s[k] !== 0) {\n for (j = k + 1; j < nu; j++) {\n t = 0;\n for (i = k; i < m; i++) {\n t += U[i][k] * U[i][j];\n }\n t = -t / U[k][k];\n for (i = k; i < m; i++) {\n U[i][j] += t * U[i][k];\n }\n }\n for (i = k; i < m; i++) {\n U[i][k] = -U[i][k];\n }\n U[k][k] = 1 + U[k][k];\n for (i = 0; i < k - 1; i++) {\n U[i][k] = 0;\n }\n } else {\n for (i = 0; i < m; i++) {\n U[i][k] = 0;\n }\n U[k][k] = 1;\n }\n }\n }\n\n if (wantv) {\n for (k = n - 1; k >= 0; k--) {\n if ((k < nrt) && (e[k] !== 0)) {\n for (j = k + 1; j < n; j++) {\n t = 0;\n for (i = k + 1; i < n; i++) {\n t += V[i][k] * V[i][j];\n }\n t = -t / V[k + 1][k];\n for (i = k + 1; i < n; i++) {\n V[i][j] += t * V[i][k];\n }\n }\n }\n for (i = 0; i < n; i++) {\n V[i][k] = 0;\n }\n V[k][k] = 1;\n }\n }\n\n var pp = p - 1,\n iter = 0,\n eps = Math.pow(2, -52);\n while (p > 0) {\n for (k = p - 2; k >= -1; k--) {\n if (k === -1) {\n break;\n }\n if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) {\n e[k] = 0;\n break;\n }\n }\n if (k === p - 2) {\n kase = 4;\n } else {\n for (ks = p - 1; ks >= k; ks--) {\n if (ks === k) {\n break;\n }\n t = (ks !== p ? Math.abs(e[ks]) : 0) + (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 f = e[p - 2];\n e[p - 2] = 0;\n for (j = p - 2; j >= k; j--) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][p - 1];\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\n V[i][j] = t;\n }\n }\n }\n break;\n }\n case 2 : {\n f = e[k - 1];\n e[k - 1] = 0;\n for (j = k; j < p; j++) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n sn = f / t;\n s[j] = t;\n f = -sn * e[j];\n e[j] = cs * e[j];\n if (wantu) {\n for (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][k - 1];\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\n U[i][j] = t;\n }\n }\n }\n break;\n }\n case 3 : {\n scale = Math.max(Math.max(Math.max(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]));\n sp = s[p - 1] / scale;\n spm1 = s[p - 2] / scale;\n epm1 = e[p - 2] / scale;\n sk = s[k] / scale;\n ek = e[k] / scale;\n b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\n c = (sp * epm1) * (sp * epm1);\n shift = 0;\n if ((b !== 0) || (c !== 0)) {\n shift = Math.sqrt(b * b + c);\n if (b < 0) {\n shift = -shift;\n }\n shift = c / (b + shift);\n }\n f = (sk + sp) * (sk - sp) + shift;\n g = sk * ek;\n for (j = k; j < p - 1; j++) {\n t = hypotenuse(f, g);\n cs = f / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][j + 1];\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\n V[i][j] = t;\n }\n }\n t = hypotenuse(f, g);\n 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 (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][j + 1];\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\n U[i][j] = t;\n }\n }\n }\n e[p - 2] = f;\n iter = iter + 1;\n break;\n }\n case 4: {\n if (s[k] <= 0) {\n s[k] = (s[k] < 0 ? -s[k] : 0);\n if (wantv) {\n for (i = 0; i <= pp; i++) {\n V[i][k] = -V[i][k];\n }\n }\n }\n while (k < pp) {\n if (s[k] >= s[k + 1]) {\n break;\n }\n t = s[k];\n s[k] = s[k + 1];\n s[k + 1] = t;\n if (wantv && (k < n - 1)) {\n for (i = 0; i < n; i++) {\n t = V[i][k + 1];\n V[i][k + 1] = V[i][k];\n V[i][k] = t;\n }\n }\n if (wantu && (k < m - 1)) {\n for (i = 0; i < m; i++) {\n t = U[i][k + 1];\n U[i][k + 1] = U[i][k];\n U[i][k] = t;\n }\n }\n k++;\n }\n iter = 0;\n p--;\n break;\n }\n // no default\n }\n }\n\n if (swapped) {\n var tmp = V;\n V = U;\n U = tmp;\n }\n\n this.m = m;\n this.n = n;\n this.s = s;\n this.U = U;\n this.V = V;\n}\n\nSingularValueDecomposition.prototype = {\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n },\n get norm2() {\n return this.s[0];\n },\n get rank() {\n var eps = Math.pow(2, -52),\n tol = Math.max(this.m, this.n) * this.s[0] * eps,\n r = 0,\n s = this.s;\n for (var i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n },\n get diagonal() {\n return this.s;\n },\n // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\n get threshold() {\n return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0];\n },\n get leftSingularVectors() {\n if (!Matrix.isMatrix(this.U)) {\n this.U = new Matrix(this.U);\n }\n return this.U;\n },\n get rightSingularVectors() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n },\n solve: function (value) {\n\n var Y = value,\n e = this.threshold,\n scols = this.s.length,\n Ls = Matrix.zeros(scols, scols),\n i;\n\n for (i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls[i][i] = 0;\n } else {\n Ls[i][i] = 1 / this.s[i];\n }\n }\n\n var U = this.U;\n var V = this.rightSingularVectors;\n\n var VL = V.mmul(Ls),\n vrows = V.rows,\n urows = U.length,\n VLU = Matrix.zeros(vrows, urows),\n j, k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < scols; k++) {\n sum += VL[i][k] * U[j][k];\n }\n VLU[i][j] = sum;\n }\n }\n\n return VLU.mmul(Y);\n },\n solveForDiagonal: function (value) {\n return this.solve(Matrix.diag(value));\n },\n inverse: function () {\n var V = this.V;\n var e = this.threshold,\n vrows = V.length,\n vcols = V[0].length,\n X = new Matrix(vrows, this.s.length),\n i, j;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < vcols; j++) {\n if (Math.abs(this.s[j]) > e) {\n X[i][j] = V[i][j] / this.s[j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n\n var U = this.U;\n\n var urows = U.length,\n ucols = U[0].length,\n Y = new Matrix(vrows, urows),\n k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < ucols; k++) {\n sum += X[i][k] * U[j][k];\n }\n Y[i][j] = sum;\n }\n }\n\n return Y;\n }\n};\n\nexport default SingularValueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/dc/svd.js\n// module id = 67\n// module chunks = 0","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport Matrix, {solve} from 'ml-matrix';\n\nexport default class PolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y, degree);\n }\n }\n\n _predict(x) {\n let y = 0;\n for (let k = 0; k < this.powers.length; k++) {\n y += this.coefficients[k] * Math.pow(x, this.powers[k]);\n }\n return y;\n }\n\n toJSON() {\n return {\n name: 'polynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'polynomialRegression') {\n throw new TypeError('not a polynomial regression model');\n }\n return new PolynomialRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y, degree) {\n const n = x.length;\n let powers;\n if (Array.isArray(degree)) {\n powers = degree;\n degree = powers.length;\n } else {\n degree++;\n powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n }\n const F = new Matrix(n, degree);\n const Y = new Matrix([y]);\n for (let k = 0; k < degree; k++) {\n for (let i = 0; i < n; i++) {\n if (powers[k] === 0) {\n F[i][k] = 1;\n } else {\n F[i][k] = Math.pow(x[i], powers[k]);\n }\n }\n }\n\n const FT = F.transposeView();\n const A = FT.mmul(F);\n const B = FT.mmul(Y.transposeView());\n\n pr.degree = degree - 1;\n pr.powers = powers;\n pr.coefficients = solve(A, B).to1DArray();\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/src/index.js\n// module id = 68\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse} from './util';\n\n//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\nfunction QrDecomposition(value) {\n if (!(this instanceof QrDecomposition)) {\n return new QrDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n\n var qr = value.clone(),\n m = value.rows,\n n = value.columns,\n rdiag = new Array(n),\n i, j, k, s;\n\n for (k = 0; k < n; k++) {\n var nrm = 0;\n for (i = k; i < m; i++) {\n nrm = hypotenuse(nrm, qr[i][k]);\n }\n if (nrm !== 0) {\n if (qr[k][k] < 0) {\n nrm = -nrm;\n }\n for (i = k; i < m; i++) {\n qr[i][k] /= nrm;\n }\n qr[k][k] += 1;\n for (j = k + 1; j < n; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * qr[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n qr[i][j] += s * qr[i][k];\n }\n }\n }\n rdiag[k] = -nrm;\n }\n\n this.QR = qr;\n this.Rdiag = rdiag;\n}\n\nQrDecomposition.prototype = {\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var qr = this.QR,\n m = qr.rows;\n\n if (value.rows !== m) {\n throw new Error('Matrix row dimensions must agree');\n }\n if (!this.isFullRank()) {\n throw new Error('Matrix is rank deficient');\n }\n\n var count = value.columns;\n var X = value.clone();\n var n = qr.columns;\n var i, j, k, s;\n\n for (k = 0; k < n; k++) {\n for (j = 0; j < count; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * X[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= this.Rdiag[k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * qr[i][k];\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n },\n isFullRank: function () {\n var columns = this.QR.columns;\n for (var i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n },\n get upperTriangularMatrix() {\n var qr = this.QR,\n n = qr.columns,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X[i][j] = qr[i][j];\n } else if (i === j) {\n X[i][j] = this.Rdiag[i];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get orthogonalMatrix() {\n var qr = this.QR,\n rows = qr.rows,\n columns = qr.columns,\n X = new Matrix(rows, columns),\n i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X[i][k] = 0;\n }\n X[k][k] = 1;\n for (j = k; j < columns; j++) {\n if (qr[k][k] !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr[i][k] * X[i][j];\n }\n\n s = -s / qr[k][k];\n\n for (i = k; i < rows; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n }\n return X;\n }\n};\n\nexport default QrDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/qr.js\n// module id = 69\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse, getFilled2DArray} from './util';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs\nfunction SingularValueDecomposition(value, options) {\n if (!(this instanceof SingularValueDecomposition)) {\n return new SingularValueDecomposition(value, options);\n }\n value = Matrix.checkMatrix(value);\n\n options = options || {};\n\n var m = value.rows,\n n = value.columns,\n nu = Math.min(m, n);\n\n var wantu = true, wantv = true;\n if (options.computeLeftSingularVectors === false) wantu = false;\n if (options.computeRightSingularVectors === false) wantv = false;\n var autoTranspose = options.autoTranspose === true;\n\n var swapped = false;\n var a;\n if (m < n) {\n if (!autoTranspose) {\n a = value.clone();\n // eslint-disable-next-line no-console\n console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose');\n } else {\n a = value.transpose();\n m = a.rows;\n n = a.columns;\n swapped = true;\n var aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n var s = new Array(Math.min(m + 1, n)),\n U = getFilled2DArray(m, nu, 0),\n V = getFilled2DArray(n, n, 0),\n e = new Array(n),\n work = new Array(m);\n\n var nct = Math.min(m - 1, n);\n var nrt = Math.max(0, Math.min(n - 2, m));\n\n var i, j, k, p, t, ks, f, cs, sn, max, kase,\n scale, sp, spm1, epm1, sk, ek, b, c, shift, g;\n\n for (k = 0, max = Math.max(nct, nrt); k < max; k++) {\n if (k < nct) {\n s[k] = 0;\n for (i = k; i < m; i++) {\n s[k] = hypotenuse(s[k], a[i][k]);\n }\n if (s[k] !== 0) {\n if (a[k][k] < 0) {\n s[k] = -s[k];\n }\n for (i = k; i < m; i++) {\n a[i][k] /= s[k];\n }\n a[k][k] += 1;\n }\n s[k] = -s[k];\n }\n\n for (j = k + 1; j < n; j++) {\n if ((k < nct) && (s[k] !== 0)) {\n t = 0;\n for (i = k; i < m; i++) {\n t += a[i][k] * a[i][j];\n }\n t = -t / a[k][k];\n for (i = k; i < m; i++) {\n a[i][j] += t * a[i][k];\n }\n }\n e[j] = a[k][j];\n }\n\n if (wantu && (k < nct)) {\n for (i = k; i < m; i++) {\n U[i][k] = a[i][k];\n }\n }\n\n if (k < nrt) {\n e[k] = 0;\n for (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 (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 (i = k + 1; i < m; i++) {\n work[i] = 0;\n }\n for (j = k + 1; j < n; j++) {\n for (i = k + 1; i < m; i++) {\n work[i] += e[j] * a[i][j];\n }\n }\n for (j = k + 1; j < n; j++) {\n t = -e[j] / e[k + 1];\n for (i = k + 1; i < m; i++) {\n a[i][j] += t * work[i];\n }\n }\n }\n if (wantv) {\n for (i = k + 1; i < n; i++) {\n V[i][k] = e[i];\n }\n }\n }\n }\n\n p = Math.min(n, m + 1);\n if (nct < n) {\n s[nct] = a[nct][nct];\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a[nrt][p - 1];\n }\n e[p - 1] = 0;\n\n if (wantu) {\n for (j = nct; j < nu; j++) {\n for (i = 0; i < m; i++) {\n U[i][j] = 0;\n }\n U[j][j] = 1;\n }\n for (k = nct - 1; k >= 0; k--) {\n if (s[k] !== 0) {\n for (j = k + 1; j < nu; j++) {\n t = 0;\n for (i = k; i < m; i++) {\n t += U[i][k] * U[i][j];\n }\n t = -t / U[k][k];\n for (i = k; i < m; i++) {\n U[i][j] += t * U[i][k];\n }\n }\n for (i = k; i < m; i++) {\n U[i][k] = -U[i][k];\n }\n U[k][k] = 1 + U[k][k];\n for (i = 0; i < k - 1; i++) {\n U[i][k] = 0;\n }\n } else {\n for (i = 0; i < m; i++) {\n U[i][k] = 0;\n }\n U[k][k] = 1;\n }\n }\n }\n\n if (wantv) {\n for (k = n - 1; k >= 0; k--) {\n if ((k < nrt) && (e[k] !== 0)) {\n for (j = k + 1; j < n; j++) {\n t = 0;\n for (i = k + 1; i < n; i++) {\n t += V[i][k] * V[i][j];\n }\n t = -t / V[k + 1][k];\n for (i = k + 1; i < n; i++) {\n V[i][j] += t * V[i][k];\n }\n }\n }\n for (i = 0; i < n; i++) {\n V[i][k] = 0;\n }\n V[k][k] = 1;\n }\n }\n\n var pp = p - 1,\n iter = 0,\n eps = Math.pow(2, -52);\n while (p > 0) {\n for (k = p - 2; k >= -1; k--) {\n if (k === -1) {\n break;\n }\n if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) {\n e[k] = 0;\n break;\n }\n }\n if (k === p - 2) {\n kase = 4;\n } else {\n for (ks = p - 1; ks >= k; ks--) {\n if (ks === k) {\n break;\n }\n t = (ks !== p ? Math.abs(e[ks]) : 0) + (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 f = e[p - 2];\n e[p - 2] = 0;\n for (j = p - 2; j >= k; j--) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][p - 1];\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\n V[i][j] = t;\n }\n }\n }\n break;\n }\n case 2 : {\n f = e[k - 1];\n e[k - 1] = 0;\n for (j = k; j < p; j++) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n sn = f / t;\n s[j] = t;\n f = -sn * e[j];\n e[j] = cs * e[j];\n if (wantu) {\n for (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][k - 1];\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\n U[i][j] = t;\n }\n }\n }\n break;\n }\n case 3 : {\n scale = Math.max(Math.max(Math.max(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]));\n sp = s[p - 1] / scale;\n spm1 = s[p - 2] / scale;\n epm1 = e[p - 2] / scale;\n sk = s[k] / scale;\n ek = e[k] / scale;\n b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\n c = (sp * epm1) * (sp * epm1);\n shift = 0;\n if ((b !== 0) || (c !== 0)) {\n shift = Math.sqrt(b * b + c);\n if (b < 0) {\n shift = -shift;\n }\n shift = c / (b + shift);\n }\n f = (sk + sp) * (sk - sp) + shift;\n g = sk * ek;\n for (j = k; j < p - 1; j++) {\n t = hypotenuse(f, g);\n cs = f / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][j + 1];\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\n V[i][j] = t;\n }\n }\n t = hypotenuse(f, g);\n 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 (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][j + 1];\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\n U[i][j] = t;\n }\n }\n }\n e[p - 2] = f;\n iter = iter + 1;\n break;\n }\n case 4: {\n if (s[k] <= 0) {\n s[k] = (s[k] < 0 ? -s[k] : 0);\n if (wantv) {\n for (i = 0; i <= pp; i++) {\n V[i][k] = -V[i][k];\n }\n }\n }\n while (k < pp) {\n if (s[k] >= s[k + 1]) {\n break;\n }\n t = s[k];\n s[k] = s[k + 1];\n s[k + 1] = t;\n if (wantv && (k < n - 1)) {\n for (i = 0; i < n; i++) {\n t = V[i][k + 1];\n V[i][k + 1] = V[i][k];\n V[i][k] = t;\n }\n }\n if (wantu && (k < m - 1)) {\n for (i = 0; i < m; i++) {\n t = U[i][k + 1];\n U[i][k + 1] = U[i][k];\n U[i][k] = t;\n }\n }\n k++;\n }\n iter = 0;\n p--;\n break;\n }\n // no default\n }\n }\n\n if (swapped) {\n var tmp = V;\n V = U;\n U = tmp;\n }\n\n this.m = m;\n this.n = n;\n this.s = s;\n this.U = U;\n this.V = V;\n}\n\nSingularValueDecomposition.prototype = {\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n },\n get norm2() {\n return this.s[0];\n },\n get rank() {\n var eps = Math.pow(2, -52),\n tol = Math.max(this.m, this.n) * this.s[0] * eps,\n r = 0,\n s = this.s;\n for (var i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n },\n get diagonal() {\n return this.s;\n },\n // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\n get threshold() {\n return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0];\n },\n get leftSingularVectors() {\n if (!Matrix.isMatrix(this.U)) {\n this.U = new Matrix(this.U);\n }\n return this.U;\n },\n get rightSingularVectors() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n },\n solve: function (value) {\n\n var Y = value,\n e = this.threshold,\n scols = this.s.length,\n Ls = Matrix.zeros(scols, scols),\n i;\n\n for (i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls[i][i] = 0;\n } else {\n Ls[i][i] = 1 / this.s[i];\n }\n }\n\n var U = this.U;\n var V = this.rightSingularVectors;\n\n var VL = V.mmul(Ls),\n vrows = V.rows,\n urows = U.length,\n VLU = Matrix.zeros(vrows, urows),\n j, k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < scols; k++) {\n sum += VL[i][k] * U[j][k];\n }\n VLU[i][j] = sum;\n }\n }\n\n return VLU.mmul(Y);\n },\n solveForDiagonal: function (value) {\n return this.solve(Matrix.diag(value));\n },\n inverse: function () {\n var V = this.V;\n var e = this.threshold,\n vrows = V.length,\n vcols = V[0].length,\n X = new Matrix(vrows, this.s.length),\n i, j;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < vcols; j++) {\n if (Math.abs(this.s[j]) > e) {\n X[i][j] = V[i][j] / this.s[j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n\n var U = this.U;\n\n var urows = U.length,\n ucols = U[0].length,\n Y = new Matrix(vrows, urows),\n k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < ucols; k++) {\n sum += X[i][k] * U[j][k];\n }\n Y[i][j] = sum;\n }\n }\n\n return Y;\n }\n};\n\nexport default SingularValueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/svd.js\n// module id = 70\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse} from './util';\n\n//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\nfunction QrDecomposition(value) {\n if (!(this instanceof QrDecomposition)) {\n return new QrDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n\n var qr = value.clone(),\n m = value.rows,\n n = value.columns,\n rdiag = new Array(n),\n i, j, k, s;\n\n for (k = 0; k < n; k++) {\n var nrm = 0;\n for (i = k; i < m; i++) {\n nrm = hypotenuse(nrm, qr[i][k]);\n }\n if (nrm !== 0) {\n if (qr[k][k] < 0) {\n nrm = -nrm;\n }\n for (i = k; i < m; i++) {\n qr[i][k] /= nrm;\n }\n qr[k][k] += 1;\n for (j = k + 1; j < n; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * qr[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n qr[i][j] += s * qr[i][k];\n }\n }\n }\n rdiag[k] = -nrm;\n }\n\n this.QR = qr;\n this.Rdiag = rdiag;\n}\n\nQrDecomposition.prototype = {\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var qr = this.QR,\n m = qr.rows;\n\n if (value.rows !== m) {\n throw new Error('Matrix row dimensions must agree');\n }\n if (!this.isFullRank()) {\n throw new Error('Matrix is rank deficient');\n }\n\n var count = value.columns;\n var X = value.clone();\n var n = qr.columns;\n var i, j, k, s;\n\n for (k = 0; k < n; k++) {\n for (j = 0; j < count; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * X[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= this.Rdiag[k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * qr[i][k];\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n },\n isFullRank: function () {\n var columns = this.QR.columns;\n for (var i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n },\n get upperTriangularMatrix() {\n var qr = this.QR,\n n = qr.columns,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X[i][j] = qr[i][j];\n } else if (i === j) {\n X[i][j] = this.Rdiag[i];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get orthogonalMatrix() {\n var qr = this.QR,\n rows = qr.rows,\n columns = qr.columns,\n X = new Matrix(rows, columns),\n i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X[i][k] = 0;\n }\n X[k][k] = 1;\n for (j = k; j < columns; j++) {\n if (qr[k][k] !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr[i][k] * X[i][j];\n }\n\n s = -s / qr[k][k];\n\n for (i = k; i < rows; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n }\n return X;\n }\n};\n\nexport default QrDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/dc/qr.js\n// module id = 71\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse, getFilled2DArray} from './util';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs\nfunction SingularValueDecomposition(value, options) {\n if (!(this instanceof SingularValueDecomposition)) {\n return new SingularValueDecomposition(value, options);\n }\n value = Matrix.checkMatrix(value);\n\n options = options || {};\n\n var m = value.rows,\n n = value.columns,\n nu = Math.min(m, n);\n\n var wantu = true, wantv = true;\n if (options.computeLeftSingularVectors === false) wantu = false;\n if (options.computeRightSingularVectors === false) wantv = false;\n var autoTranspose = options.autoTranspose === true;\n\n var swapped = false;\n var a;\n if (m < n) {\n if (!autoTranspose) {\n a = value.clone();\n // eslint-disable-next-line no-console\n console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose');\n } else {\n a = value.transpose();\n m = a.rows;\n n = a.columns;\n swapped = true;\n var aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n var s = new Array(Math.min(m + 1, n)),\n U = getFilled2DArray(m, nu, 0),\n V = getFilled2DArray(n, n, 0),\n e = new Array(n),\n work = new Array(m);\n\n var nct = Math.min(m - 1, n);\n var nrt = Math.max(0, Math.min(n - 2, m));\n\n var i, j, k, p, t, ks, f, cs, sn, max, kase,\n scale, sp, spm1, epm1, sk, ek, b, c, shift, g;\n\n for (k = 0, max = Math.max(nct, nrt); k < max; k++) {\n if (k < nct) {\n s[k] = 0;\n for (i = k; i < m; i++) {\n s[k] = hypotenuse(s[k], a[i][k]);\n }\n if (s[k] !== 0) {\n if (a[k][k] < 0) {\n s[k] = -s[k];\n }\n for (i = k; i < m; i++) {\n a[i][k] /= s[k];\n }\n a[k][k] += 1;\n }\n s[k] = -s[k];\n }\n\n for (j = k + 1; j < n; j++) {\n if ((k < nct) && (s[k] !== 0)) {\n t = 0;\n for (i = k; i < m; i++) {\n t += a[i][k] * a[i][j];\n }\n t = -t / a[k][k];\n for (i = k; i < m; i++) {\n a[i][j] += t * a[i][k];\n }\n }\n e[j] = a[k][j];\n }\n\n if (wantu && (k < nct)) {\n for (i = k; i < m; i++) {\n U[i][k] = a[i][k];\n }\n }\n\n if (k < nrt) {\n e[k] = 0;\n for (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 (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 (i = k + 1; i < m; i++) {\n work[i] = 0;\n }\n for (j = k + 1; j < n; j++) {\n for (i = k + 1; i < m; i++) {\n work[i] += e[j] * a[i][j];\n }\n }\n for (j = k + 1; j < n; j++) {\n t = -e[j] / e[k + 1];\n for (i = k + 1; i < m; i++) {\n a[i][j] += t * work[i];\n }\n }\n }\n if (wantv) {\n for (i = k + 1; i < n; i++) {\n V[i][k] = e[i];\n }\n }\n }\n }\n\n p = Math.min(n, m + 1);\n if (nct < n) {\n s[nct] = a[nct][nct];\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a[nrt][p - 1];\n }\n e[p - 1] = 0;\n\n if (wantu) {\n for (j = nct; j < nu; j++) {\n for (i = 0; i < m; i++) {\n U[i][j] = 0;\n }\n U[j][j] = 1;\n }\n for (k = nct - 1; k >= 0; k--) {\n if (s[k] !== 0) {\n for (j = k + 1; j < nu; j++) {\n t = 0;\n for (i = k; i < m; i++) {\n t += U[i][k] * U[i][j];\n }\n t = -t / U[k][k];\n for (i = k; i < m; i++) {\n U[i][j] += t * U[i][k];\n }\n }\n for (i = k; i < m; i++) {\n U[i][k] = -U[i][k];\n }\n U[k][k] = 1 + U[k][k];\n for (i = 0; i < k - 1; i++) {\n U[i][k] = 0;\n }\n } else {\n for (i = 0; i < m; i++) {\n U[i][k] = 0;\n }\n U[k][k] = 1;\n }\n }\n }\n\n if (wantv) {\n for (k = n - 1; k >= 0; k--) {\n if ((k < nrt) && (e[k] !== 0)) {\n for (j = k + 1; j < n; j++) {\n t = 0;\n for (i = k + 1; i < n; i++) {\n t += V[i][k] * V[i][j];\n }\n t = -t / V[k + 1][k];\n for (i = k + 1; i < n; i++) {\n V[i][j] += t * V[i][k];\n }\n }\n }\n for (i = 0; i < n; i++) {\n V[i][k] = 0;\n }\n V[k][k] = 1;\n }\n }\n\n var pp = p - 1,\n iter = 0,\n eps = Math.pow(2, -52);\n while (p > 0) {\n for (k = p - 2; k >= -1; k--) {\n if (k === -1) {\n break;\n }\n if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) {\n e[k] = 0;\n break;\n }\n }\n if (k === p - 2) {\n kase = 4;\n } else {\n for (ks = p - 1; ks >= k; ks--) {\n if (ks === k) {\n break;\n }\n t = (ks !== p ? Math.abs(e[ks]) : 0) + (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 f = e[p - 2];\n e[p - 2] = 0;\n for (j = p - 2; j >= k; j--) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][p - 1];\n V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];\n V[i][j] = t;\n }\n }\n }\n break;\n }\n case 2 : {\n f = e[k - 1];\n e[k - 1] = 0;\n for (j = k; j < p; j++) {\n t = hypotenuse(s[j], f);\n cs = s[j] / t;\n sn = f / t;\n s[j] = t;\n f = -sn * e[j];\n e[j] = cs * e[j];\n if (wantu) {\n for (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][k - 1];\n U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];\n U[i][j] = t;\n }\n }\n }\n break;\n }\n case 3 : {\n scale = Math.max(Math.max(Math.max(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]));\n sp = s[p - 1] / scale;\n spm1 = s[p - 2] / scale;\n epm1 = e[p - 2] / scale;\n sk = s[k] / scale;\n ek = e[k] / scale;\n b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\n c = (sp * epm1) * (sp * epm1);\n shift = 0;\n if ((b !== 0) || (c !== 0)) {\n shift = Math.sqrt(b * b + c);\n if (b < 0) {\n shift = -shift;\n }\n shift = c / (b + shift);\n }\n f = (sk + sp) * (sk - sp) + shift;\n g = sk * ek;\n for (j = k; j < p - 1; j++) {\n t = hypotenuse(f, g);\n cs = f / t;\n 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 (i = 0; i < n; i++) {\n t = cs * V[i][j] + sn * V[i][j + 1];\n V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];\n V[i][j] = t;\n }\n }\n t = hypotenuse(f, g);\n 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 (i = 0; i < m; i++) {\n t = cs * U[i][j] + sn * U[i][j + 1];\n U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];\n U[i][j] = t;\n }\n }\n }\n e[p - 2] = f;\n iter = iter + 1;\n break;\n }\n case 4: {\n if (s[k] <= 0) {\n s[k] = (s[k] < 0 ? -s[k] : 0);\n if (wantv) {\n for (i = 0; i <= pp; i++) {\n V[i][k] = -V[i][k];\n }\n }\n }\n while (k < pp) {\n if (s[k] >= s[k + 1]) {\n break;\n }\n t = s[k];\n s[k] = s[k + 1];\n s[k + 1] = t;\n if (wantv && (k < n - 1)) {\n for (i = 0; i < n; i++) {\n t = V[i][k + 1];\n V[i][k + 1] = V[i][k];\n V[i][k] = t;\n }\n }\n if (wantu && (k < m - 1)) {\n for (i = 0; i < m; i++) {\n t = U[i][k + 1];\n U[i][k + 1] = U[i][k];\n U[i][k] = t;\n }\n }\n k++;\n }\n iter = 0;\n p--;\n break;\n }\n // no default\n }\n }\n\n if (swapped) {\n var tmp = V;\n V = U;\n U = tmp;\n }\n\n this.m = m;\n this.n = n;\n this.s = s;\n this.U = U;\n this.V = V;\n}\n\nSingularValueDecomposition.prototype = {\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n },\n get norm2() {\n return this.s[0];\n },\n get rank() {\n var eps = Math.pow(2, -52),\n tol = Math.max(this.m, this.n) * this.s[0] * eps,\n r = 0,\n s = this.s;\n for (var i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n },\n get diagonal() {\n return this.s;\n },\n // https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs\n get threshold() {\n return (Math.pow(2, -52) / 2) * Math.max(this.m, this.n) * this.s[0];\n },\n get leftSingularVectors() {\n if (!Matrix.isMatrix(this.U)) {\n this.U = new Matrix(this.U);\n }\n return this.U;\n },\n get rightSingularVectors() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n },\n solve: function (value) {\n\n var Y = value,\n e = this.threshold,\n scols = this.s.length,\n Ls = Matrix.zeros(scols, scols),\n i;\n\n for (i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls[i][i] = 0;\n } else {\n Ls[i][i] = 1 / this.s[i];\n }\n }\n\n var U = this.U;\n var V = this.rightSingularVectors;\n\n var VL = V.mmul(Ls),\n vrows = V.rows,\n urows = U.length,\n VLU = Matrix.zeros(vrows, urows),\n j, k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < scols; k++) {\n sum += VL[i][k] * U[j][k];\n }\n VLU[i][j] = sum;\n }\n }\n\n return VLU.mmul(Y);\n },\n solveForDiagonal: function (value) {\n return this.solve(Matrix.diag(value));\n },\n inverse: function () {\n var V = this.V;\n var e = this.threshold,\n vrows = V.length,\n vcols = V[0].length,\n X = new Matrix(vrows, this.s.length),\n i, j;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < vcols; j++) {\n if (Math.abs(this.s[j]) > e) {\n X[i][j] = V[i][j] / this.s[j];\n } else {\n X[i][j] = 0;\n }\n }\n }\n\n var U = this.U;\n\n var urows = U.length,\n ucols = U[0].length,\n Y = new Matrix(vrows, urows),\n k, sum;\n\n for (i = 0; i < vrows; i++) {\n for (j = 0; j < urows; j++) {\n sum = 0;\n for (k = 0; k < ucols; k++) {\n sum += X[i][k] * U[j][k];\n }\n Y[i][j] = sum;\n }\n }\n\n return Y;\n }\n};\n\nexport default SingularValueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/dc/svd.js\n// module id = 72\n// module chunks = 0","export {default as default, default as Matrix} from './matrix';\nexport {default as abstractMatrix} from './abstractMatrix';\n\nexport {solve, inverse} from './decompositions';\nexport {default as SingularValueDecomposition, default as SVD} from './dc/svd.js';\nexport {default as EigenvalueDecomposition, default as EVD} from './dc/evd.js';\nexport {default as CholeskyDecomposition, default as CHO} from './dc/cholesky.js';\nexport {default as LuDecomposition, default as LU} from './dc/lu.js';\nexport {default as QrDecomposition, default as QR} from './dc/qr.js';\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/index.js\n// module id = 73\n// module chunks = 0","'use strict';\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n/**\n * Computes the sum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.sum = function sum(values) {\n var sum = 0;\n for (var i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum;\n};\n\n/**\n * Computes the maximum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.max = function max(values) {\n var max = -Infinity;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] > max) max = values[i];\n }\n return max;\n};\n\n/**\n * Computes the minimum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.min = function min(values) {\n var min = Infinity;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] < min) min = values[i];\n }\n return min;\n};\n\n/**\n * Computes the min and max of the given values\n * @param {Array} values\n * @returns {{min: number, max: number}}\n */\nexports.minMax = function minMax(values) {\n var min = Infinity;\n var max = -Infinity;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] < min) min = values[i];\n if (values[i] > max) max = values[i];\n }\n return {\n min: min,\n max: max\n };\n};\n\n/**\n * Computes the arithmetic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.arithmeticMean = function arithmeticMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n sum += values[i];\n }\n return sum / l;\n};\n\n/**\n * {@link arithmeticMean}\n */\nexports.mean = exports.arithmeticMean;\n\n/**\n * Computes the geometric mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.geometricMean = function geometricMean(values) {\n var mul = 1;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n mul *= values[i];\n }\n return Math.pow(mul, 1 / l);\n};\n\n/**\n * Computes the mean of the log of the given values\n * If the return value is exponentiated, it gives the same result as the\n * geometric mean.\n * @param {Array} values\n * @returns {number}\n */\nexports.logMean = function logMean(values) {\n var lnsum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n lnsum += Math.log(values[i]);\n }\n return lnsum / l;\n};\n\n/**\n * Computes the weighted grand mean for a list of means and sample sizes\n * @param {Array} means - Mean values for each set of samples\n * @param {Array} samples - Number of original values for each set of samples\n * @returns {number}\n */\nexports.grandMean = function grandMean(means, samples) {\n var sum = 0;\n var n = 0;\n var l = means.length;\n for (var i = 0; i < l; i++) {\n sum += samples[i] * means[i];\n n += samples[i];\n }\n return sum / n;\n};\n\n/**\n * Computes the truncated mean of the given values using a given percentage\n * @param {Array} values\n * @param {number} percent - The percentage of values to keep (range: [0,1])\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = values.slice().sort(compareNumbers);\n }\n var l = values.length;\n var k = Math.floor(l * percent);\n var sum = 0;\n for (var i = k; i < (l - k); i++) {\n sum += values[i];\n }\n return sum / (l - 2 * k);\n};\n\n/**\n * Computes the harmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.harmonicMean = function harmonicMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] === 0) {\n throw new RangeError('value at index ' + i + 'is zero');\n }\n sum += 1 / values[i];\n }\n return l / sum;\n};\n\n/**\n * Computes the contraharmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.contraHarmonicMean = function contraHarmonicMean(values) {\n var r1 = 0;\n var r2 = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n r1 += values[i] * values[i];\n r2 += values[i];\n }\n if (r2 < 0) {\n throw new RangeError('sum of values is negative');\n }\n return r1 / r2;\n};\n\n/**\n * Computes the median of the given values\n * @param {Array} values\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.median = function median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = values.slice().sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n};\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.variance = function variance(values, unbiased) {\n if (unbiased === undefined) unbiased = true;\n var theMean = exports.mean(values);\n var theVariance = 0;\n var l = values.length;\n\n for (var i = 0; i < l; i++) {\n var x = values[i] - theMean;\n theVariance += x * x;\n }\n\n if (unbiased) {\n return theVariance / (l - 1);\n } else {\n return theVariance / l;\n }\n};\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.standardDeviation = function standardDeviation(values, unbiased) {\n return Math.sqrt(exports.variance(values, unbiased));\n};\n\nexports.standardError = function standardError(values) {\n return exports.standardDeviation(values) / Math.sqrt(values.length);\n};\n\nexports.quartiles = function quartiles(values, alreadySorted) {\n if (typeof(alreadySorted) === 'undefined') alreadySorted = false;\n if (!alreadySorted) {\n values = values.slice();\n values.sort(compareNumbers);\n }\n\n var quart = values.length / 4;\n var q1 = values[Math.ceil(quart) - 1];\n var q2 = exports.median(values, true);\n var q3 = values[Math.ceil(quart * 3) - 1];\n\n return {q1: q1, q2: q2, q3: q3};\n};\n\nexports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {\n return Math.sqrt(exports.pooledVariance(samples, unbiased));\n};\n\nexports.pooledVariance = function pooledVariance(samples, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var sum = 0;\n var length = 0, l = samples.length;\n for (var i = 0; i < l; i++) {\n var values = samples[i];\n var vari = exports.variance(values);\n\n sum += (values.length - 1) * vari;\n\n if (unbiased)\n length += values.length - 1;\n else\n length += values.length;\n }\n return sum / length;\n};\n\nexports.mode = function mode(values) {\n var l = values.length,\n itemCount = new Array(l),\n i;\n for (i = 0; i < l; i++) {\n itemCount[i] = 0;\n }\n var itemArray = new Array(l);\n var count = 0;\n\n for (i = 0; i < l; i++) {\n var index = itemArray.indexOf(values[i]);\n if (index >= 0)\n itemCount[index]++;\n else {\n itemArray[count] = values[i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (i = 0; i < count; i++) {\n if (itemCount[i] > maxValue) {\n maxValue = itemCount[i];\n maxIndex = i;\n }\n }\n\n return itemArray[maxIndex];\n};\n\nexports.covariance = function covariance(vector1, vector2, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var mean1 = exports.mean(vector1);\n var mean2 = exports.mean(vector2);\n\n if (vector1.length !== vector2.length)\n throw \"Vectors do not have the same dimensions\";\n\n var cov = 0, l = vector1.length;\n for (var i = 0; i < l; i++) {\n var x = vector1[i] - mean1;\n var y = vector2[i] - mean2;\n cov += x * y;\n }\n\n if (unbiased)\n return cov / (l - 1);\n else\n return cov / l;\n};\n\nexports.skewness = function skewness(values, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n\n var s2 = 0, s3 = 0, l = values.length;\n for (var i = 0; i < l; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n var m2 = s2 / l;\n var m3 = s3 / l;\n\n var g = m3 / (Math.pow(m2, 3 / 2.0));\n if (unbiased) {\n var a = Math.sqrt(l * (l - 1));\n var b = l - 2;\n return (a / b) * g;\n }\n else {\n return g;\n }\n};\n\nexports.kurtosis = function kurtosis(values, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n var n = values.length, s2 = 0, s4 = 0;\n\n for (var i = 0; i < n; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n\n return a * b - 3 * c;\n }\n else {\n return m4 / (m2 * m2) - 3;\n }\n};\n\nexports.entropy = function entropy(values, eps) {\n if (typeof(eps) === 'undefined') eps = 0;\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * Math.log(values[i] + eps);\n return -sum;\n};\n\nexports.weightedMean = function weightedMean(values, weights) {\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * weights[i];\n return sum;\n};\n\nexports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {\n return Math.sqrt(exports.weightedVariance(values, weights));\n};\n\nexports.weightedVariance = function weightedVariance(values, weights) {\n var theMean = exports.weightedMean(values, weights);\n var vari = 0, l = values.length;\n var a = 0, b = 0;\n\n for (var i = 0; i < l; i++) {\n var z = values[i] - theMean;\n var w = weights[i];\n\n vari += w * (z * z);\n b += w;\n a += w * w;\n }\n\n return vari * (b / (b * b - a));\n};\n\nexports.center = function center(values, inPlace) {\n if (typeof(inPlace) === 'undefined') inPlace = false;\n\n var result = values;\n if (!inPlace)\n result = values.slice();\n\n var theMean = exports.mean(result), l = result.length;\n for (var i = 0; i < l; i++)\n result[i] -= theMean;\n};\n\nexports.standardize = function standardize(values, standardDev, inPlace) {\n if (typeof(standardDev) === 'undefined') standardDev = exports.standardDeviation(values);\n if (typeof(inPlace) === 'undefined') inPlace = false;\n var l = values.length;\n var result = inPlace ? values : new Array(l);\n for (var i = 0; i < l; i++)\n result[i] = values[i] / standardDev;\n return result;\n};\n\nexports.cumulativeSum = function cumulativeSum(array) {\n var l = array.length;\n var result = new Array(l);\n result[0] = array[0];\n for (var i = 1; i < l; i++)\n result[i] = result[i - 1] + array[i];\n return result;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-savitzky-golay-generalized/~/ml-stat/array.js\n// module id = 74\n// module chunks = 0","function NodeSquare(x, y, weights, som) {\n this.x = x;\n this.y = y;\n this.weights = weights;\n this.som = som;\n this.neighbors = {};\n}\n\nNodeSquare.prototype.adjustWeights = function adjustWeights(target, learningRate, influence) {\n for (var i = 0, ii = this.weights.length; i < ii; i++) {\n this.weights[i] += learningRate * influence * (target[i] - this.weights[i]);\n }\n};\n\nNodeSquare.prototype.getDistance = function getDistance(otherNode) {\n return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y));\n};\n\nNodeSquare.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.x - otherNode.x),\n distY = Math.abs(this.y - otherNode.y);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY));\n};\n\nNodeSquare.prototype.getNeighbors = function getNeighbors(xy) {\n if (!this.neighbors[xy]) {\n this.neighbors[xy] = new Array(2);\n\n // left or bottom neighbor\n var v;\n if (this[xy] > 0) {\n v = this[xy] - 1;\n } else if (this.som.torus) {\n v = this.som.gridDim[xy] - 1\n }\n if (typeof v !== 'undefined') {\n var x, y;\n if (xy === 'x') {\n x = v;\n y = this.y;\n } else {\n x = this.x;\n y = v;\n }\n this.neighbors[xy][0] = this.som.nodes[x][y];\n }\n\n // top or right neighbor\n var w;\n if (this[xy] < (this.som.gridDim[xy] - 1)) {\n w = this[xy] + 1;\n } else if (this.som.torus) {\n w = 0;\n }\n if (typeof w !== 'undefined') {\n if (xy === 'x') {\n x = w;\n y = this.y;\n } else {\n x = this.x;\n y = w;\n }\n this.neighbors[xy][1] = this.som.nodes[x][y];\n }\n }\n return this.neighbors[xy];\n};\n\nNodeSquare.prototype.getPos = function getPos(xy, element) {\n var neighbors = this.getNeighbors(xy),\n distance = this.som.distance,\n bestNeighbor,\n direction;\n if(neighbors[0]) {\n if (neighbors[1]) {\n var dist1 = distance(element, neighbors[0].weights),\n dist2 = distance(element, neighbors[1].weights);\n if(dist1 < dist2) {\n bestNeighbor = neighbors[0];\n direction = -1;\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n } else {\n bestNeighbor = neighbors[0];\n direction = -1;\n }\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n var simA = 1 - distance(element, this.weights),\n simB = 1 - distance(element, bestNeighbor.weights);\n var factor = ((simA - simB) / (2 - simA - simB));\n return 0.5 + 0.5 * factor * direction;\n};\n\nNodeSquare.prototype.getPosition = function getPosition(element) {\n return [\n this.getPos('x', element),\n this.getPos('y', element)\n ];\n};\n\nmodule.exports = NodeSquare;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-som/src/node-square.js\n// module id = 75\n// module chunks = 0","'use strict';\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n/**\n * Computes the sum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.sum = function sum(values) {\n var sum = 0;\n for (var i = 0; i < values.length; i++) {\n sum += values[i];\n }\n return sum;\n};\n\n/**\n * Computes the maximum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.max = function max(values) {\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] > max) max = values[i];\n }\n return max;\n};\n\n/**\n * Computes the minimum of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.min = function min(values) {\n var min = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n }\n return min;\n};\n\n/**\n * Computes the min and max of the given values\n * @param {Array} values\n * @returns {{min: number, max: number}}\n */\nexports.minMax = function minMax(values) {\n var min = values[0];\n var max = values[0];\n var l = values.length;\n for (var i = 1; i < l; i++) {\n if (values[i] < min) min = values[i];\n if (values[i] > max) max = values[i];\n }\n return {\n min: min,\n max: max\n };\n};\n\n/**\n * Computes the arithmetic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.arithmeticMean = function arithmeticMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n sum += values[i];\n }\n return sum / l;\n};\n\n/**\n * {@link arithmeticMean}\n */\nexports.mean = exports.arithmeticMean;\n\n/**\n * Computes the geometric mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.geometricMean = function geometricMean(values) {\n var mul = 1;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n mul *= values[i];\n }\n return Math.pow(mul, 1 / l);\n};\n\n/**\n * Computes the mean of the log of the given values\n * If the return value is exponentiated, it gives the same result as the\n * geometric mean.\n * @param {Array} values\n * @returns {number}\n */\nexports.logMean = function logMean(values) {\n var lnsum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n lnsum += Math.log(values[i]);\n }\n return lnsum / l;\n};\n\n/**\n * Computes the weighted grand mean for a list of means and sample sizes\n * @param {Array} means - Mean values for each set of samples\n * @param {Array} samples - Number of original values for each set of samples\n * @returns {number}\n */\nexports.grandMean = function grandMean(means, samples) {\n var sum = 0;\n var n = 0;\n var l = means.length;\n for (var i = 0; i < l; i++) {\n sum += samples[i] * means[i];\n n += samples[i];\n }\n return sum / n;\n};\n\n/**\n * Computes the truncated mean of the given values using a given percentage\n * @param {Array} values\n * @param {number} percent - The percentage of values to keep (range: [0,1])\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var k = Math.floor(l * percent);\n var sum = 0;\n for (var i = k; i < (l - k); i++) {\n sum += values[i];\n }\n return sum / (l - 2 * k);\n};\n\n/**\n * Computes the harmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.harmonicMean = function harmonicMean(values) {\n var sum = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (values[i] === 0) {\n throw new RangeError('value at index ' + i + 'is zero');\n }\n sum += 1 / values[i];\n }\n return l / sum;\n};\n\n/**\n * Computes the contraharmonic mean of the given values\n * @param {Array} values\n * @returns {number}\n */\nexports.contraHarmonicMean = function contraHarmonicMean(values) {\n var r1 = 0;\n var r2 = 0;\n var l = values.length;\n for (var i = 0; i < l; i++) {\n r1 += values[i] * values[i];\n r2 += values[i];\n }\n if (r2 < 0) {\n throw new RangeError('sum of values is negative');\n }\n return r1 / r2;\n};\n\n/**\n * Computes the median of the given values\n * @param {Array} values\n * @param {boolean} [alreadySorted=false]\n * @returns {number}\n */\nexports.median = function median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n};\n\n/**\n * Computes the variance of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.variance = function variance(values, unbiased) {\n if (unbiased === undefined) unbiased = true;\n var theMean = exports.mean(values);\n var theVariance = 0;\n var l = values.length;\n\n for (var i = 0; i < l; i++) {\n var x = values[i] - theMean;\n theVariance += x * x;\n }\n\n if (unbiased) {\n return theVariance / (l - 1);\n } else {\n return theVariance / l;\n }\n};\n\n/**\n * Computes the standard deviation of the given values\n * @param {Array} values\n * @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.\n * @returns {number}\n */\nexports.standardDeviation = function standardDeviation(values, unbiased) {\n return Math.sqrt(exports.variance(values, unbiased));\n};\n\nexports.standardError = function standardError(values) {\n return exports.standardDeviation(values) / Math.sqrt(values.length);\n};\n\n/**\n * IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-\n * Calculate the standard deviation via the Median of the absolute deviation\n * The formula for the standard deviation only holds for Gaussian random variables.\n * @returns {{mean: number, stdev: number}}\n */\nexports.robustMeanAndStdev = function robustMeanAndStdev(y) {\n var mean = 0, stdev = 0;\n var length = y.length, i = 0;\n for (i = 0; i < length; i++) {\n mean += y[i];\n }\n mean /= length;\n var averageDeviations = new Array(length);\n for (i = 0; i < length; i++)\n averageDeviations[i] = Math.abs(y[i] - mean);\n averageDeviations.sort(compareNumbers);\n if (length % 2 === 1) {\n stdev = averageDeviations[(length - 1) / 2] / 0.6745;\n } else {\n stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745;\n }\n\n return {\n mean: mean,\n stdev: stdev\n };\n};\n\nexports.quartiles = function quartiles(values, alreadySorted) {\n if (typeof (alreadySorted) === 'undefined') alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n\n var quart = values.length / 4;\n var q1 = values[Math.ceil(quart) - 1];\n var q2 = exports.median(values, true);\n var q3 = values[Math.ceil(quart * 3) - 1];\n\n return {q1: q1, q2: q2, q3: q3};\n};\n\nexports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {\n return Math.sqrt(exports.pooledVariance(samples, unbiased));\n};\n\nexports.pooledVariance = function pooledVariance(samples, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var sum = 0;\n var length = 0, l = samples.length;\n for (var i = 0; i < l; i++) {\n var values = samples[i];\n var vari = exports.variance(values);\n\n sum += (values.length - 1) * vari;\n\n if (unbiased)\n length += values.length - 1;\n else\n length += values.length;\n }\n return sum / length;\n};\n\nexports.mode = function mode(values) {\n var l = values.length,\n itemCount = new Array(l),\n i;\n for (i = 0; i < l; i++) {\n itemCount[i] = 0;\n }\n var itemArray = new Array(l);\n var count = 0;\n\n for (i = 0; i < l; i++) {\n var index = itemArray.indexOf(values[i]);\n if (index >= 0)\n itemCount[index]++;\n else {\n itemArray[count] = values[i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (i = 0; i < count; i++) {\n if (itemCount[i] > maxValue) {\n maxValue = itemCount[i];\n maxIndex = i;\n }\n }\n\n return itemArray[maxIndex];\n};\n\nexports.covariance = function covariance(vector1, vector2, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var mean1 = exports.mean(vector1);\n var mean2 = exports.mean(vector2);\n\n if (vector1.length !== vector2.length)\n throw 'Vectors do not have the same dimensions';\n\n var cov = 0, l = vector1.length;\n for (var i = 0; i < l; i++) {\n var x = vector1[i] - mean1;\n var y = vector2[i] - mean2;\n cov += x * y;\n }\n\n if (unbiased)\n return cov / (l - 1);\n else\n return cov / l;\n};\n\nexports.skewness = function skewness(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n\n var s2 = 0, s3 = 0, l = values.length;\n for (var i = 0; i < l; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n var m2 = s2 / l;\n var m3 = s3 / l;\n\n var g = m3 / (Math.pow(m2, 3 / 2.0));\n if (unbiased) {\n var a = Math.sqrt(l * (l - 1));\n var b = l - 2;\n return (a / b) * g;\n } else {\n return g;\n }\n};\n\nexports.kurtosis = function kurtosis(values, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var theMean = exports.mean(values);\n var n = values.length, s2 = 0, s4 = 0;\n\n for (var i = 0; i < n; i++) {\n var dev = values[i] - theMean;\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n\n return a * b - 3 * c;\n } else {\n return m4 / (m2 * m2) - 3;\n }\n};\n\nexports.entropy = function entropy(values, eps) {\n if (typeof (eps) === 'undefined') eps = 0;\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * Math.log(values[i] + eps);\n return -sum;\n};\n\nexports.weightedMean = function weightedMean(values, weights) {\n var sum = 0, l = values.length;\n for (var i = 0; i < l; i++)\n sum += values[i] * weights[i];\n return sum;\n};\n\nexports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {\n return Math.sqrt(exports.weightedVariance(values, weights));\n};\n\nexports.weightedVariance = function weightedVariance(values, weights) {\n var theMean = exports.weightedMean(values, weights);\n var vari = 0, l = values.length;\n var a = 0, b = 0;\n\n for (var i = 0; i < l; i++) {\n var z = values[i] - theMean;\n var w = weights[i];\n\n vari += w * (z * z);\n b += w;\n a += w * w;\n }\n\n return vari * (b / (b * b - a));\n};\n\nexports.center = function center(values, inPlace) {\n if (typeof (inPlace) === 'undefined') inPlace = false;\n\n var result = values;\n if (!inPlace)\n result = [].concat(values);\n\n var theMean = exports.mean(result), l = result.length;\n for (var i = 0; i < l; i++)\n result[i] -= theMean;\n};\n\nexports.standardize = function standardize(values, standardDev, inPlace) {\n if (typeof (standardDev) === 'undefined') standardDev = exports.standardDeviation(values);\n if (typeof (inPlace) === 'undefined') inPlace = false;\n var l = values.length;\n var result = inPlace ? values : new Array(l);\n for (var i = 0; i < l; i++)\n result[i] = values[i] / standardDev;\n return result;\n};\n\nexports.cumulativeSum = function cumulativeSum(array) {\n var l = array.length;\n var result = new Array(l);\n result[0] = array[0];\n for (var i = 1; i < l; i++)\n result[i] = result[i - 1] + array[i];\n return result;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-stat/array.js\n// module id = 76\n// module chunks = 0","'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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-bit-array/src/index.js\n// module id = 77\n// module chunks = 0","'use strict';\n\nconst ConfusionMatrix = require('./ConfusionMatrix');\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 validation\n * set while the rest is used as the training set. This is repeated once for each observation. LOO-CV is a special case\n * of LPO-CV. @see leavePout\n * @param {constructor} Classifier - The classifier 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 * @returns {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leaveOneOut = function (Classifier, features, labels, classifierOptions) {\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 Classifier - The classifier 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} p - The size of the validation sub-samples' set\n * @returns {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.leavePOut = function (Classifier, features, labels, classifierOptions, p) {\n check(features, labels);\n const distinct = getDistinct(labels);\n const confusionMatrix = initMatrix(distinct.length, distinct.length);\n var i, N = features.length;\n var gen = combinations(p, N);\n var allIdx = new Array(N);\n for (i = 0; i < N; i++) {\n allIdx[i] = i;\n }\n for (const testIdx of gen) {\n var trainIdx = allIdx.slice();\n\n for (i = testIdx.length - 1; i >= 0; i--) {\n trainIdx.splice(testIdx[i], 1);\n }\n\n validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\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 Classifier - The classifier 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 * @returns {ConfusionMatrix} - The cross-validation confusion matrix\n */\nCV.kFold = function (Classifier, features, labels, classifierOptions, k) {\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 validate(Classifier, features, labels, classifierOptions, testIdx, trainIdx, confusionMatrix, distinct);\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 var testFeatures = testIdx.map(function (index) {\n return features[index];\n });\n var trainFeatures = trainIdx.map(function (index) {\n return features[index];\n });\n var testLabels = testIdx.map(function (index) {\n return labels[index];\n });\n var trainLabels = trainIdx.map(function (index) {\n return labels[index];\n });\n\n var classifier = new Classifier(classifierOptions);\n classifier.train(trainFeatures, trainLabels);\n var predictedLabels = classifier.predict(testFeatures);\n for (var i = 0; i < predictedLabels.length; i++) {\n confusionMatrix[distinct.indexOf(testLabels[i])][distinct.indexOf(predictedLabels[i])]++;\n }\n}\n\nmodule.exports = CV;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-cross-validation/src/crossValidation.js\n// module id = 78\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix');\n\nconst Layer = require('./Layer');\nconst OutputLayer = require('./OutputLayer');\nconst Utils = require('./utils');\nconst ACTIVATION_FUNCTIONS = require('./activationFunctions');\n\nclass FeedForwardNeuralNetworks {\n\n /**\n * Create a new Feedforword neural network model.\n * @param {object} options\n * @param {Array} [options.hiddenLayers=[10]] - Array that contains the sizes of the hidden layers.\n * @oaram {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 * @poram {number} [options.regularization=0.01] - Regularization parameter af the neural net.\n * @poram {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 === undefined ? [10] : options.hiddenLayers;\n this.iterations = options.iterations === undefined ? 50 : options.iterations;\n\n this.learningRate = options.learningRate === undefined ? 0.01 : options.learningRate;\n //this.momentum = options.momentum === undefined ? 0.1 : options.momentum;\n this.regularization = options.regularization === undefined ? 0.01 : options.regularization;\n\n this.activation = options.activation === undefined ? 'tanh' : options.activation;\n this.activationParam = options.activationParam === undefined ? 1 : options.activationParam;\n if (!(this.activation in Object.keys(ACTIVATION_FUNCTIONS))) {\n this.activation = 'tanh';\n }\n }\n }\n\n /**\n * Function that build and initialize the neural net.\n * @param {number} inputSize - total of features to fit.\n * @param {number} outputSize - total of labels of the prediction set.\n */\n buildNetwork(inputSize, outputSize) {\n var size = 2 + (this.hiddenLayers.length - 1);\n this.model = new Array(size);\n\n // input layer\n this.model[0] = new Layer({\n inputSize: inputSize,\n outputSize: this.hiddenLayers[0],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n\n // hidden layers\n for (var i = 1; i < this.hiddenLayers.length; ++i) {\n this.model[i] = new Layer({\n inputSize: this.hiddenLayers[i - 1],\n outputSize: this.hiddenLayers[i],\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n // output layer\n this.model[size - 1] = new OutputLayer({\n inputSize: this.hiddenLayers[this.hiddenLayers.length - 1],\n outputSize: outputSize,\n activation: this.activation,\n activationParam: this.activationParam,\n regularization: this.regularization,\n epsilon: this.learningRate\n });\n }\n\n /**\n * Train the neural net with the given features and labels.\n * @param {Matrix|Array} features\n * @param {Matrix|Array} labels\n */\n train(features, labels) {\n features = Matrix.checkMatrix(features);\n this.dicts = Utils.dictOutputs(labels);\n\n var inputSize = features.columns;\n var outputSize = Object.keys(this.dicts.inputs).length;\n\n this.buildNetwork(inputSize, outputSize);\n\n for (var i = 0; i < this.iterations; ++i) {\n var probabilities = this.propagate(features);\n this.backpropagation(features, labels, probabilities);\n }\n }\n\n /**\n * Propagate the input(training set) and retrives the probabilities of each class.\n * @param {Matrix} X\n * @return {Matrix} probabilities of each class.\n */\n propagate(X) {\n var input = X;\n for (var i = 0; i < this.model.length; ++i) {\n //console.log(i);\n input = this.model[i].forward(input);\n }\n\n // get probabilities\n return input.divColumnVector(Utils.sumRow(input));\n }\n\n /**\n * Function that applies the backpropagation algorithm on each layer of the network\n * in order to fit the features and labels.\n * @param {Matrix} features\n * @param {Array} labels\n * @param {Matrix} probabilities - probabilities of each class of the feature set.\n */\n backpropagation(features, labels, probabilities) {\n for (var i = 0; i < probabilities.length; ++i) {\n probabilities[i][this.dicts.inputs[labels[i]]] -= 1;\n }\n\n // remember, the last delta doesn't matter\n var delta = probabilities;\n for (i = this.model.length - 1; i >= 0; --i) {\n var a = i > 0 ? this.model[i - 1].a : features;\n delta = this.model[i].backpropagation(delta, a);\n }\n\n for (i = 0; i < this.model.length; ++i) {\n this.model[i].update();\n }\n }\n\n /**\n * Predict the output given the feature set.\n * @param {Array|Matrix} features\n * @return {Array}\n */\n predict(features) {\n features = Matrix.checkMatrix(features);\n var outputs = new Array(features.rows);\n var probabilities = this.propagate(features);\n for (var i = 0; i < features.rows; ++i) {\n outputs[i] = this.dicts.outputs[probabilities.maxRowIndex(i)[1]];\n }\n\n return outputs;\n }\n\n /**\n * Export the current model to JSOM.\n * @return {object} model\n */\n toJSON() {\n var model = {\n model: 'FNN',\n hiddenLayers: this.hiddenLayers,\n iterations: this.iterations,\n learningRate: this.learningRate,\n regularization: this.regularization,\n activation: this.activation,\n activationParam: this.activationParam,\n dicts: this.dicts,\n layers: new Array(this.model.length)\n };\n\n for (var i = 0; i < this.model.length; ++i) {\n model.layers[i] = this.model[i].toJSON();\n }\n\n return model;\n }\n\n /**\n * Load a Feedforward Neural Network with the current model.\n * @param {object} model\n * @return {FeedForwardNeuralNetworks}\n */\n static load(model) {\n if (model.model !== 'FNN') {\n throw new RangeError('the current model is not a feed forward network');\n }\n\n return new FeedForwardNeuralNetworks(model);\n }\n}\n\nmodule.exports = FeedForwardNeuralNetworks;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-fnn/src/FeedForwardNeuralNetwork.js\n// module id = 79\n// module chunks = 0","'use strict';\n\nexports.agnes = require('./agnes');\nexports.diana = require('./diana');\n//exports.birch = require('./birch');\n//exports.cure = require('./cure');\n//exports.chameleon = require('./chameleon');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/index.js\n// module id = 80\n// module chunks = 0","'use strict';\n\nmodule.exports = require('./knn');\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-knn/src/index.js\n// module id = 82\n// module chunks = 0","'use strict';\n\nconst errorCalculation = require('./errorCalculation');\nconst step = require('./step');\n\nconst defaultOptions = {\n damping: undefined,\n gradientDifference: 10e-2,\n initialValues: undefined,\n maxIterations: 100,\n errorTolerance: 10e-3\n};\n\n/**\n * Curve fitting algorithm\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @param {object} [options] - Options object\n * @param {number} [options.damping = undefined] - Levenberg-Marquardt parameter\n * @param {number} [options.gradientDifference = 10e-2] - Adjustment for decrease the damping parameter\n * @param {Array} [options.initialValues = undefined] - Array of initial parameter values\n * @param {number} [options.maxIterations = 100] - Maximum of allowed iterations\n * @param {number} [options.errorTolerance = 10e-3] - Minimum uncertainty allowed for each point\n * @return {{parameterValues: Array, parameterError: number, iterations: number}}\n */\nfunction levenbergMarquardt(data, parameterizedFunction, options) {\n // verify that damping is not undefined\n if ((!options) || (!options.damping) || (options.damping <= 0)) {\n throw new TypeError('The damping option should be a positive number');\n }\n\n // assign default values\n options = Object.assign({}, defaultOptions, options);\n\n // fill with default value for initialValues\n if (!options.initialValues) {\n options.initialValues = new Array(parameterizedFunction.length);\n\n for (var i = 0; i < parameterizedFunction.length; i++) {\n options.initialValues[i] = 1;\n }\n }\n\n // check that the data has the correct format\n if (!data.x || !data.y) {\n throw new TypeError('The data parameter should have a x and y elements');\n } else if ((data.x.constructor !== Array) || (data.x.length < 2) ||\n (data.y.constructor !== Array) || (data.y.length < 2)) {\n throw new TypeError('The data parameter elements should be an array with more than 2 points');\n }\n\n const dataLen = data.x.length;\n if (dataLen !== data.y.length) {\n throw new RangeError('The data parameter elements should have the same size');\n }\n\n // initial parameters\n var parameters = options.initialValues;\n\n // check errorCalculation\n var error = errorCalculation(data, parameters, parameterizedFunction);\n var converged = error <= options.errorTolerance;\n\n for (var iteration = 0; (iteration < options.maxIterations) && !converged; iteration++) {\n // step function\n parameters = step(data, parameters, options.damping, options.gradientDifference, parameterizedFunction);\n\n // reevaluate errorCalculation\n error = errorCalculation(data, parameters, parameterizedFunction);\n converged = error <= options.errorTolerance;\n }\n\n\n // return example\n return {\n parameterValues: parameters,\n parameterError: error,\n iterations: iteration\n };\n}\n\nmodule.exports = levenbergMarquardt;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-levenberg-marquardt/src/index.js\n// module id = 83\n// module chunks = 0","'use strict';\n\nmodule.exports = exports = require('./naiveBayes').NaiveBayes;\nexports.separateClasses = require('./naiveBayes').separateClasses;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-naivebayes/src/index.js\n// module id = 84\n// module chunks = 0","'use strict';\n\nvar LM = require('ml-curve-fitting');\nvar math = LM.Matrix.algebra;\nvar Matrix = require('ml-matrix');\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 * @param c Constant parameters(Not used)\n * @returns {*}\n */\nfunction sumOfLorentzians(t,p,c){\n var nL = p.length/3,factor,i, j,p2, cols = t.rows;\n var result = Matrix.zeros(t.length,1);\n\n for(i=0;imaxY)\n maxY = y[i];\n }\n }\n else{\n //It is a colum matrix\n if(typeof x[0] === \"object\"){\n for(i=0;imaxY)\n maxY = y[i][0];\n }\n }\n\n }\n\n //}\n }\n else{\n //Looks like a column wise matrix [[x],[y]]\n var nbPoints = nbSeries;\n //if(nbPoints<3)\n // throw new SizeException(nbPoints);\n //else {\n t = new Array(nbPoints);//new Matrix(nbPoints, 1);\n y_data = new Array(nbPoints);//new Matrix(nbPoints, 1);\n for (i = 0; i < nbPoints; i++) {\n t[i] = xy[i][0];\n y_data[i] = xy[i][1];\n if(y_data[i]>maxY)\n maxY = y_data[i];\n }\n //}\n }\n for (i = 0; i < nbPoints; i++) {\n y_data[i]/=maxY;\n }\n if(threshold){\n for (i = nbPoints-1; i >=0; i--) {\n if(y_data[i]0)\n return [(new Matrix([t])).transpose(),(new Matrix([y_data])).transpose(),maxY];\n return null;\n}\n\nfunction sizeException(nbPoints) {\n return new RangeError(\"Not enough points to perform the optimization: \"+nbPoints +\"< 3\");\n}\n\nmodule.exports.optimizeSingleLorentzian = optimizeSingleLorentzian;\nmodule.exports.optimizeLorentzianSum = optimizeLorentzianSum;\nmodule.exports.optimizeSingleGaussian = optimizeSingleGaussian;\nmodule.exports.optimizeGaussianSum = optimizeGaussianSum;\nmodule.exports.singleGaussian = singleGaussian;\nmodule.exports.singleLorentzian = singleLorentzian;\nmodule.exports.optimizeGaussianTrain = optimizeGaussianTrain;\nmodule.exports.optimizeLorentzianTrain = optimizeLorentzianTrain;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-optimize-lorentzian/src/index.js\n// module id = 85\n// module chunks = 0","'use strict';\n\nconst Matrix = require('ml-matrix');\nconst EVD = Matrix.DC.EVD;\nconst SVD = Matrix.DC.SVD;\nconst Stat = require('ml-stat').matrix;\nconst mean = Stat.mean;\nconst stdev = Stat.standardDeviation;\n\nconst defaultOptions = {\n isCovarianceMatrix: false,\n center: true,\n scale: false\n};\n\n/**\n * Creates new PCA (Principal Component Analysis) from the dataset\n * @param {Matrix} dataset - dataset or covariance matrix\n * @param {Object} options\n * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix\n * @param {boolean} [options.center=true] - should the data be centered (subtract the mean)\n * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation)\n * */\nclass PCA {\n constructor(dataset, options) {\n if (dataset === true) {\n const model = options;\n this.center = model.center;\n this.scale = model.scale;\n this.means = model.means;\n this.stdevs = model.stdevs;\n this.U = Matrix.checkMatrix(model.U);\n this.S = model.S;\n return;\n }\n\n options = Object.assign({}, defaultOptions, options);\n\n this.center = false;\n this.scale = false;\n this.means = null;\n this.stdevs = null;\n\n if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset\n this._computeFromCovarianceMatrix(dataset);\n return;\n }\n\n var useCovarianceMatrix;\n if (typeof options.useCovarianceMatrix === 'boolean') {\n useCovarianceMatrix = options.useCovarianceMatrix;\n } else {\n useCovarianceMatrix = dataset.length > dataset[0].length;\n }\n\n if (useCovarianceMatrix) { // user provided a dataset but wants us to compute and use the covariance matrix\n dataset = this._adjust(dataset, options);\n const covarianceMatrix = dataset.transposeView().mmul(dataset).div(dataset.rows - 1);\n this._computeFromCovarianceMatrix(covarianceMatrix);\n } else {\n dataset = this._adjust(dataset, options);\n var svd = new SVD(dataset, {\n computeLeftSingularVectors: false,\n computeRightSingularVectors: true,\n autoTranspose: true\n });\n\n this.U = svd.rightSingularVectors;\n\n const singularValues = svd.diagonal;\n const eigenvalues = new Array(singularValues.length);\n for (var i = 0; i < singularValues.length; i++) {\n eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1);\n }\n this.S = eigenvalues;\n }\n }\n\n /**\n * Load a PCA model from JSON\n * @param {Object} model\n * @return {PCA}\n */\n static load(model) {\n if (model.name !== 'PCA')\n throw new RangeError('Invalid model: ' + model.name);\n return new PCA(true, model);\n }\n\n /**\n * Project the dataset into the PCA space\n * @param {Matrix} dataset\n * @return {Matrix} dataset projected in the PCA space\n */\n predict(dataset) {\n dataset = new Matrix(dataset);\n\n if (this.center) {\n dataset.subRowVector(this.means);\n if (this.scale) {\n dataset.divRowVector(this.stdevs);\n }\n }\n\n return dataset.mmul(this.U);\n }\n\n /**\n * Returns the proportion of variance for each component\n * @return {[number]}\n */\n getExplainedVariance() {\n var sum = 0;\n for (var i = 0; i < this.S.length; i++) {\n sum += this.S[i];\n }\n return this.S.map(value => value / sum);\n }\n\n /**\n * Returns the cumulative proportion of variance\n * @return {[number]}\n */\n getCumulativeVariance() {\n var explained = this.getExplainedVariance();\n for (var i = 1; i < explained.length; i++) {\n explained[i] += explained[i - 1];\n }\n return explained;\n }\n\n /**\n * Returns the Eigenvectors of the covariance matrix\n * @returns {Matrix}\n */\n getEigenvectors() {\n return this.U;\n }\n\n /**\n * Returns the Eigenvalues (on the diagonal)\n * @returns {[number]}\n */\n getEigenvalues() {\n return this.S;\n }\n\n /**\n * Returns the standard deviations of the principal components\n * @returns {[number]}\n */\n getStandardDeviations() {\n return this.S.map(x => Math.sqrt(x));\n }\n\n /**\n * Returns the loadings matrix\n * @return {Matrix}\n */\n getLoadings() {\n return this.U.transpose();\n }\n\n /**\n * Export the current model to a JSON object\n * @return {Object} model\n */\n toJSON() {\n return {\n name: 'PCA',\n center: this.center,\n scale: this.scale,\n means: this.means,\n stdevs: this.stdevs,\n U: this.U,\n S: this.S,\n };\n }\n\n _adjust(dataset, options) {\n this.center = !!options.center;\n this.scale = !!options.scale;\n\n dataset = new Matrix(dataset);\n\n if (this.center) {\n const means = mean(dataset);\n const stdevs = this.scale ? stdev(dataset, means, true) : null;\n this.means = means;\n dataset.subRowVector(means);\n if (this.scale) {\n for (var i = 0; i < stdevs.length; i++) {\n if (stdevs[i] === 0) {\n throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i);\n }\n }\n this.stdevs = stdevs;\n dataset.divRowVector(stdevs);\n }\n }\n\n return dataset;\n }\n\n _computeFromCovarianceMatrix(dataset) {\n const evd = new EVD(dataset, {assumeSymmetric: true});\n this.U = evd.eigenvectorMatrix;\n for (var i = 0; i < this.U.length; i++) {\n this.U[i].reverse();\n }\n this.S = evd.realEigenvalues.reverse();\n }\n}\n\nmodule.exports = PCA;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pca/src/pca.js\n// module id = 86\n// module chunks = 0","module.exports = exports = require('./pls');\nexports.Utils = require('./utils');\nexports.OPLS = require('./opls');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pls/src/index.js\n// module id = 88\n// module chunks = 0","'use strict';\n\nexports.SimpleLinearRegression = exports.SLR = require('ml-regression-simple-linear');\nexports.PolynomialRegression = require('ml-regression-polynomial');\nexports.ExponentialRegression = require('ml-regression-exponential');\nexports.PowerRegression = require('ml-regression-power');\n\nexports.NonLinearRegression = exports.NLR = {\n PotentialRegression: require('./regression/potential-regression')\n};\nexports.KernelRidgeRegression = exports.KRR = require('./regression/kernel-ridge-regression');\n//exports.MultipleLinearRegression = exports.MLR = require('./regression/multiple-linear-regression');\n//exports.MultivariateLinearRegression = exports.MVLR = require('./regression/multivariate-linear-regression');\nexports.PolinomialFitting2D = require('./regression/poly-fit-regression2d');\n\n// robust regressions\nexports.TheilSenRegression = require('ml-regression-theil-sen');\nexports.RobustPolynomialRegression = require('ml-regression-robust-polynomial');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/index.js\n// module id = 89\n// module chunks = 0","//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007\nvar extend = require('extend');\nvar stat = require('ml-stat');\n\nvar defaultOptions = {\n windowSize: 9,\n derivative: 0,\n polynomial: 3,\n};\n\n\nfunction SavitzkyGolay(data, h, options) {\n options = extend({}, defaultOptions, options);\n\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)')\n\n\n if (options.windowSize>data.length)\n throw new RangeError('Window size is higher than the data length '+options.windowSize+\">\"+data.length);\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n if (options.polynomial >= 6)\n console.warn('You should not use polynomial grade higher than 5 if you are' +\n ' not sure that your data arises from such a model. Possible polynomial oscillation problems');\n\n var windowSize = options.windowSize;\n\n var half = Math.floor(windowSize/2);\n var np = data.length;\n var ans = new Array(np);\n var weights = fullWeights(windowSize,options.polynomial,options.derivative);\n var hs = 0;\n var constantH = true;\n if( Object.prototype.toString.call( h ) === '[object Array]' ) {\n constantH = false;\n }\n else{\n hs = Math.pow(h, options.derivative);\n }\n //console.log(\"Constant h: \"+constantH);\n //For the borders\n for(var i=0;i=0 && i < h.length-1){\n hs+= (h[i+1]-h[i]);\n count++;\n }\n }\n return Math.pow(hs/count,derivative);\n}\n\nfunction GramPoly(i,m,k,s){\n var Grampoly = 0;\n if(k>0){\n Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) +\n s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s);\n }\n else{\n if(k==0&&s==0){\n Grampoly=1;\n }\n else{\n Grampoly=0;\n }\n }\n //console.log(Grampoly);\n return Grampoly;\n}\n\nfunction GenFact(a,b){\n var gf=1;\n if(a>=b){\n for(var j=a-b+1;j<=a;j++){\n gf*=j;\n }\n }\n return gf;\n}\n\nfunction Weight(i,t,m,n,s){\n var sum=0;\n for(var k=0;k<=n;k++){\n //console.log(k);\n sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s)\n }\n return sum;\n}\n\n/**\n *\n * @param m Number of points\n * @param n Polynomial grade\n * @param s Derivative\n */\nfunction fullWeights(m,n,s){\n var weights = new Array(m);\n var np = Math.floor(m/2);\n for(var t=-np;t<=np;t++){\n weights[t+np] = new Array(m);\n for(var j=-np;j<=np;j++){\n weights[t+np][j+np]=Weight(j,t,np,n,s);\n }\n }\n return weights;\n}\n\n/*function entropy(data,h,options){\n var trend = SavitzkyGolay(data,h,trendOptions);\n var copy = new Array(data.length);\n var sum = 0;\n var max = 0;\n for(var i=0;i} data\n * @param {number} h\n * @param {Object} options\n * @returns {Array}\n */\nfunction SavitzkyGolay (data, h, options) {\n options = extend({}, defaultOptions, options);\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n\n var C, norm;\n var step = Math.floor(options.windowSize / 2);\n\n if (options.pad === 'pre') {\n data = padArray(data, {size: step, value: options.padValue});\n }\n\n var ans = new Array(data.length - 2*step);\n\n if ((options.windowSize === 5) && (options.polynomial === 2) && ((options.derivative === 1) || (options.derivative === 2))) {\n if (options.derivative === 1) {\n C = [-2,-1,0,1,2];\n norm = 10;\n }\n else {\n C = [2, -1, -2, -1, 2];\n norm = 7;\n }\n }\n else {\n var J = Matrix.ones(options.windowSize, options.polynomial + 1);\n var inic = -(options.windowSize - 1) / 2;\n for (var i = 0; i < J.length; i++) {\n for (var j = 0; j < J[i].length; j++) {\n if ((inic + 1 !== 0) || (j !== 0))\n J[i][j] = Math.pow((inic + i), j);\n }\n }\n var Jtranspose = J.transposeView();\n var Jinv = (Jtranspose.mmul(J)).inverse();\n C = Jinv.mmul(Jtranspose);\n C = C[options.derivative];\n norm = 1;\n }\n var det = norm * Math.pow(h, options.derivative);\n for (var k = step; k < (data.length - step); k++) {\n var d = 0;\n for (var l = 0; l < C.length; l++)\n d += C[l] * data[l + k - step] / det;\n ans[k - step] = d;\n }\n\n if (options.pad === 'post') {\n ans = padArray(ans, {size: step, value: options.padValue});\n }\n\n return ans;\n}\n\nmodule.exports = SavitzkyGolay;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-savitzky-golay/src/index.js\n// module id = 91\n// module chunks = 0","'use strict';\n\nvar NodeSquare = require('./node-square'),\n NodeHexagonal = require('./node-hexagonal');\n\nvar defaultOptions = {\n fields: 3,\n randomizer: Math.random,\n distance: squareEuclidean,\n iterations: 10,\n learningRate: 0.1,\n gridType: 'rect',\n torus: true,\n method: 'random'\n};\n\nfunction SOM(x, y, options, reload) {\n\n this.x = x;\n this.y = y;\n\n options = options || {};\n this.options = {};\n for (var i in defaultOptions) {\n if (options.hasOwnProperty(i)) {\n this.options[i] = options[i];\n } else {\n this.options[i] = defaultOptions[i];\n }\n }\n\n if (typeof this.options.fields === 'number') {\n this.numWeights = this.options.fields;\n } else if (Array.isArray(this.options.fields)) {\n this.numWeights = this.options.fields.length;\n var converters = getConverters(this.options.fields);\n this.extractor = converters.extractor;\n this.creator = converters.creator;\n } else {\n throw new Error('Invalid fields definition');\n }\n\n if (this.options.gridType === 'rect') {\n this.nodeType = NodeSquare;\n this.gridDim = {\n x: x,\n y: y\n };\n } else {\n this.nodeType = NodeHexagonal;\n var hx = this.x - Math.floor(this.y / 2);\n this.gridDim = {\n x: hx,\n y: this.y,\n z: -(0 - hx - this.y)\n };\n }\n\n this.torus = this.options.torus;\n this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance';\n\n this.distance = this.options.distance;\n\n this.maxDistance = getMaxDistance(this.distance, this.numWeights);\n\n if (reload === true) { // For model loading\n this.done = true;\n return;\n }\n if (!(x > 0 && y > 0)) {\n throw new Error('x and y must be positive');\n }\n\n this.times = {\n findBMU: 0,\n adjust: 0\n };\n\n this.randomizer = this.options.randomizer;\n\n this.iterationCount = 0;\n this.iterations = this.options.iterations;\n\n this.startLearningRate = this.learningRate = this.options.learningRate;\n\n this.mapRadius = Math.floor(Math.max(x, y) / 2);\n\n this.algorithmMethod = this.options.method;\n\n this._initNodes();\n\n this.done = false;\n}\n\nSOM.load = function loadModel(model, distance) {\n if (model.name === 'SOM') {\n var x = model.data.length,\n y = model.data[0].length;\n if (distance) {\n model.options.distance = distance;\n } else if (model.options.distance) {\n model.options.distance = eval('(' + model.options.distance + ')');\n }\n var som = new SOM(x, y, model.options, true);\n som.nodes = new Array(x);\n for (var i = 0; i < x; i++) {\n som.nodes[i] = new Array(y);\n for (var j = 0; j < y; j++) {\n som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som);\n }\n }\n return som;\n } else {\n throw new Error('expecting a SOM model');\n }\n};\n\nSOM.prototype.export = function exportModel(includeDistance) {\n if (!this.done) {\n throw new Error('model is not ready yet');\n }\n var model = {\n name: 'SOM'\n };\n model.options = {\n fields: this.options.fields,\n gridType: this.options.gridType,\n torus: this.options.torus\n };\n model.data = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n model.data[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n model.data[i][j] = this.nodes[i][j].weights;\n }\n }\n if (includeDistance) {\n model.options.distance = this.distance.toString();\n }\n return model;\n};\n\nSOM.prototype._initNodes = function initNodes() {\n var now = Date.now(),\n i, j, k;\n this.nodes = new Array(this.x);\n for (i = 0; i < this.x; i++) {\n this.nodes[i] = new Array(this.y);\n for (j = 0; j < this.y; j++) {\n var weights = new Array(this.numWeights);\n for (k = 0; k < this.numWeights; k++) {\n weights[k] = this.randomizer();\n }\n this.nodes[i][j] = new this.nodeType(i, j, weights, this);\n }\n }\n this.times.initNodes = Date.now() - now;\n};\n\nSOM.prototype.setTraining = function setTraining(trainingSet) {\n if (this.trainingSet) {\n throw new Error('training set has already been set');\n }\n var now = Date.now();\n var convertedSet = trainingSet;\n var i, l = trainingSet.length;\n if (this.extractor) {\n convertedSet = new Array(l);\n for (i = 0; i < l; i++) {\n convertedSet[i] = this.extractor(trainingSet[i]);\n }\n }\n this.numIterations = this.iterations * l;\n\n if (this.algorithmMethod === 'random') {\n this.timeConstant = this.numIterations / Math.log(this.mapRadius);\n } else {\n this.timeConstant = l / Math.log(this.mapRadius);\n }\n this.trainingSet = convertedSet;\n this.times.setTraining = Date.now() - now;\n};\n\nSOM.prototype.trainOne = function trainOne() {\n if (this.done) {\n\n return false;\n\n } else if (this.numIterations-- > 0) {\n\n var neighbourhoodRadius,\n trainingValue,\n trainingSetFactor;\n\n if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step\n neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant);\n trainingValue = getRandomValue(this.trainingSet, this.randomizer);\n this._adjust(trainingValue, neighbourhoodRadius);\n this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations);\n } else { // Get next input vector\n trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length);\n neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant);\n trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length];\n this._adjust(trainingValue, neighbourhoodRadius);\n if (((this.iterationCount + 1) % this.trainingSet.length) === 0) {\n this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length));\n }\n }\n\n this.iterationCount++;\n\n return true;\n\n } else {\n\n this.done = true;\n return false;\n\n }\n};\n\nSOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) {\n var now = Date.now(),\n x, y, dist, influence;\n\n var bmu = this._findBestMatchingUnit(trainingValue);\n\n var now2 = Date.now();\n this.times.findBMU += now2 - now;\n\n var radiusLimit = Math.floor(neighbourhoodRadius);\n var xMin = bmu.x - radiusLimit,\n xMax = bmu.x + radiusLimit,\n yMin = bmu.y - radiusLimit,\n yMax = bmu.y + radiusLimit;\n\n for (x = xMin; x <= xMax; x++) {\n var theX = x;\n if (x < 0) {\n theX += this.x;\n } else if (x >= this.x) {\n theX -= this.x;\n }\n for (y = yMin; y <= yMax; y++) {\n var theY = y;\n if (y < 0) {\n theY += this.y;\n } else if (y >= this.y) {\n theY -= this.y;\n }\n\n dist = bmu[this.distanceMethod](this.nodes[theX][theY]);\n\n if (dist < neighbourhoodRadius) {\n influence = Math.exp(-dist / (2 * neighbourhoodRadius));\n this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence);\n }\n\n }\n }\n\n this.times.adjust += (Date.now() - now2);\n\n};\n\nSOM.prototype.train = function train(trainingSet) {\n if (!this.done) {\n this.setTraining(trainingSet);\n while (this.trainOne()) {\n }\n }\n};\n\nSOM.prototype.getConvertedNodes = function getConvertedNodes() {\n var result = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n result[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n var node = this.nodes[i][j];\n result[i][j] = this.creator ? this.creator(node.weights) : node.weights;\n }\n }\n return result;\n};\n\nSOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) {\n\n var bmu,\n lowest = Infinity,\n dist;\n\n for (var i = 0; i < this.x; i++) {\n for (var j = 0; j < this.y; j++) {\n dist = this.distance(this.nodes[i][j].weights, candidate);\n if (dist < lowest) {\n lowest = dist;\n bmu = this.nodes[i][j];\n }\n }\n }\n\n return bmu;\n\n};\n\nSOM.prototype.predict = function predict(data, computePosition) {\n if (typeof data === 'boolean') {\n computePosition = data;\n data = null;\n }\n if (!data) {\n data = this.trainingSet;\n }\n if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset\n var self = this;\n return data.map(function (element) {\n return self._predict(element, computePosition);\n });\n } else { // predict a single element\n return this._predict(data, computePosition);\n }\n};\n\nSOM.prototype._predict = function _predict(element, computePosition) {\n if (!Array.isArray(element)) {\n element = this.extractor(element);\n }\n var bmu = this._findBestMatchingUnit(element);\n var result = [bmu.x, bmu.y];\n if (computePosition) {\n result[2] = bmu.getPosition(element);\n }\n return result;\n};\n\n// As seen in http://www.scholarpedia.org/article/Kohonen_network\nSOM.prototype.getQuantizationError = function getQuantizationError() {\n var fit = this.getFit(),\n l = fit.length,\n sum = 0;\n for (var i = 0; i < l; i++) {\n sum += fit[i];\n }\n return sum / l;\n};\n\nSOM.prototype.getFit = function getFit(dataset) {\n if (!dataset) {\n dataset = this.trainingSet;\n }\n var l = dataset.length,\n bmu,\n result = new Array(l);\n for (var i = 0; i < l; i++) {\n bmu = this._findBestMatchingUnit(dataset[i]);\n result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights));\n }\n return result;\n};\n\nfunction getConverters(fields) {\n var l = fields.length,\n normalizers = new Array(l),\n denormalizers = new Array(l);\n for (var i = 0; i < l; i++) {\n normalizers[i] = getNormalizer(fields[i].range);\n denormalizers[i] = getDenormalizer(fields[i].range);\n }\n return {\n extractor: function extractor(value) {\n var result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = normalizers[i](value[fields[i].name]);\n }\n return result;\n },\n creator: function creator(value) {\n var result = {};\n for (var i = 0; i < l; i++) {\n result[fields[i].name] = denormalizers[i](value[i]);\n }\n return result;\n }\n };\n}\n\nfunction getNormalizer(minMax) {\n return function normalizer(value) {\n return (value - minMax[0]) / (minMax[1] - minMax[0]);\n };\n}\n\nfunction getDenormalizer(minMax) {\n return function denormalizer(value) {\n return (minMax[0] + value * (minMax[1] - minMax[0]));\n };\n}\n\nfunction squareEuclidean(a, b) {\n var d = 0;\n for (var i = 0, ii = a.length; i < ii; i++) {\n d += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return d;\n}\n\nfunction getRandomValue(arr, randomizer) {\n return arr[Math.floor(randomizer() * arr.length)];\n}\n\nfunction getMaxDistance(distance, numWeights) {\n var zero = new Array(numWeights),\n one = new Array(numWeights);\n for (var i = 0; i < numWeights; i++) {\n zero[i] = 0;\n one[i] = 1;\n }\n return distance(zero, one);\n}\n\nmodule.exports = SOM;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-som/src/index.js\n// module id = 92\n// module chunks = 0","const HashTable = require('ml-hash-table');\n\nclass SparseMatrix {\n constructor(rows, columns, options = {}) {\n if (rows instanceof SparseMatrix) { // clone\n const other = rows;\n this._init(other.rows, other.columns, other.elements.clone(), other.threshold);\n return;\n }\n\n if (Array.isArray(rows)) {\n const matrix = rows;\n rows = matrix.length;\n options = columns || {};\n columns = matrix[0].length;\n this._init(rows, columns, new HashTable(options), options.threshold);\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n var value = matrix[i][j];\n if (this.threshold && Math.abs(value) < this.threshold) value = 0;\n if (value !== 0) {\n this.elements.set(i * columns + j, matrix[i][j]);\n }\n }\n }\n } else {\n this._init(rows, columns, new HashTable(options), options.threshold);\n }\n }\n\n _init(rows, columns, elements, threshold) {\n this.rows = rows;\n this.columns = columns;\n this.elements = elements;\n this.threshold = threshold || 0;\n }\n \n static eye(rows = 1, columns = rows) {\n const min = Math.min(rows, columns);\n const matrix = new SparseMatrix(rows, columns, {initialCapacity: min});\n for (var i = 0; i < min; i++) {\n matrix.set(i, i, 1);\n }\n return matrix;\n }\n\n clone() {\n return new SparseMatrix(this);\n }\n \n to2DArray() {\n const copy = new Array(this.rows);\n for (var i = 0; i < this.rows; i++) {\n copy[i] = new Array(this.columns);\n for (var j = 0; j < this.columns; j++) {\n copy[i][j] = this.get(i, j);\n }\n }\n return copy;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isSymmetric() {\n if (!this.isSquare()) return false;\n\n var symmetric = true;\n this.forEachNonZero((i, j, v) => {\n if (this.get(j, i) !== v) {\n symmetric = false;\n return false;\n }\n return v;\n });\n return symmetric;\n }\n\n 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 console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');\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\nSparseMatrix.prototype.klass = 'Matrix';\n\nSparseMatrix.identity = SparseMatrix.eye;\nSparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct;\n\nmodule.exports = SparseMatrix;\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\nvar 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 (var operator of operators) {\n for (var i = 1; i < operator.length; i++) {\n SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]}));\n SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]}));\n\n SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]}));\n }\n}\n\nvar methods = [\n ['~', 'not']\n];\n\n[\n 'abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil',\n 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p',\n 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'\n].forEach(function (mathMethod) {\n methods.push(['Math.' + mathMethod, mathMethod]);\n});\n\nfor (var method of methods) {\n for (var i = 1; i < method.length; i++) {\n SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, {name: method[i], method: method[0]}));\n SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, {name: method[i]}));\n }\n}\n\nfunction fillTemplateFunction(template, values) {\n for (var i in values) {\n template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]);\n }\n return template;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-sparse-matrix/src/SparseMatrix.js\n// module id = 93\n// module chunks = 0","'use strict';\nconst Kernel = require('ml-kernel');\nconst stat = require('ml-stat').array;\n\nvar defaultOptions = {\n C: 1,\n tol: 1e-4,\n maxPasses: 10,\n maxIterations: 10000,\n kernel: 'linear',\n alphaTol: 1e-6,\n random: Math.random,\n whitening: true\n};\n\n/**\n * Simplified version of the Sequential Minimal Optimization algorithm for training\n * support vector machines\n * @param {{Object}} options - SVM options\n * @param {Number} [options.C=1] - regularization parameter\n * @param {Number} [options.tol=1e-4] - numerical tolerance\n * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors\n * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing\n * @param {Number} [options.maxIterations=10000] - max number of iterations\n * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels}\n * @param {Function} [options.random=Math.random] - custom random number generator\n * @constructor\n */\nfunction SVM(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions);\n this.b = 0;\n}\n\n/**\n * Train the SVM model\n * @param {Array >} features - training data features\n * @param {Array } labels - training data labels in the domain {1,-1}\n */\nSVM.prototype.train = function (features, labels) {\n if (features.length !== labels.length) {\n throw new Error('Features and labels should have the same length');\n }\n if (features.length < 2) {\n throw new Error('Cannot train with less than 2 observations');\n }\n this._trained = false;\n this._loaded = false;\n this.N = labels.length;\n this.D = features[0].length;\n if (this.options.whitening) {\n this.X = new Array(this.N);\n for (var i = 0; i < this.N; i++) {\n this.X[i] = new Array(this.D);\n }\n this.minMax = new Array(this.D);\n // Apply normalization and keep normalization parameters\n for (var j = 0; j < this.D; j++) {\n var d = new Array(this.N);\n for (i = 0; i < this.N; i++) {\n d[i] = features[i][j];\n }\n this.minMax[j] = stat.minMax(d);\n for (i = 0; i < this.N; i++) {\n this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n }\n } else {\n this.X = features;\n }\n this.Y = labels;\n this.b = 0;\n this.W = undefined;\n\n var kernel = this.kernel.compute(this.X);\n var m = labels.length;\n var alpha = new Array(m).fill(0);\n this.alphas = alpha;\n for (var a = 0; a < m; a++)\n alpha[a] = 0;\n\n var b1 = 0,\n b2 = 0,\n iter = 0,\n passes = 0,\n Ei = 0,\n Ej = 0,\n ai = 0,\n aj = 0,\n L = 0,\n H = 0,\n eta = 0;\n\n while (passes < this.options.maxPasses && iter < this.options.maxIterations) {\n var numChange = 0;\n for (i = 0; i < m; i++) {\n Ei = this._marginOnePrecomputed(i, kernel) - labels[i];\n if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) {\n j = i;\n while (j === i) j = Math.floor(this.options.random() * m);\n Ej = this._marginOnePrecomputed(j, kernel) - labels[j];\n ai = alpha[i];\n aj = alpha[j];\n if (labels[i] === labels[j]) {\n L = Math.max(0, ai + aj - this.options.C);\n H = Math.min(this.options.C, ai + aj);\n } else {\n L = Math.max(0, aj - ai);\n H = Math.min(this.options.C, this.options.C + aj + ai);\n }\n if (Math.abs(L - H) < 1e-4) continue;\n\n eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j];\n if (eta >= 0) continue;\n var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta;\n if (newaj > H)\n newaj = H;\n else if (newaj < L)\n newaj = L;\n if (Math.abs(aj - newaj) < 10e-4) continue;\n alpha[j] = newaj;\n alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj);\n b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j];\n b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j];\n this.b = (b1 + b2) / 2;\n if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1;\n if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2;\n numChange += 1;\n }\n }\n iter++;\n if (numChange === 0)\n passes += 1;\n else\n passes = 0;\n }\n if (iter === this.options.maxIterations) {\n throw new Error('max iterations reached');\n }\n\n this.iterations = iter;\n\n // Compute the weights (useful for fast decision on new test instances when linear SVM)\n if (this.options.kernel === 'linear') {\n this.W = new Array(this.D);\n for (var r = 0; r < this.D; r++) {\n this.W[r] = 0;\n for (var w = 0; w < m; w++)\n this.W[r] += labels[w] * alpha[w] * this.X[w][r];\n }\n }\n\n // Keep only support vectors\n // It will compute decision on new test instances faster\n // We also keep the index of the support vectors\n // in the original data\n var nX = [];\n var nY = [];\n var nAlphas = [];\n this._supportVectorIdx = [];\n for (i = 0; i < this.N; i++) {\n if (this.alphas[i] > this.options.alphaTol) {\n nX.push(this.X[i]);\n nY.push(labels[i]);\n nAlphas.push(this.alphas[i]);\n this._supportVectorIdx.push(i);\n\n }\n }\n this.X = nX;\n this.Y = nY;\n this.N = nX.length;\n this.alphas = nAlphas;\n\n\n // A flag to say this SVM has been trained\n this._trained = true;\n};\n\n/**\n * Get prediction ({-1,1}) given one observation's features.\n * @private\n * @param p The observation's features.\n * @returns {number} Classification result ({-1,1})\n */\nSVM.prototype.predictOne = function (p) {\n var margin = this.marginOne(p);\n return margin > 0 ? 1 : -1;\n};\n\n/**\n * Predict the classification outcome of a trained svm given one or several observations' features.\n * @param {Array} features - The observation(s)' features\n * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation\n * is given\n */\nSVM.prototype.predict = function (features) {\n if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first');\n if (Array.isArray(features) && Array.isArray(features[0])) {\n return features.map(this.predictOne.bind(this));\n } else {\n return this.predictOne(features);\n }\n};\n\n/**\n * Get margin given one observation's features\n * @private\n * @param {Array} features - Features\n * @returns {Number} - The computed margin\n */\nSVM.prototype.marginOne = function (features, noWhitening) {\n // Apply normalization\n if (this.options.whitening && !noWhitening) {\n features = this._applyWhitening(features);\n }\n var ans = this.b, i;\n if (this.options.kernel === 'linear' && this.W) {\n // Use weights, it's faster\n for (i = 0; i < this.W.length; i++) {\n ans += this.W[i] * features[i];\n }\n } else {\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0];\n }\n }\n return ans;\n};\n\n\n/**\n * Get a margin using the precomputed kernel. Much faster than normal margin computation\n * @private\n * @param {Number} index - Train data index\n * @param {Array< Array >} kernel - The precomputed kernel\n * @returns {number} Computed margin\n * @private\n */\nSVM.prototype._marginOnePrecomputed = function (index, kernel) {\n var ans = this.b, i;\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * kernel[index][i];\n }\n return ans;\n};\n\n\n/**\n * Returns the margin of one or several observations given its features\n * @param {Array >|Array} features - Features from on or several observations.\n * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if\n * only one observation's features given\n */\nSVM.prototype.margin = function (features) {\n if (Array.isArray(features)) {\n return features.map(this.marginOne.bind(this));\n } else {\n return this.marginOne(features);\n }\n};\n\n/**\n * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances\n * created from {@link #SVM.load load} if linear kernel\n * @returns {Array} The indices in the training vector of the support vectors\n */\nSVM.prototype.supportVectors = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first');\n if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them');\n return this._supportVectorIdx;\n};\n\n/**\n * Create a SVM instance from a saved model\n * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON}\n * @returns {SVM} Instance of svm classifier\n */\nSVM.load = function (model) {\n this._loaded = true;\n this._trained = false;\n var svm = new SVM(model.options);\n if (model.options.kernel === 'linear') {\n svm.W = model.W.slice();\n svm.D = svm.W.length;\n } else {\n svm.X = model.X.slice();\n svm.Y = model.Y.slice();\n svm.alphas = model.alphas.slice();\n svm.N = svm.X.length;\n svm.D = svm.X[0].length;\n }\n svm.minMax = model.minMax;\n svm.b = model.b;\n svm._loaded = true;\n svm._trained = false;\n return svm;\n};\n\n/**\n * Export the minimal object that enables to reload the model\n * @returns {Object} Model object that can be reused with {@link #SVM.load load}\n */\nSVM.prototype.toJSON = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first');\n var model = {};\n model.options = Object.assign({}, this.options);\n model.b = this.b;\n model.minMax = this.minMax;\n if (model.options.kernel === 'linear') {\n model.W = this.W.slice();\n } else {\n // Exporting non-linear models is heavier\n model.X = this.X.slice();\n model.Y = this.Y.slice();\n model.alphas = this.alphas.slice();\n }\n return model;\n};\n\nSVM.prototype._applyWhitening = function (features) {\n if (!this.minMax) throw new Error('Could not apply whitening');\n var whitened = new Array(features.length);\n for (var j = 0; j < features.length; j++) {\n whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n return whitened;\n};\n\nmodule.exports = SVM;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-svm/src/svm.js\n// module id = 94\n// module chunks = 0","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar LOOP = 8;\nvar FLOAT_MUL = 1 / 16777216;\n\nfunction multiply_uint32(n, m) {\n n >>>= 0;\n m >>>= 0;\n var nlo = n & 0xffff;\n var nhi = n - nlo;\n return (nhi * m >>> 0) + nlo * m >>> 0;\n}\n\nvar XSadd = (function () {\n function XSadd() {\n var seed = arguments.length <= 0 || arguments[0] === undefined ? Date.now() : arguments[0];\n\n _classCallCheck(this, XSadd);\n\n this.state = new Uint32Array(4);\n this.init(seed);\n }\n\n _createClass(XSadd, [{\n key: \"init\",\n value: function init(seed) {\n this.state[0] = seed;\n this.state[1] = 0;\n this.state[2] = 0;\n this.state[3] = 0;\n for (var i = 1; i < LOOP; i++) {\n this.state[i & 3] ^= i + multiply_uint32(1812433253, this.state[i - 1 & 3] ^ this.state[i - 1 & 3] >>> 30 >>> 0) >>> 0;\n }\n period_certification(this);\n for (var i = 0; i < LOOP; i++) {\n next_state(this);\n }\n }\n\n /**\n * Returns a 32-bit integer r (0 <= r < 2^32)\n */\n }, {\n key: \"getUint32\",\n value: function getUint32() {\n next_state(this);\n return this.state[3] + this.state[2] >>> 0;\n }\n\n /**\n * Returns a floating point number r (0.0 <= r < 1.0)\n */\n }, {\n key: \"getFloat\",\n value: function getFloat() {\n return (this.getUint32() >>> 8) * FLOAT_MUL;\n }\n }, {\n key: \"random\",\n get: function get() {\n if (!this._random) {\n this._random = this.getFloat.bind(this);\n }\n return this._random;\n }\n }]);\n\n return XSadd;\n})();\n\nexports[\"default\"] = XSadd;\n\nfunction period_certification(xsadd) {\n if (xsadd.state[0] === 0 && xsadd.state[1] === 0 && xsadd.state[2] === 0 && xsadd.state[3] === 0) {\n xsadd.state[0] = 88; // X\n xsadd.state[1] = 83; // S\n xsadd.state[2] = 65; // A\n xsadd.state[3] = 68; // D\n }\n}\n\nvar sh1 = 15;\nvar sh2 = 18;\nvar sh3 = 11;\nfunction next_state(xsadd) {\n var t = xsadd.state[0];\n t ^= t << sh1;\n t ^= t >>> sh2;\n t ^= xsadd.state[3] << sh3;\n xsadd.state[0] = xsadd.state[1];\n xsadd.state[1] = xsadd.state[2];\n xsadd.state[2] = xsadd.state[3];\n xsadd.state[3] = t;\n}\nmodule.exports = exports[\"default\"];\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-xsadd/xsadd-es5.js\n// module id = 95\n// module chunks = 0","(function(undefined) {\r\n 'use strict';\r\n\r\n // Node.js usage:\r\n //\r\n // var Picker = require('RandomSelection').Picker;\r\n // var greetingPicker = new Picker(['hello', 'hi', 'howdy']);\r\n // var greeting = greetingPicker.pick();\r\n\r\n // Our namespace. Exported members will be attached to this.\r\n var ns;\r\n\r\n // Set our namespace based on whether we are running in Node.js or the browser.\r\n if (typeof module !== 'undefined' && module.exports) {\r\n // We are running in Node.\r\n ns = module.exports;\r\n }\r\n else {\r\n // We are running in the browser.\r\n // `this` is the `window`.\r\n // Use window.RandomSelection as our namespace.\r\n ns = this.RandomSelection = {};\r\n }\r\n\r\n // Gets a shallow copy of the given array.\r\n function clone(arr) {\r\n \tvar newArr = [];\r\n \tfor (var i=0; i y) {\n return 1;\n }\n return 0;\n };\n\n\n /*\n Insert item x in list a, and keep it sorted assuming a is sorted.\n \n If x is already in a, insert it to the right of the rightmost x.\n \n Optional args lo (default 0) and hi (default a.length) bound the slice\n of a to be searched.\n */\n\n insort = function(a, x, lo, hi, cmp) {\n var mid;\n if (lo == null) {\n lo = 0;\n }\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (lo < 0) {\n throw new Error('lo must be non-negative');\n }\n if (hi == null) {\n hi = a.length;\n }\n while (lo < hi) {\n mid = floor((lo + hi) / 2);\n if (cmp(x, a[mid]) < 0) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n };\n\n\n /*\n Push item onto heap, maintaining the heap invariant.\n */\n\n heappush = function(array, item, cmp) {\n if (cmp == null) {\n cmp = defaultCmp;\n }\n array.push(item);\n return _siftdown(array, 0, array.length - 1, cmp);\n };\n\n\n /*\n Pop the smallest item off the heap, maintaining the heap invariant.\n */\n\n heappop = function(array, cmp) {\n var lastelt, returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n lastelt = array.pop();\n if (array.length) {\n returnitem = array[0];\n array[0] = lastelt;\n _siftup(array, 0, cmp);\n } else {\n returnitem = lastelt;\n }\n return returnitem;\n };\n\n\n /*\n Pop and return the current smallest value, and add the new item.\n \n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed size heap. Note that the value\n returned may be larger than item! That constrains reasonable use of\n this routine unless written as part of a conditional replacement:\n if item > array[0]\n item = heapreplace(array, item)\n */\n\n heapreplace = function(array, item, cmp) {\n var returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n returnitem = array[0];\n array[0] = item;\n _siftup(array, 0, cmp);\n return returnitem;\n };\n\n\n /*\n Fast version of a heappush followed by a heappop.\n */\n\n heappushpop = function(array, item, cmp) {\n var _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (array.length && cmp(array[0], item) < 0) {\n _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n _siftup(array, 0, cmp);\n }\n return item;\n };\n\n\n /*\n Transform list into a heap, in-place, in O(array.length) time.\n */\n\n heapify = function(array, cmp) {\n var i, _i, _j, _len, _ref, _ref1, _results, _results1;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n _ref1 = (function() {\n _results1 = [];\n for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n return _results1;\n }).apply(this).reverse();\n _results = [];\n for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n i = _ref1[_i];\n _results.push(_siftup(array, i, cmp));\n }\n return _results;\n };\n\n\n /*\n Update the position of the given item in the heap.\n This function should be called every time the item is being modified.\n */\n\n updateItem = function(array, item, cmp) {\n var pos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n pos = array.indexOf(item);\n if (pos === -1) {\n return;\n }\n _siftdown(array, 0, pos, cmp);\n return _siftup(array, pos, cmp);\n };\n\n\n /*\n Find the n largest elements in a dataset.\n */\n\n nlargest = function(array, n, cmp) {\n var elem, result, _i, _len, _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n result = array.slice(0, n);\n if (!result.length) {\n return result;\n }\n heapify(result, cmp);\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n heappushpop(result, elem, cmp);\n }\n return result.sort(cmp).reverse();\n };\n\n\n /*\n Find the n smallest elements in a dataset.\n */\n\n nsmallest = function(array, n, cmp) {\n var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (n * 10 <= array.length) {\n result = array.slice(0, n).sort(cmp);\n if (!result.length) {\n return result;\n }\n los = result[result.length - 1];\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n if (cmp(elem, los) < 0) {\n insort(result, elem, 0, null, cmp);\n result.pop();\n los = result[result.length - 1];\n }\n }\n return result;\n }\n heapify(array, cmp);\n _results = [];\n for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {\n _results.push(heappop(array, cmp));\n }\n return _results;\n };\n\n _siftdown = function(array, startpos, pos, cmp) {\n var newitem, parent, parentpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n newitem = array[pos];\n while (pos > startpos) {\n parentpos = (pos - 1) >> 1;\n parent = array[parentpos];\n if (cmp(newitem, parent) < 0) {\n array[pos] = parent;\n pos = parentpos;\n continue;\n }\n break;\n }\n return array[pos] = newitem;\n };\n\n _siftup = function(array, pos, cmp) {\n var childpos, endpos, newitem, rightpos, startpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n endpos = array.length;\n startpos = pos;\n newitem = array[pos];\n childpos = 2 * pos + 1;\n while (childpos < endpos) {\n rightpos = childpos + 1;\n if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n childpos = rightpos;\n }\n array[pos] = array[childpos];\n pos = childpos;\n childpos = 2 * pos + 1;\n }\n array[pos] = newitem;\n return _siftdown(array, startpos, pos, cmp);\n };\n\n Heap = (function() {\n Heap.push = heappush;\n\n Heap.pop = heappop;\n\n Heap.replace = heapreplace;\n\n Heap.pushpop = heappushpop;\n\n Heap.heapify = heapify;\n\n Heap.updateItem = updateItem;\n\n Heap.nlargest = nlargest;\n\n Heap.nsmallest = nsmallest;\n\n function Heap(cmp) {\n this.cmp = cmp != null ? cmp : defaultCmp;\n this.nodes = [];\n }\n\n Heap.prototype.push = function(x) {\n return heappush(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pop = function() {\n return heappop(this.nodes, this.cmp);\n };\n\n Heap.prototype.peek = function() {\n return this.nodes[0];\n };\n\n Heap.prototype.contains = function(x) {\n return this.nodes.indexOf(x) !== -1;\n };\n\n Heap.prototype.replace = function(x) {\n return heapreplace(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pushpop = function(x) {\n return heappushpop(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.heapify = function() {\n return heapify(this.nodes, this.cmp);\n };\n\n Heap.prototype.updateItem = function(x) {\n return updateItem(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.clear = function() {\n return this.nodes = [];\n };\n\n Heap.prototype.empty = function() {\n return this.nodes.length === 0;\n };\n\n Heap.prototype.size = function() {\n return this.nodes.length;\n };\n\n Heap.prototype.clone = function() {\n var heap;\n heap = new Heap();\n heap.nodes = this.nodes.slice(0);\n return heap;\n };\n\n Heap.prototype.toArray = function() {\n return this.nodes.slice(0);\n };\n\n Heap.prototype.insert = Heap.prototype.push;\n\n Heap.prototype.top = Heap.prototype.peek;\n\n Heap.prototype.front = Heap.prototype.peek;\n\n Heap.prototype.has = Heap.prototype.contains;\n\n Heap.prototype.copy = Heap.prototype.clone;\n\n return Heap;\n\n })();\n\n (function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n return define([], factory);\n } else if (typeof exports === 'object') {\n return module.exports = factory();\n } else {\n return root.Heap = factory();\n }\n })(this, function() {\n return Heap;\n });\n\n}).call(this);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/heap/lib/heap.js\n// module id = 99\n// module chunks = 0","'use strict';\n\nconst Stat = require('ml-stat').array;\n/**\n * Function that returns an array of points given 1D array as follows:\n *\n * [x1, y1, .. , x2, y2, ..]\n *\n * And receive the number of dimensions of each point.\n * @param array\n * @param dimensions\n * @returns {Array} - Array of points.\n */\nfunction coordArrayToPoints(array, dimensions) {\n if(array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var length = array.length / dimensions;\n var pointsArr = new Array(length);\n\n var k = 0;\n for(var i = 0; i < array.length; i += dimensions) {\n var point = new Array(dimensions);\n for(var j = 0; j < dimensions; ++j) {\n point[j] = array[i + j];\n }\n\n pointsArr[k] = point;\n k++;\n }\n\n return pointsArr;\n}\n\n\n/**\n * Function that given an array as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * Returns an array as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * And receives the number of dimensions of each coordinate.\n * @param array\n * @param dimensions\n * @returns {Array} - Matrix of coordinates\n */\nfunction coordArrayToCoordMatrix(array, dimensions) {\n if(array.length % dimensions !== 0) {\n throw new RangeError('Dimensions number must be accordance with the size of the array.');\n }\n\n var coordinatesArray = new Array(dimensions);\n var points = array.length / dimensions;\n for (var i = 0; i < coordinatesArray.length; i++) {\n coordinatesArray[i] = new Array(points);\n }\n\n for(i = 0; i < array.length; i += dimensions) {\n for(var j = 0; j < dimensions; ++j) {\n var currentPoint = Math.floor(i / dimensions);\n coordinatesArray[j][currentPoint] = array[i + j];\n }\n }\n\n return coordinatesArray;\n}\n\n/**\n * Function that receives a coordinate matrix as follows:\n * [[x1, x2, ..], [y1, y2, ..], [ .. ]]\n *\n * Returns an array of coordinates as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param coordMatrix\n * @returns {Array}\n */\nfunction coordMatrixToCoordArray(coordMatrix) {\n var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length);\n var k = 0;\n for(var i = 0; i < coordMatrix[0].length; ++i) {\n for(var j = 0; j < coordMatrix.length; ++j) {\n coodinatesArray[k] = coordMatrix[j][i];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Tranpose a matrix, this method is for coordMatrixToPoints and\n * pointsToCoordMatrix, that because only transposing the matrix\n * you can change your representation.\n *\n * @param matrix\n * @returns {Array}\n */\nfunction transpose(matrix) {\n var resultMatrix = new Array(matrix[0].length);\n for(var i = 0; i < resultMatrix.length; ++i) {\n resultMatrix[i] = new Array(matrix.length);\n }\n\n for (i = 0; i < matrix.length; ++i) {\n for(var j = 0; j < matrix[0].length; ++j) {\n resultMatrix[j][i] = matrix[i][j];\n }\n }\n\n return resultMatrix;\n}\n\n/**\n * Function that transform an array of points into a coordinates array\n * as follows:\n * [x1, y1, .. , x2, y2, ..]\n *\n * @param points\n * @returns {Array}\n */\nfunction pointsToCoordArray(points) {\n var coodinatesArray = new Array(points.length * points[0].length);\n var k = 0;\n for(var i = 0; i < points.length; ++i) {\n for(var j = 0; j < points[0].length; ++j) {\n coodinatesArray[k] = points[i][j];\n ++k;\n }\n }\n\n return coodinatesArray;\n}\n\n/**\n * Apply the dot product between the smaller vector and a subsets of the\n * largest one.\n *\n * @param firstVector\n * @param secondVector\n * @returns {Array} each dot product of size of the difference between the\n * larger and the smallest one.\n */\nfunction applyDotProduct(firstVector, secondVector) {\n var largestVector, smallestVector;\n if(firstVector.length <= secondVector.length) {\n smallestVector = firstVector;\n largestVector = secondVector;\n } else {\n smallestVector = secondVector;\n largestVector = firstVector;\n }\n\n var difference = largestVector.length - smallestVector.length + 1;\n var dotProductApplied = new Array(difference);\n\n for (var i = 0; i < difference; ++i) {\n var sum = 0;\n for (var j = 0; j < smallestVector.length; ++j) {\n sum += smallestVector[j] * largestVector[i + j];\n }\n dotProductApplied[i] = sum;\n }\n\n return dotProductApplied;\n}\n/**\n * To scale the input array between the specified min and max values. The operation is performed inplace\n * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling\n * will multiply the input array by min/min(input) or max/max(input)\n * @param input\n * @param options\n * @returns {*}\n */\nfunction scale(input, options){\n var y;\n if(options.inPlace){\n y = input;\n }\n else{\n y = new Array(input.length);\n }\n const max = options.max;\n const min = options.min;\n if(typeof max === \"number\"){\n if(typeof min === \"number\"){\n var minMax = Stat.minMax(input);\n var factor = (max - min)/(minMax.max-minMax.min);\n for(var i=0;i< y.length;i++){\n y[i]=(input[i]-minMax.min)*factor+min;\n }\n }\n else{\n var currentMin = Stat.max(input);\n var factor = max/currentMin;\n for(var i=0;i< y.length;i++){\n y[i] = input[i]*factor;\n }\n }\n }\n else{\n if(typeof min === \"number\"){\n var currentMin = Stat.min(input);\n var factor = min/currentMin;\n for(var i=0;i< y.length;i++){\n y[i] = input[i]*factor;\n }\n }\n }\n return y;\n}\n\nmodule.exports = {\n coordArrayToPoints: coordArrayToPoints,\n coordArrayToCoordMatrix: coordArrayToCoordMatrix,\n coordMatrixToCoordArray: coordMatrixToCoordArray,\n coordMatrixToPoints: transpose,\n pointsToCoordArray: pointsToCoordArray,\n pointsToCoordMatrix: transpose,\n applyDotProduct: applyDotProduct,\n scale:scale\n};\n\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-array-utils/src/ArrayUtils.js\n// module id = 100\n// module chunks = 0","'use strict';\n\n/**\n *\n * Function that returns a Number array of equally spaced numberOfPoints\n * containing a representation of intensities of the spectra arguments x\n * and y.\n *\n * The options parameter contains an object in the following form:\n * from: starting point\n * to: last point\n * numberOfPoints: number of points between from and to\n * variant: \"slot\" or \"smooth\" - smooth is the default option\n *\n * The slot variant consist that each point in the new array is calculated\n * averaging the existing points between the slot that belongs to the current\n * value. The smooth variant is the same but takes the integral of the range\n * of the slot and divide by the step size between two points in the new array.\n *\n * @param x - sorted increasing x values\n * @param y\n * @param options\n * @returns {Array} new array with the equally spaced data.\n *\n */\nfunction getEquallySpacedData(x, y, options) {\n if (x.length>1 && x[0]>x[1]) {\n x=x.slice().reverse();\n y=y.slice().reverse();\n }\n\n var xLength = x.length;\n if(xLength !== y.length)\n throw new RangeError(\"the x and y vector doesn't have the same size.\");\n\n if (options === undefined) options = {};\n\n var from = options.from === undefined ? x[0] : options.from\n if (isNaN(from) || !isFinite(from)) {\n throw new RangeError(\"'From' value must be a number\");\n }\n var to = options.to === undefined ? x[x.length - 1] : options.to;\n if (isNaN(to) || !isFinite(to)) {\n throw new RangeError(\"'To' value must be a number\");\n }\n\n var reverse = from > to;\n if(reverse) {\n var temp = from;\n from = to;\n to = temp;\n }\n\n var numberOfPoints = options.numberOfPoints === undefined ? 100 : options.numberOfPoints;\n if (isNaN(numberOfPoints) || !isFinite(numberOfPoints)) {\n throw new RangeError(\"'Number of points' value must be a number\");\n }\n if(numberOfPoints < 1)\n throw new RangeError(\"the number of point must be higher than 1\");\n\n var algorithm = options.variant === \"slot\" ? \"slot\" : \"smooth\"; // default value: smooth\n\n var output = algorithm === \"slot\" ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints);\n\n return reverse ? output.reverse() : output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"smooth\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"smooth\"\n */\nfunction getEquallySpacedSmooth(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n var initialOriginalStep = x[1] - x[0];\n var lastOriginalStep = x[x.length - 1] - x[x.length - 2];\n\n // Init main variables\n var min = start;\n var max = start + step;\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 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 j++;\n\n if (j === numberOfPoints)\n break main;\n\n min = max;\n max += step;\n sumAtMin = sumAtMax;\n }\n\n if(previousX <= min && min <= nextX) {\n add = integral(0, min - previousX, slope, previousY);\n sumAtMin = currentValue + add;\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 // updating parameters\n slope = getSlope(previousX, previousY, nextX, nextY);\n intercept = -slope*previousX + previousY;\n }\n\n return output;\n}\n\n/**\n * function that retrieves the getEquallySpacedData with the variant \"slot\"\n *\n * @param x\n * @param y\n * @param from - Initial point\n * @param to - Final point\n * @param numberOfPoints\n * @returns {Array} - Array of y's equally spaced with the variant \"slot\"\n */\nfunction getEquallySpacedSlot(x, y, from, to, numberOfPoints) {\n var xLength = x.length;\n\n var step = (to - from) / (numberOfPoints - 1);\n var halfStep = step / 2;\n var lastStep = x[x.length - 1] - x[x.length - 2];\n\n var start = from - halfStep;\n var output = new Array(numberOfPoints);\n\n // Init main variables\n var min = start;\n var max = start + step;\n\n var previousX = -Number.MAX_VALUE;\n var previousY = 0;\n var nextX = x[0];\n var nextY = y[0];\n var frontOutsideSpectra = 0;\n var backOutsideSpectra = true;\n\n var currentValue = 0;\n\n // for slot algorithm\n var currentPoints = 0;\n\n var i = 1; // index of input\n var j = 0; // index of output\n\n main: while(true) {\n if (previousX>=nextX) throw (new Error('x must be an increasing serie'));\n while (previousX - max > 0) {\n // no overlap with original point, just consume current value\n if(backOutsideSpectra) {\n currentPoints++;\n backOutsideSpectra = false;\n }\n\n output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints;\n j++;\n\n if (j === numberOfPoints)\n break main;\n\n 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 previousX = nextX;\n previousY = nextY;\n\n if (i < xLength) {\n nextX = x[i];\n nextY = y[i];\n i++;\n } else {\n nextX += lastStep;\n nextY = 0;\n frontOutsideSpectra++;\n }\n }\n\n return output;\n}\n/**\n * Function that calculates the integral of the line between two\n * x-coordinates, given the slope and intercept of the line.\n *\n * @param x0\n * @param x1\n * @param slope\n * @param intercept\n * @returns {number} integral value.\n */\nfunction integral(x0, x1, slope, intercept) {\n return (0.5 * slope * x1 * x1 + intercept * x1) - (0.5 * slope * x0 * x0 + intercept * x0);\n}\n\nexports.getEquallySpacedData = getEquallySpacedData;\nexports.integral = integral;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-array-utils/src/getEquallySpaced.js\n// module id = 101\n// module chunks = 0","'use strict';\n\nexports.SNV = SNV;\nvar Stat = require('ml-stat').array;\n\n/**\n * Function that applies the standard normal variate (SNV) to an array of values.\n *\n * @param data - Array of values.\n * @returns {Array} - applied the SNV.\n */\nfunction SNV(data) {\n var mean = Stat.mean(data);\n var std = Stat.standardDeviation(data);\n var result = data.slice();\n for (var i = 0; i < data.length; i++) {\n result[i] = (result[i] - mean) / std;\n }\n return result;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-array-utils/src/snv.js\n// module id = 102\n// module chunks = 0","// auxiliary file to create the 256 look at table elements\n\nvar ans = new Array(256);\nfor (var i = 0; i < 256; i++) {\n var num = i;\n var c = 0;\n while (num) {\n num = num & (num - 1);\n c++;\n }\n ans[i] = c;\n}\n\nmodule.exports = ans;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-bit-array/src/creator.js\n// module id = 103\n// module chunks = 0","'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 if (p[j - 1] === 0) {\n for (i = j - 1; i !== 1; i--)\n p[i] = -1;\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 do\n j++;\n while (p[j] > 0);\n k = j - 1;\n i = j;\n while (p[i] === 0)\n p[i++] = -1;\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\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-combinations/src/index.js\n// module id = 104\n// module chunks = 0","'use strict';\n\n/**\n * ConfusionMatrix class\n */\nclass ConfusionMatrix {\n /**\n * Constructor\n * @param {Array} matrix - The confusion matrix, a 2D Array\n * @param {Array} labels - Labels of the confusion matrix, a 1D Array\n */\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 * Compute the general prediction accuracy\n * @returns {number} - The prediction accuracy ([0-1]\n */\n get accuracy() {\n var correct = 0, 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\n return correct / (correct + incorrect);\n }\n\n /**\n * Compute the number of predicted observations\n * @returns {number} - The number of predicted observations\n */\n get nbPredicted() {\n var 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\nmodule.exports = ConfusionMatrix;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-cross-validation/src/ConfusionMatrix.js\n// module id = 105\n// module chunks = 0","/**\n * Created by acastillo on 8/5/15.\n */\nvar Matrix = require(\"ml-matrix\");\nvar math = require(\"./algebra\");\n\nvar DEBUG = false;\n/** Levenberg Marquardt curve-fitting: minimize sum of weighted squared residuals\n ---------- INPUT VARIABLES -----------\n func = function of n independent variables, 't', and m parameters, 'p',\n returning the simulated model: y_hat = func(t,p,c)\n p = n-vector of initial guess of parameter values\n t = m-vectors or matrix of independent variables (used as arg to func)\n y_dat = m-vectors or matrix of data to be fit by func(t,p)\n weight = weighting vector for least squares fit ( weight >= 0 ) ...\n inverse of the standard measurement errors\n Default: sqrt(d.o.f. / ( y_dat' * y_dat ))\n dp = fractional increment of 'p' for numerical derivatives\n dp(j)>0 central differences calculated\n dp(j)<0 one sided 'backwards' differences calculated\n dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed\n Default: 0.001;\n p_min = n-vector of lower bounds for parameter values\n p_max = n-vector of upper bounds for parameter values\n c = an optional matrix of values passed to func(t,p,c)\n opts = vector of algorithmic parameters\n parameter defaults meaning\n opts(1) = prnt 3 >1 intermediate results; >2 plots\n opts(2) = MaxIter 10*Npar maximum number of iterations\n opts(3) = epsilon_1 1e-3 convergence tolerance for gradient\n opts(4) = epsilon_2 1e-3 convergence tolerance for parameters\n opts(5) = epsilon_3 1e-3 convergence tolerance for Chi-square\n opts(6) = epsilon_4 1e-2 determines acceptance of a L-M step\n opts(7) = lambda_0 1e-2 initial value of L-M paramter\n opts(8) = lambda_UP_fac 11 factor for increasing lambda\n opts(9) = lambda_DN_fac 9 factor for decreasing lambda\n opts(10) = Update_Type 1 1: Levenberg-Marquardt lambda update\n 2: Quadratic update\n 3: Nielsen's lambda update equations\n\n ---------- OUTPUT VARIABLES -----------\n p = least-squares optimal estimate of the parameter values\n X2 = Chi squared criteria\n sigma_p = asymptotic standard error of the parameters\n sigma_y = asymptotic standard error of the curve-fit\n corr = correlation matrix of the parameters\n R_sq = R-squared cofficient of multiple determination\n cvg_hst = convergence history\n\n Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. 22 Sep 2013\n modified from: http://octave.sourceforge.net/optim/function/leasqr.html\n using references by\n Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15.\n Sam Roweis http://www.cs.toronto.edu/~roweis/notes/lm.pdf\n Manolis Lourakis http://www.ics.forth.gr/~lourakis/levmar/levmar.pdf\n Hans Nielson http://www2.imm.dtu.dk/~hbn/publ/TR9905.ps\n Mathworks optimization toolbox reference manual\n K. Madsen, H.B., Nielsen, and O. Tingleff\n http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf\n */\nvar LM = {\n\n optimize: function(func,p,t,y_dat,weight,dp,p_min,p_max,c,opts){\n\n var tensor_parameter = 0;\t\t\t// set to 1 of parameter is a tensor\n\n var iteration = 0;\t\t\t// iteration counter\n //func_calls = 0;\t\t\t// running count of function evaluations\n\n if((typeof p[0])!=\"object\"){\n for(var i=0;i< p.length;i++){\n p[i]=[p[i]];\n }\n\n }\n //p = p(:); y_dat = y_dat(:); \t\t// make column vectors\n var i,k;\n var eps = 2^-52;\n var Npar = p.length;//length(p); \t\t\t// number of parameters\n var Npnt = y_dat.length;//length(y_dat);\t\t// number of data points\n var p_old = Matrix.zeros(Npar,1);\t\t// previous set of parameters\n var y_old = Matrix.zeros(Npnt,1);\t\t// previous model, y_old = y_hat(t;p_old)\n var X2 = 1e-2/eps;\t\t\t// a really big initial Chi-sq value\n var X2_old = 1e-2/eps;\t\t\t// a really big initial Chi-sq value\n var J = Matrix.zeros(Npnt,Npar);\n\n\n if (t.length != y_dat.length) {\n console.log('lm.m error: the length of t must equal the length of y_dat');\n\n length_t = t.length;\n length_y_dat = y_dat.length;\n var X2 = 0, corr = 0, sigma_p = 0, sigma_y = 0, R_sq = 0, cvg_hist = 0;\n if (!tensor_parameter) {\n return;\n }\n }\n\n weight = weight||Math.sqrt((Npnt-Npar+1)/(math.multiply(math.transpose(y_dat),y_dat)));\n dp = dp || 0.001;\n p_min = p_min || math.multiply(Math.abs(p),-100);\n p_max = p_max || math.multiply(Math.abs(p),100);\n c = c || 1;\n // Algorithmic Paramters\n //prnt MaxIter eps1 eps2 epx3 eps4 lam0 lamUP lamDN UpdateType\n opts = opts ||[ 3,10*Npar, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 1 ];\n\n var prnt = opts[0];\t// >1 intermediate results; >2 plots\n var MaxIter = opts[1];\t// maximum number of iterations\n var epsilon_1 = opts[2];\t// convergence tolerance for gradient\n var epsilon_2 = opts[3];\t// convergence tolerance for parameter\n var epsilon_3 = opts[4];\t// convergence tolerance for Chi-square\n var epsilon_4 = opts[5];\t// determines acceptance of a L-M step\n var lambda_0 = opts[6];\t// initial value of damping paramter, lambda\n var lambda_UP_fac = opts[7];\t// factor for increasing lambda\n var lambda_DN_fac = opts[8];\t// factor for decreasing lambda\n var Update_Type = opts[9];\t// 1: Levenberg-Marquardt lambda update\n // 2: Quadratic update\n // 3: Nielsen's lambda update equations\n\n if ( tensor_parameter && prnt == 3 ) prnt = 2;\n\n\n if(!dp.length || dp.length == 1){\n var dp_array = new Array(Npar);\n for(var i=0;i 2;\n //this is a big step\n // --- Are parameters [p+h] much better than [p] ?\n var hidx = new Array(idx.length);\n for(k=0;k epsilon_4 ) {\t\t// it IS significantly better\n //console.log(\"Here\");\n dX2 = X2 - X2_old;\n X2_old = X2;\n p_old = p;\n y_old = y_hat;\n p = p_try;\t\t\t// accept p_try\n\n result = this.lm_matx(func, t, p_old, y_old, dX2, J, p, y_dat, weight_sq, dp, c);\n JtWJ = result.JtWJ,JtWdy=result.JtWdy,X2=result.Chi_sq,y_hat=result.y_hat,J=result.J;\n // decrease lambda ==> Gauss-Newton method\n\n switch (Update_Type) {\n case 1:\t\t\t\t\t\t\t// Levenberg\n lambda = Math.max(lambda / lambda_DN_fac, 1.e-7);\n break;\n case 2:\t\t\t\t\t\t\t// Quadratic\n lambda = Math.max(lambda / (1 + alpha), 1.e-7);\n break;\n case 3:\t\t\t\t\t\t\t// Nielsen\n lambda = math.multiply(Math.max(1 / 3, 1 - (2 * rho - 1) ^ 3),lambda);\n nu = 2;\n break;\n }\n }\n else {\t\t\t\t\t// it IS NOT better\n X2 = X2_old;\t\t\t// do not accept p_try\n if (iteration%(2 * Npar)==0) {\t// rank-1 update of Jacobian\n result = this.lm_matx(func, t, p_old, y_old, -1, J, p, y_dat, weight_sq, dp, c);\n JtWJ = result.JtWJ,JtWdy=result.JtWdy,dX2=result.Chi_sq,y_hat=result.y_hat,J=result.J;\n }\n\n // increase lambda ==> gradient descent method\n switch (Update_Type) {\n case 1:\t\t\t\t\t\t\t// Levenberg\n lambda = Math.min(lambda * lambda_UP_fac, 1.e7);\n break;\n case 2:\t\t\t\t\t\t\t// Quadratic\n lambda = lambda + Math.abs((X2_try - X2) / 2 / alpha);\n break;\n case 3:\t\t\t\t\t\t// Nielsen\n lambda = lambda * nu;\n nu = 2 * nu;\n break;\n }\n }\n }// --- End of Main Loop\n\n // --- convergence achieved, find covariance and confidence intervals\n\n // equal weights for paramter error analysis\n weight_sq = math.multiply(math.multiply(math.transpose(delta_y),delta_y), Matrix.ones(Npnt,1));\n\n weight_sq.apply(function(i,j){\n weight_sq[i][j] = (Npnt-Nfit+1)/weight_sq[i][j];\n });\n //console.log(weight_sq);\n result = this.lm_matx(func,t,p_old,y_old,-1,J,p,y_dat,weight_sq,dp,c);\n JtWJ = result.JtWJ,JtWdy=result.JtWdy,X2=result.Chi_sq,y_hat=result.y_hat,J=result.J;\n\n /*if nargout > 2\t\t\t\t// standard error of parameters\n covar = inv(JtWJ);\n sigma_p = sqrt(diag(covar));\n end\n\n if nargout > 3\t\t\t\t// standard error of the fit\n // sigma_y = sqrt(diag(J * covar * J'));\t// slower version of below\n sigma_y = zeros(Npnt,1);\n for i=1:Npnt\n sigma_y(i) = J(i,:) * covar * J(i,:)';\n end\n sigma_y = sqrt(sigma_y);\n end\n\n if nargout > 4\t\t\t\t// parameter correlation matrix\n corr = covar ./ [sigma_p*sigma_p'];\n end\n\n if nargout > 5\t\t\t\t// coefficient of multiple determination\n R_sq = corrcoef([y_dat y_hat]);\n R_sq = R_sq(1,2).^2;\n end\n\n if nargout > 6\t\t\t\t// convergence history\n cvg_hst = cvg_hst(1:iteration,:);\n end*/\n\n // endfunction # ---------------------------------------------------------- LM\n\n return { p:p, X2:X2};\n },\n\n lm_FD_J:function(func,t,p,y,dp,c) {\n // J = lm_FD_J(func,t,p,y,{dp},{c})\n //\n // partial derivatives (Jacobian) dy/dp for use with lm.m\n // computed via Finite Differences\n // Requires n or 2n function evaluations, n = number of nonzero values of dp\n // -------- INPUT VARIABLES ---------\n // func = function of independent variables, 't', and parameters, 'p',\n // returning the simulated model: y_hat = func(t,p,c)\n // t = m-vector of independent variables (used as arg to func)\n // p = n-vector of current parameter values\n // y = func(t,p,c) n-vector initialised by user before each call to lm_FD_J\n // dp = fractional increment of p for numerical derivatives\n // dp(j)>0 central differences calculated\n // dp(j)<0 one sided differences calculated\n // dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed\n // Default: 0.001;\n // c = optional vector of constants passed to y_hat = func(t,p,c)\n //---------- OUTPUT VARIABLES -------\n // J = Jacobian Matrix J(i,j)=dy(i)/dp(j)\ti=1:n; j=1:m\n\n // Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. November 2005\n // modified from: ftp://fly.cnuce.cnr.it/pub/software/octave/leasqr/\n // Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15.\n\n var m = y.length;\t\t\t// number of data points\n var n = p.length;\t\t\t// number of parameters\n\n dp = dp || math.multiply( Matrix.ones(n, 1), 0.001);\n\n var ps = p.clone();//JSON.parse(JSON.stringify(p));\n //var ps = $.extend(true, [], p);\n var J = new Matrix(m,n), del =new Array(n); // initialize Jacobian to Zero\n\n for (var j = 0;j < n; j++) {\n //console.log(j+\" \"+dp[j]+\" \"+p[j]+\" \"+ps[j]+\" \"+del[j]);\n del[j] = dp[j]*(1+Math.abs(p[j][0])); // parameter perturbation\n p[j] = [ps[j][0]+del[j]];\t // perturb parameter p(j)\n //console.log(j+\" \"+dp[j]+\" \"+p[j]+\" \"+ps[j]+\" \"+del[j]);\n\n if (del[j] != 0){\n y1 = func(t, p, c);\n //func_calls = func_calls + 1;\n if (dp[j][0] < 0) {\t\t// backwards difference\n //J(:,j) = math.dotDivide(math.subtract(y1, y),del[j]);//. / del[j];\n //console.log(del[j]);\n //console.log(y);\n var column = math.dotDivide(math.subtract(y1, y),del[j]);\n for(var k=0;k< m;k++){\n J[k][j]=column[k][0];\n }\n //console.log(column);\n }\n else{\n p[j][0] = ps[j][0] - del[j];\n //J(:,j) = (y1 - feval(func, t, p, c)). / (2. * del[j]);\n var column = math.dotDivide(math.subtract(y1,func(t,p,c)),2*del[j]);\n for(var k=0;k< m;k++){\n J[k][j]=column[k][0];\n }\n\n }\t\t\t// central difference, additional func call\n }\n\n p[j] = ps[j];\t\t// restore p(j)\n\n }\n //console.log(\"lm_FD_J: \"+ JSON.stringify(J));\n return J;\n\n },\n\n // endfunction # -------------------------------------------------- LM_FD_J\n lm_Broyden_J: function(p_old,y_old,J,p,y){\n // J = lm_Broyden_J(p_old,y_old,J,p,y)\n // carry out a rank-1 update to the Jacobian matrix using Broyden's equation\n //---------- INPUT VARIABLES -------\n // p_old = previous set of parameters\n // y_old = model evaluation at previous set of parameters, y_hat(t;p_old)\n // J = current version of the Jacobian matrix\n // p = current set of parameters\n // y = model evaluation at current set of parameters, y_hat(t;p)\n //---------- OUTPUT VARIABLES -------\n // J = rank-1 update to Jacobian Matrix J(i,j)=dy(i)/dp(j)\ti=1:n; j=1:m\n //console.log(p+\" X \"+ p_old)\n var h = math.subtract(p, p_old);\n\n //console.log(\"hhh \"+h);\n var h_t = math.transpose(h);\n h_t.div(math.multiply(h_t,h));\n\n //console.log(h_t);\n //J = J + ( y - y_old - J*h )*h' / (h'*h);\t// Broyden rank-1 update eq'n\n J = math.add(J, math.multiply(math.subtract(y, math.add(y_old,math.multiply(J,h))),h_t));\n return J;\n // endfunction # ---------------------------------------------- LM_Broyden_J\n },\n\n lm_matx : function (func,t,p_old,y_old,dX2,J,p,y_dat,weight_sq,dp,c,iteration){\n // [JtWJ,JtWdy,Chi_sq,y_hat,J] = this.lm_matx(func,t,p_old,y_old,dX2,J,p,y_dat,weight_sq,{da},{c})\n //\n // Evaluate the linearized fitting matrix, JtWJ, and vector JtWdy,\n // and calculate the Chi-squared error function, Chi_sq\n // Used by Levenberg-Marquard algorithm, lm.m\n // -------- INPUT VARIABLES ---------\n // func = function ofpn independent variables, p, and m parameters, p,\n // returning the simulated model: y_hat = func(t,p,c)\n // t = m-vectors or matrix of independent variables (used as arg to func)\n // p_old = n-vector of previous parameter values\n // y_old = m-vector of previous model ... y_old = y_hat(t;p_old);\n // dX2 = previous change in Chi-squared criteria\n // J = m-by-n Jacobian of model, y_hat, with respect to parameters, p\n // p = n-vector of current parameter values\n // y_dat = n-vector of data to be fit by func(t,p,c)\n // weight_sq = square of the weighting vector for least squares fit ...\n //\t inverse of the standard measurement errors\n // dp = fractional increment of 'p' for numerical derivatives\n // dp(j)>0 central differences calculated\n // dp(j)<0 one sided differences calculated\n // dp(j)=0 sets corresponding partials to zero; i.e. holds p(j) fixed\n // Default: 0.001;\n // c = optional vector of constants passed to y_hat = func(t,p,c)\n //---------- OUTPUT VARIABLES -------\n // JtWJ\t = linearized Hessian matrix (inverse of covariance matrix)\n // JtWdy = linearized fitting vector\n // Chi_sq = Chi-squared criteria: weighted sum of the squared residuals WSSR\n // y_hat = model evaluated with parameters 'p'\n // J = m-by-n Jacobian of model, y_hat, with respect to parameters, p\n\n // Henri Gavin, Dept. Civil & Environ. Engineering, Duke Univ. November 2005\n // modified from: ftp://fly.cnuce.cnr.it/pub/software/octave/leasqr/\n // Press, et al., Numerical Recipes, Cambridge Univ. Press, 1992, Chapter 15.\n\n\n var Npnt = y_dat.length;\t\t// number of data points\n var Npar = p.length;\t\t// number of parameters\n\n dp = dp || 0.001;\n\n\n //var JtWJ = new Matrix.zeros(Npar);\n //var JtWdy = new Matrix.zeros(Npar,1);\n\n var y_hat = func(t,p,c);\t// evaluate model using parameters 'p'\n //func_calls = func_calls + 1;\n //console.log(J);\n if ( (iteration%(2*Npar))==0 || dX2 > 0 ) {\n //console.log(\"Par\");\n J = this.lm_FD_J(func, t, p, y_hat, dp, c);\t\t// finite difference\n }\n else{\n //console.log(\"ImPar\");\n J = this.lm_Broyden_J(p_old, y_old, J, p, y_hat); // rank-1 update\n }\n //console.log(y_dat);\n //console.log(y_hat);\n var delta_y = math.subtract(y_dat, y_hat);\t// residual error between model and data\n //console.log(delta_y[0][0]);\n //console.log(delta_y.rows+\" \"+delta_y.columns+\" \"+JSON.stringify(weight_sq));\n //var Chi_sq = delta_y' * ( delta_y .* weight_sq ); \t// Chi-squared error criteria\n var Chi_sq = math.multiply(math.transpose(delta_y),math.dotMultiply(delta_y,weight_sq));\n //JtWJ = J' * ( J .* ( weight_sq * ones(1,Npar) ) );\n var Jt = math.transpose(J);\n\n //console.log(weight_sq);\n\n var JtWJ = math.multiply(Jt, math.dotMultiply(J,math.multiply(weight_sq, Matrix.ones(1,Npar))));\n\n //JtWdy = J' * ( weight_sq .* delta_y );\n var JtWdy = math.multiply(Jt, math.dotMultiply(weight_sq,delta_y));\n\n\n return {JtWJ:JtWJ,JtWdy:JtWdy,Chi_sq:Chi_sq,y_hat:y_hat,J:J};\n // endfunction # ------------------------------------------------------ LM_MATX\n }\n\n\n\n};\n\nmodule.exports = LM;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-curve-fitting/src/LM.js\n// module id = 106\n// module chunks = 0","'use strict';\n\nmodule.exports = require('./LM');\nmodule.exports.Matrix = require('ml-matrix');\nmodule.exports.Matrix.algebra = require('./algebra');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-curve-fitting/src/index.js\n// module id = 107\n// module chunks = 0","\"use strict\";\n\nexports.additiveSymmetric = require('./distances/additiveSymmetric');\nexports.avg = require('./distances/avg');\nexports.bhattacharyya = require('./distances/bhattacharyya');\nexports.canberra = require('./distances/canberra');\nexports.chebyshev = require('./distances/chebyshev');\nexports.clark = require('./distances/clark');\nexports.czekanowski = require('./distances/czekanowski');\nexports.dice = require('./distances/dice');\nexports.divergence = require('./distances/divergence');\nexports.euclidean = require('ml-distance-euclidean');\nexports.fidelity = require('./distances/fidelity');\nexports.gower = require('./distances/gower');\nexports.harmonicMean = require('./distances/harmonicMean');\nexports.hellinger = require('./distances/hellinger');\nexports.innerProduct = require('./distances/innerProduct');\nexports.intersection = require('./distances/intersection');\nexports.jaccard = require('./distances/jaccard');\nexports.jeffreys = require('./distances/jeffreys');\nexports.jensenDifference = require('./distances/jensenDifference');\nexports.jensenShannon = require('./distances/jensenShannon');\nexports.kdivergence = require('./distances/kdivergence');\nexports.kulczynski = require('./distances/kulczynski');\nexports.kullbackLeibler = require('./distances/kullbackLeibler');\nexports.kumarHassebrook = require('./distances/kumarHassebrook');\nexports.kumarJohnson = require('./distances/kumarJohnson');\nexports.lorentzian = require('./distances/lorentzian');\nexports.manhattan = require('./distances/manhattan');\nexports.matusita = require('./distances/matusita');\nexports.minkowski = require('./distances/minkowski');\nexports.motyka = require('./distances/motyka');\nexports.neyman = require('./distances/neyman');\nexports.pearson = require('./distances/pearson');\nexports.probabilisticSymmetric = require('./distances/probabilisticSymmetric');\nexports.ruzicka = require('./distances/ruzicka');\nexports.soergel = require('./distances/soergel');\nexports.sorensen = require('./distances/sorensen');\nexports.squared = require('./distances/squared');\nexports.squaredChord = require('./distances/squaredChord');\nexports.squaredEuclidean = require('ml-distance-euclidean').squared;\nexports.taneja = require('./distances/taneja');\nexports.tanimoto = require('./distances/tanimoto');\nexports.topsoe = require('./distances/topsoe');\nexports.tree = require('ml-tree-similarity');\nexports.waveHedges = require('./distances/waveHedges');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances.js\n// module id = 108\n// module chunks = 0","module.exports = function additiveSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]);\n }\n return 2 * d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/additiveSymmetric.js\n// module id = 109\n// module chunks = 0","module.exports = function avg(a, b) {\n var ii = a.length,\n max = 0,\n ans = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n ans += aux;\n if (max < aux) {\n max = aux;\n }\n }\n return (max + ans) / 2;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/avg.js\n// module id = 110\n// module chunks = 0","module.exports = function bhattacharyya(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return - Math.log(ans);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/bhattacharyya.js\n// module id = 111\n// module chunks = 0","module.exports = function canberra(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/canberra.js\n// module id = 112\n// module chunks = 0","module.exports = function chebyshev(a, b) {\n var ii = a.length,\n max = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n if (max < aux) {\n max = aux;\n }\n }\n return max;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/chebyshev.js\n// module id = 113\n// module chunks = 0","module.exports = function clark(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])));\n }\n return 2 * d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/clark.js\n// module id = 114\n// module chunks = 0","'use strict';\n\nconst czekanowskiSimilarity = require('../similarities/czekanowski');\n\nmodule.exports = function czekanowskiDistance(a, b) {\n return 1 - czekanowskiSimilarity(a, b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/czekanowski.js\n// module id = 115\n// module chunks = 0","module.exports = function divergence(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]));\n }\n return 2 * d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/divergence.js\n// module id = 116\n// module chunks = 0","module.exports = function fidelity(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/fidelity.js\n// module id = 117\n// module chunks = 0","module.exports = function gower(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]);\n }\n return ans / ii;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/gower.js\n// module id = 118\n// module chunks = 0","module.exports = function harmonicMean(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] * b[i]) / (a[i] + b[i]);\n }\n return 2 * ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/harmonicMean.js\n// module id = 119\n// module chunks = 0","module.exports = function hellinger(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return 2 * Math.sqrt(1 - ans);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/hellinger.js\n// module id = 120\n// module chunks = 0","module.exports = function innerProduct(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/innerProduct.js\n// module id = 121\n// module chunks = 0","module.exports = function jeffreys(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] - b[i]) * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/jeffreys.js\n// module id = 122\n// module chunks = 0","module.exports = function jensenDifference(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += ((a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2) - ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/jensenDifference.js\n// module id = 123\n// module chunks = 0","module.exports = function jensenShannon(a, b) {\n var ii = a.length,\n p = 0,\n q = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n q += b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return (p + q) / 2;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/jensenShannon.js\n// module id = 124\n// module chunks = 0","module.exports = function kdivergence(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kdivergence.js\n// module id = 125\n// module chunks = 0","module.exports = function kullbackLeibler(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kullbackLeibler.js\n// module id = 126\n// module chunks = 0","module.exports = function kumarHassebrook(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (p2 + q2 - p);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kumarHassebrook.js\n// module id = 127\n// module chunks = 0","module.exports = function kumarJohnson(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.pow(a[i] * a[i] - b[i] * b[i],2) / (2 * Math.pow(a[i] * b[i],1.5));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/kumarJohnson.js\n// module id = 128\n// module chunks = 0","module.exports = function lorentzian(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.log(Math.abs(a[i] - b[i]) + 1);\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/lorentzian.js\n// module id = 129\n// module chunks = 0","module.exports = function manhattan(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/manhattan.js\n// module id = 130\n// module chunks = 0","module.exports = function matusita(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return Math.sqrt(2 - 2 * ans);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/matusita.js\n// module id = 131\n// module chunks = 0","module.exports = function minkowski(a, b, p) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.pow(Math.abs(a[i] - b[i]),p);\n }\n return Math.pow(d,(1/p));\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/minkowski.js\n// module id = 132\n// module chunks = 0","module.exports = function neyman(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / a[i];\n }\n return d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/neyman.js\n// module id = 133\n// module chunks = 0","module.exports = function pearson(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / b[i];\n }\n return d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/pearson.js\n// module id = 134\n// module chunks = 0","module.exports = function probabilisticSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return 2 * d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/probabilisticSymmetric.js\n// module id = 135\n// module chunks = 0","module.exports = function ruzicka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i],b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/ruzicka.js\n// module id = 136\n// module chunks = 0","module.exports = function soergel(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/soergel.js\n// module id = 137\n// module chunks = 0","module.exports = function sorensen(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += a[i] + b[i];\n }\n return up / down;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/sorensen.js\n// module id = 138\n// module chunks = 0","module.exports = function squared(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return d;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/squared.js\n// module id = 139\n// module chunks = 0","module.exports = function taneja(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/taneja.js\n// module id = 140\n// module chunks = 0","var tanimotoS = require('./../similarities/tanimoto');\n\nmodule.exports = function tanimoto(a, b, bitvector) {\n if (bitvector)\n return 1 - tanimotoS(a, b, bitvector);\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return (p + q - 2 * m) / (p + q - m);\n }\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/tanimoto.js\n// module id = 141\n// module chunks = 0","module.exports = function topsoe(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/topsoe.js\n// module id = 142\n// module chunks = 0","module.exports = function waveHedges(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += 1 - (Math.min(a[i], b[i]) / Math.max(a[i], b[i]));\n }\n return ans;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/distances/waveHedges.js\n// module id = 143\n// module chunks = 0","\"use strict\";\n\nexports.cosine = require('./similarities/cosine');\nexports.czekanowski = require('./similarities/czekanowski');\nexports.dice = require('./similarities/dice');\nexports.intersection = require('./similarities/intersection');\nexports.jaccard = require('./similarities/jaccard');\nexports.kulczynski = require('./similarities/kulczynski');\nexports.motyka = require('./similarities/motyka');\nexports.pearson = require('./similarities/pearson');\nexports.squaredChord = require('./similarities/squaredChord');\nexports.tanimoto = require('./similarities/tanimoto');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities.js\n// module id = 144\n// module chunks = 0","var diceD = require('./../distances/dice');\n\nmodule.exports = function dice(a, b) {\n return 1 - diceD(a,b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/dice.js\n// module id = 145\n// module chunks = 0","var intersectionD = require('./../distances/intersection');\n\nmodule.exports = function intersection(a, b) {\n return 1 - intersectionD(a,b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/intersection.js\n// module id = 146\n// module chunks = 0","var jaccardD = require('./../distances/jaccard');\n\nmodule.exports = function jaccard(a, b) {\n return 1 - jaccardD(a, b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/jaccard.js\n// module id = 147\n// module chunks = 0","var kulczynskiD = require('./../distances/kulczynski');\n\nmodule.exports = function kulczynski(a, b) {\n return 1 / kulczynskiD(a, b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/kulczynski.js\n// module id = 148\n// module chunks = 0","var motykaD = require('./../distances/motyka');\n\nmodule.exports = function motyka(a, b) {\n return 1 - motykaD(a,b);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-distance/src/similarities/motyka.js\n// module id = 149\n// module chunks = 0","'use strict';\n\nvar stat=require('ml-stat').array;\nvar cosine=require('./cosine');\n\nmodule.exports = function pearson(a, b) {\n var avgA=stat.mean(a);\n var avgB=stat.mean(b);\n\n var newA=new Array(a.length);\n var newB=new Array(b.length);\n for (var i=0; i>} distance - Array of points to be clustered\n * @param {json} options\n * @option isDistanceMatrix: Is the input a distance matrix?\n * @constructor\n */\nfunction agnes(data, options) {\n options = Object.assign({}, defaultOptions, options);\n var len = data.length;\n var distance = data;//If source\n if (!options.isDistanceMatrix) {\n distance = distanceMatrix(data, options.disFunc);\n }\n\n\n // allows to use a string or a given function\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n\n var list = new Array(len);\n for (var i = 0; i < distance.length; i++) {\n list[i] = new ClusterLeaf(i);\n }\n var min = 10e5,\n d = {},\n dis = 0;\n\n while (list.length > 1) {\n // calculates the minimum distance\n d = {};\n min = 10e5;\n for (var j = 0; j < list.length; j++) {\n for (var k = j + 1; k < list.length; k++) {\n var fdistance, sdistance;\n if (list[j] instanceof ClusterLeaf) {\n fdistance = [list[j].index];\n } else {\n fdistance = new Array(list[j].index.length);\n for (var e = 0; e < fdistance.length; e++) {\n fdistance[e] = list[j].index[e].index;\n }\n }\n if (list[k] instanceof ClusterLeaf) {\n sdistance = [list[k].index];\n } else {\n sdistance = new Array(list[k].index.length);\n for (var f = 0; f < sdistance.length; f++) {\n sdistance[f] = list[k].index[f].index;\n }\n }\n dis = options.kind(fdistance, sdistance, distance).toFixed(4);\n if (dis in d) {\n d[dis].push([list[j], list[k]]);\n } else {\n d[dis] = [[list[j], list[k]]];\n }\n min = Math.min(dis, min);\n }\n }\n // cluster dots\n var dmin = d[min.toFixed(4)];\n var clustered = new Array(dmin.length);\n var aux,\n count = 0;\n while (dmin.length > 0) {\n aux = dmin.shift();\n for (var q = 0; q < dmin.length; q++) {\n var int = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) !== -1;\n });\n if (int.length > 0) {\n var diff = dmin[q].filter(function (n) {\n //noinspection JSReferencingMutableVariableFromClosure\n return aux.indexOf(n) === -1;\n });\n aux = aux.concat(diff);\n dmin.splice(q--, 1);\n }\n }\n clustered[count++] = aux;\n }\n clustered.length = count;\n\n for (var ii = 0; ii < clustered.length; ii++) {\n var obj = new Cluster();\n obj.children = clustered[ii].concat();\n obj.distance = min;\n obj.index = new Array(len);\n var indCount = 0;\n for (var jj = 0; jj < clustered[ii].length; jj++) {\n if (clustered[ii][jj] instanceof ClusterLeaf) {\n obj.index[indCount++] = clustered[ii][jj];\n } else {\n indCount += clustered[ii][jj].index.length;\n obj.index = clustered[ii][jj].index.concat(obj.index);\n }\n list.splice((list.indexOf(clustered[ii][jj])), 1);\n }\n obj.index.length = indCount;\n list.push(obj);\n }\n }\n return list[0];\n}\n\nmodule.exports = agnes;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/agnes.js\n// module id = 154\n// module chunks = 0","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\nconst ClusterLeaf = require('./ClusterLeaf');\nconst Cluster = require('./Cluster');\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.min(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = i; j < cluster2.length; j++) {\n var d = disFun(cluster1[i], cluster2[j]);\n m = Math.max(d, m);\n }\n }\n return m;\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++) {\n for (var j = 0; j < cluster2.length; j++) {\n m += disFun(cluster1[i], cluster2[j]);\n }\n }\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]);\n}\n\n/**\n * @private\n * @param {Array >} cluster1\n * @param {Array >} cluster2\n * @param {function} disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n var x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0;\n for (var i = 0; i < cluster1.length; i++) {\n x1 += cluster1[i][0];\n y1 += cluster1[i][1];\n }\n for (var j = 0; j < cluster2.length; j++) {\n x2 += cluster2[j][0];\n y2 += cluster2[j][1];\n }\n x1 /= cluster1.length;\n y1 /= cluster1.length;\n x2 /= cluster2.length;\n y2 /= cluster2.length;\n return disFun([x1, y1], [x2, y2]) * cluster1.length * cluster2.length / (cluster1.length + cluster2.length);\n}\n\n/**\n * @private\n * Returns the most distant point and his distance\n * @param {Array >} splitting - Clusters to split\n * @param {Array >} data - Original data\n * @param {function} disFun - Distance function\n * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant\n */\nfunction diff(splitting, data, disFun) {\n var ans = {\n d: 0,\n p: 0\n };\n\n var Ci = new Array(splitting[0].length);\n for (var e = 0; e < splitting[0].length; e++) {\n Ci[e] = data[splitting[0][e]];\n }\n var Cj = new Array(splitting[1].length);\n for (var f = 0; f < splitting[1].length; f++) {\n Cj[f] = data[splitting[1][f]];\n }\n\n var dist, ndist;\n for (var i = 0; i < Ci.length; i++) {\n dist = 0;\n for (var j = 0; j < Ci.length; j++) {\n if (i !== j) {\n dist += disFun(Ci[i], Ci[j]);\n }\n }\n dist /= (Ci.length - 1);\n ndist = 0;\n for (var k = 0; k < Cj.length; k++) {\n ndist += disFun(Ci[i], Cj[k]);\n }\n ndist /= Cj.length;\n if ((dist - ndist) > ans.d) {\n ans.d = (dist - ndist);\n ans.p = i;\n }\n }\n return ans;\n}\n\nvar defaultOptions = {\n dist: euclidean,\n kind: 'single'\n};\n\n/**\n * @private\n * Intra-cluster distance\n * @param {Array} index\n * @param {Array} data\n * @param {function} disFun\n * @returns {number}\n */\nfunction intrDist(index, data, disFun) {\n var dist = 0,\n count = 0;\n for (var i = 0; i < index.length; i++) {\n for (var j = i; j < index.length; j++) {\n dist += disFun(data[index[i].index], data[index[j].index]);\n count++;\n }\n }\n return dist / count;\n}\n\n/**\n * Splits the higher level clusters\n * @param {Array >} data - Array of points to be clustered\n * @param {json} options\n * @constructor\n */\nfunction diana(data, options) {\n options = Object.assign({}, defaultOptions, options);\n if (typeof options.kind === 'string') {\n switch (options.kind) {\n case 'single':\n options.kind = simpleLink;\n break;\n case 'complete':\n options.kind = completeLink;\n break;\n case 'average':\n options.kind = averageLink;\n break;\n case 'centroid':\n options.kind = centroidLink;\n break;\n case 'ward':\n options.kind = wardLink;\n break;\n default:\n throw new RangeError('Unknown kind of similarity');\n }\n } else if (typeof options.kind !== 'function') {\n throw new TypeError('Undefined kind of similarity');\n }\n var tree = new Cluster();\n tree.children = new Array(data.length);\n tree.index = new Array(data.length);\n for (var ind = 0; ind < data.length; ind++) {\n tree.children[ind] = new ClusterLeaf(ind);\n tree.index[ind] = new ClusterLeaf(ind);\n }\n\n tree.distance = intrDist(tree.index, data, options.dist);\n var m, M, clId,\n dist, rebel;\n var list = [tree];\n while (list.length > 0) {\n M = 0;\n clId = 0;\n for (var i = 0; i < list.length; i++) {\n m = 0;\n for (var j = 0; j < list[i].length; j++) {\n for (var l = (j + 1); l < list[i].length; l++) {\n m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m);\n }\n }\n if (m > M) {\n M = m;\n clId = i;\n }\n }\n M = 0;\n if (list[clId].index.length === 2) {\n list[clId].children = [list[clId].index[0], list[clId].index[1]];\n list[clId].distance = options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]);\n } else if (list[clId].index.length === 3) {\n list[clId].children = [list[clId].index[0], list[clId].index[1], list[clId].index[2]];\n var d = [\n options.dist(data[list[clId].index[0].index], data[list[clId].index[1].index]),\n options.dist(data[list[clId].index[1].index], data[list[clId].index[2].index])\n ];\n list[clId].distance = (d[0] + d[1]) / 2;\n } else {\n var C = new Cluster();\n var sG = new Cluster();\n var splitting = [new Array(list[clId].index.length), []];\n for (var spl = 0; spl < splitting[0].length; spl++) {\n splitting[0][spl] = spl;\n }\n for (var ii = 0; ii < splitting[0].length; ii++) {\n dist = 0;\n for (var jj = 0; jj < splitting[0].length; jj++) {\n if (ii !== jj) {\n dist += options.dist(data[list[clId].index[splitting[0][jj]].index], data[list[clId].index[splitting[0][ii]].index]);\n }\n }\n dist /= (splitting[0].length - 1);\n if (dist > M) {\n M = dist;\n rebel = ii;\n }\n }\n splitting[1] = [rebel];\n splitting[0].splice(rebel, 1);\n dist = diff(splitting, data, options.dist);\n while (dist.d > 0) {\n splitting[1].push(splitting[0][dist.p]);\n splitting[0].splice(dist.p, 1);\n dist = diff(splitting, data, options.dist);\n }\n var fData = new Array(splitting[0].length);\n C.index = new Array(splitting[0].length);\n for (var e = 0; e < fData.length; e++) {\n fData[e] = data[list[clId].index[splitting[0][e]].index];\n C.index[e] = list[clId].index[splitting[0][e]];\n C.children[e] = list[clId].index[splitting[0][e]];\n }\n var sData = new Array(splitting[1].length);\n sG.index = new Array(splitting[1].length);\n for (var f = 0; f < sData.length; f++) {\n sData[f] = data[list[clId].index[splitting[1][f]].index];\n sG.index[f] = list[clId].index[splitting[1][f]];\n sG.children[f] = list[clId].index[splitting[1][f]];\n }\n C.distance = intrDist(C.index, data, options.dist);\n sG.distance = intrDist(sG.index, data, options.dist);\n list.push(C);\n list.push(sG);\n list[clId].children = [C, sG];\n }\n list.splice(clId, 1);\n }\n return tree;\n}\n\nmodule.exports = diana;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-hclust/src/diana.js\n// module id = 155\n// module chunks = 0","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass GaussianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = GaussianKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel-gaussian/gaussian-kernel.js\n// module id = 156\n// module chunks = 0","'use strict';\n\nconst defaultOptions = {\n degree: 1,\n constant: 1,\n scale: 1\n};\n\nclass PolynomialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n\n this.degree = options.degree;\n this.constant = options.constant;\n this.scale = options.scale;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.pow(this.scale * sum + this.constant, this.degree);\n }\n}\n\nmodule.exports = PolynomialKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel-polynomial/polynomial-kernel.js\n// module id = 157\n// module chunks = 0","'use strict';\n\nconst defaultOptions = {\n alpha: 0.01,\n constant: -Math.E\n};\n\nclass SigmoidKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.alpha = options.alpha;\n this.constant = options.constant;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.tanh(this.alpha * sum + this.constant);\n }\n}\n\nmodule.exports = SigmoidKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel-sigmoid/sigmoid-kernel.js\n// module id = 158\n// module chunks = 0","import Matrix from '../matrix';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\nfunction CholeskyDecomposition(value) {\n if (!(this instanceof CholeskyDecomposition)) {\n return new CholeskyDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n if (!value.isSymmetric()) {\n throw new Error('Matrix is not symmetric');\n }\n\n var a = value,\n dimension = a.rows,\n l = new Matrix(dimension, dimension),\n positiveDefinite = true,\n i, j, k;\n\n for (j = 0; j < dimension; j++) {\n var Lrowj = l[j];\n var d = 0;\n for (k = 0; k < j; k++) {\n var Lrowk = l[k];\n var s = 0;\n for (i = 0; i < k; i++) {\n s += Lrowk[i] * Lrowj[i];\n }\n Lrowj[k] = s = (a[j][k] - s) / l[k][k];\n d = d + s * s;\n }\n\n d = a[j][j] - d;\n\n positiveDefinite &= (d > 0);\n l[j][j] = Math.sqrt(Math.max(d, 0));\n for (k = j + 1; k < dimension; k++) {\n l[j][k] = 0;\n }\n }\n\n if (!positiveDefinite) {\n throw new Error('Matrix is not positive definite');\n }\n\n this.L = l;\n}\n\nCholeskyDecomposition.prototype = {\n get lowerTriangularMatrix() {\n return this.L;\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var l = this.L,\n dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n\n var count = value.columns,\n B = value.clone(),\n i, j, k;\n\n for (k = 0; k < dimension; k++) {\n for (j = 0; j < count; j++) {\n for (i = 0; i < k; i++) {\n B[k][j] -= B[i][j] * l[k][i];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n for (k = dimension - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n for (i = k + 1; i < dimension; i++) {\n B[k][j] -= B[i][j] * l[i][k];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n return B;\n }\n};\n\nexport default CholeskyDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/dc/cholesky.js\n// module id = 159\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse, getFilled2DArray} from './util';\n\nconst defaultOptions = {\n assumeSymmetric: false\n};\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\nfunction EigenvalueDecomposition(matrix, options) {\n options = Object.assign({}, defaultOptions, options);\n if (!(this instanceof EigenvalueDecomposition)) {\n return new EigenvalueDecomposition(matrix, options);\n }\n matrix = Matrix.checkMatrix(matrix);\n if (!matrix.isSquare()) {\n throw new Error('Matrix is not a square matrix');\n }\n\n var n = matrix.columns,\n V = getFilled2DArray(n, n, 0),\n d = new Array(n),\n e = new Array(n),\n value = matrix,\n i, j;\n\n var isSymmetric = false;\n if (options.assumeSymmetric) {\n isSymmetric = true;\n } else {\n isSymmetric = matrix.isSymmetric();\n }\n\n if (isSymmetric) {\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = value.get(i, j);\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n var H = getFilled2DArray(n, n, 0),\n ort = new Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H[i][j] = value.get(i, j);\n }\n }\n orthes(n, H, ort, V);\n hqr2(n, e, d, V, H);\n }\n\n this.n = n;\n this.e = e;\n this.d = d;\n this.V = V;\n}\n\nEigenvalueDecomposition.prototype = {\n get realEigenvalues() {\n return this.d;\n },\n get imaginaryEigenvalues() {\n return this.e;\n },\n get eigenvectorMatrix() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n var n = this.n,\n e = this.e,\n d = this.d,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X[i][j] = 0;\n }\n X[i][i] = d[i];\n if (e[i] > 0) {\n X[i][i + 1] = e[i];\n } else if (e[i] < 0) {\n X[i][i - 1] = e[i];\n }\n }\n return X;\n }\n};\n\nfunction tred2(n, e, d, V) {\n\n var f, g, h, i, j, k,\n hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n }\n\n for (i = n - 1; i > 0; i--) {\n scale = 0;\n h = 0;\n for (k = 0; k < i; k++) {\n scale = scale + Math.abs(d[k]);\n }\n\n if (scale === 0) {\n e[i] = d[i - 1];\n for (j = 0; j < i; j++) {\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n V[j][i] = 0;\n }\n } else {\n for (k = 0; k < i; k++) {\n d[k] /= scale;\n h += d[k] * d[k];\n }\n\n f = d[i - 1];\n g = Math.sqrt(h);\n if (f > 0) {\n g = -g;\n }\n\n e[i] = scale * g;\n h = h - f * g;\n d[i - 1] = f - g;\n for (j = 0; j < i; j++) {\n e[j] = 0;\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n V[j][i] = f;\n g = e[j] + V[j][j] * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V[k][j] * d[k];\n e[k] += V[k][j] * f;\n }\n e[j] = g;\n }\n\n f = 0;\n for (j = 0; j < i; j++) {\n e[j] /= h;\n f += e[j] * d[j];\n }\n\n hh = f / (h + h);\n for (j = 0; j < i; j++) {\n e[j] -= hh * d[j];\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n g = e[j];\n for (k = j; k <= i - 1; k++) {\n V[k][j] -= (f * e[k] + g * d[k]);\n }\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V[n - 1][i] = V[i][i];\n V[i][i] = 1;\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V[k][i + 1] / h;\n }\n\n for (j = 0; j <= i; j++) {\n g = 0;\n for (k = 0; k <= i; k++) {\n g += V[k][i + 1] * V[k][j];\n }\n for (k = 0; k <= i; k++) {\n V[k][j] -= g * d[k];\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V[k][i + 1] = 0;\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n V[n - 1][j] = 0;\n }\n\n V[n - 1][n - 1] = 1;\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n\n var g, h, i, j, k, l, m, p, r,\n dl1, c, c2, c3, el1, s, s2,\n iter;\n\n for (i = 1; i < n; i++) {\n e[i - 1] = e[i];\n }\n\n e[n - 1] = 0;\n\n var f = 0,\n tst1 = 0,\n eps = Math.pow(2, -52);\n\n for (l = 0; l < n; l++) {\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\n m = l;\n while (m < n) {\n if (Math.abs(e[m]) <= eps * tst1) {\n break;\n }\n m++;\n }\n\n if (m > l) {\n iter = 0;\n do {\n iter = iter + 1;\n\n g = d[l];\n p = (d[l + 1] - g) / (2 * e[l]);\n r = hypotenuse(p, 1);\n if (p < 0) {\n r = -r;\n }\n\n d[l] = e[l] / (p + r);\n d[l + 1] = e[l] * (p + r);\n dl1 = d[l + 1];\n h = g - d[l];\n for (i = l + 2; i < n; i++) {\n d[i] -= h;\n }\n\n f = f + h;\n\n p = d[m];\n c = 1;\n c2 = c;\n c3 = c;\n el1 = e[l + 1];\n s = 0;\n s2 = 0;\n for (i = m - 1; i >= l; i--) {\n c3 = c2;\n c2 = c;\n s2 = s;\n g = c * e[i];\n h = c * p;\n r = hypotenuse(p, e[i]);\n e[i + 1] = s * r;\n s = e[i] / r;\n c = p / r;\n p = c * d[i] - s * g;\n d[i + 1] = h + s * (c * g + s * d[i]);\n\n for (k = 0; k < n; k++) {\n h = V[k][i + 1];\n V[k][i + 1] = s * V[k][i] + c * h;\n V[k][i] = c * V[k][i] - s * h;\n }\n }\n\n p = -s * s2 * c3 * el1 * e[l] / dl1;\n e[l] = s * p;\n d[l] = c * p;\n\n }\n while (Math.abs(e[l]) > eps * tst1);\n }\n d[l] = d[l] + f;\n e[l] = 0;\n }\n\n for (i = 0; i < n - 1; i++) {\n k = i;\n p = d[i];\n for (j = i + 1; j < n; j++) {\n if (d[j] < p) {\n k = j;\n p = d[j];\n }\n }\n\n if (k !== i) {\n d[k] = d[i];\n d[i] = p;\n for (j = 0; j < n; j++) {\n p = V[j][i];\n V[j][i] = V[j][k];\n V[j][k] = p;\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n\n var low = 0,\n high = n - 1,\n f, g, h, i, j, m,\n scale;\n\n for (m = low + 1; m <= high - 1; m++) {\n scale = 0;\n for (i = m; i <= high; i++) {\n scale = scale + Math.abs(H[i][m - 1]);\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H[i][m - 1] / scale;\n h += ort[i] * ort[i];\n }\n\n g = Math.sqrt(h);\n if (ort[m] > 0) {\n g = -g;\n }\n\n h = h - ort[m] * g;\n ort[m] = ort[m] - g;\n\n for (j = m; j < n; j++) {\n f = 0;\n for (i = high; i >= m; i--) {\n f += ort[i] * H[i][j];\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H[i][j] -= f * ort[i];\n }\n }\n\n for (i = 0; i <= high; i++) {\n f = 0;\n for (j = high; j >= m; j--) {\n f += ort[j] * H[i][j];\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H[i][j] -= f * ort[j];\n }\n }\n\n ort[m] = scale * ort[m];\n H[m][m - 1] = scale * g;\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = (i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H[m][m - 1] !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H[i][m - 1];\n }\n\n for (j = m; j <= high; j++) {\n g = 0;\n for (i = m; i <= high; i++) {\n g += ort[i] * V[i][j];\n }\n\n g = (g / ort[m]) / H[m][m - 1];\n for (i = m; i <= high; i++) {\n V[i][j] += g * ort[i];\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n var n = nn - 1,\n low = 0,\n high = nn - 1,\n eps = Math.pow(2, -52),\n exshift = 0,\n norm = 0,\n p = 0,\n q = 0,\n r = 0,\n s = 0,\n z = 0,\n iter = 0,\n i, j, k, l, m, t, w, x, y,\n ra, sa, vr, vi,\n notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H[i][i];\n e[i] = 0;\n }\n\n for (j = Math.max(i - 1, 0); j < nn; j++) {\n norm = norm + Math.abs(H[i][j]);\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H[l][l - 1]) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H[n][n] = H[n][n] + exshift;\n d[n] = H[n][n];\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H[n][n - 1] * H[n - 1][n];\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H[n][n] = H[n][n] + exshift;\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\n x = H[n][n];\n\n if (q >= 0) {\n z = (p >= 0) ? (p + z) : (p - z);\n d[n - 1] = x + z;\n d[n] = d[n - 1];\n if (z !== 0) {\n d[n] = x - w / z;\n }\n e[n - 1] = 0;\n e[n] = 0;\n x = H[n][n - 1];\n s = Math.abs(x) + Math.abs(z);\n p = x / s;\n q = z / s;\n r = Math.sqrt(p * p + q * q);\n p = p / r;\n q = q / r;\n\n for (j = n - 1; j < nn; j++) {\n z = H[n - 1][j];\n H[n - 1][j] = q * z + p * H[n][j];\n H[n][j] = q * H[n][j] - p * z;\n }\n\n for (i = 0; i <= n; i++) {\n z = H[i][n - 1];\n H[i][n - 1] = q * z + p * H[i][n];\n H[i][n] = q * H[i][n] - p * z;\n }\n\n for (i = low; i <= high; i++) {\n z = V[i][n - 1];\n V[i][n - 1] = q * z + p * V[i][n];\n V[i][n] = q * V[i][n] - p * z;\n }\n } else {\n d[n - 1] = x + p;\n d[n] = x + p;\n e[n - 1] = z;\n e[n] = -z;\n }\n\n n = n - 2;\n iter = 0;\n } else {\n x = H[n][n];\n y = 0;\n w = 0;\n if (l < n) {\n y = H[n - 1][n - 1];\n w = H[n][n - 1] * H[n - 1][n];\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H[i][i] -= x;\n }\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\n x = y = 0.75 * s;\n w = -0.4375 * s * s;\n }\n\n if (iter === 30) {\n s = (y - x) / 2;\n s = s * s + w;\n if (s > 0) {\n s = Math.sqrt(s);\n if (y < x) {\n s = -s;\n }\n s = x - w / ((y - x) / 2 + s);\n for (i = low; i <= n; i++) {\n H[i][i] -= s;\n }\n exshift += s;\n x = y = w = 0.964;\n }\n }\n\n iter = iter + 1;\n\n m = n - 2;\n while (m >= l) {\n z = H[m][m];\n r = x - z;\n s = y - z;\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\n q = H[m + 1][m + 1] - z - r - s;\n r = H[m + 2][m + 1];\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\n p = p / s;\n q = q / s;\n r = r / s;\n if (m === l) {\n break;\n }\n if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H[i][i - 2] = 0;\n if (i > m + 2) {\n H[i][i - 3] = 0;\n }\n }\n\n for (k = m; k <= n - 1; k++) {\n notlast = (k !== n - 1);\n if (k !== m) {\n p = H[k][k - 1];\n q = H[k + 1][k - 1];\n r = (notlast ? H[k + 2][k - 1] : 0);\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\n if (x !== 0) {\n p = p / x;\n q = q / x;\n r = r / x;\n }\n }\n\n if (x === 0) {\n break;\n }\n\n s = Math.sqrt(p * p + q * q + r * r);\n if (p < 0) {\n s = -s;\n }\n\n if (s !== 0) {\n if (k !== m) {\n H[k][k - 1] = -s * x;\n } else if (l !== m) {\n H[k][k - 1] = -H[k][k - 1];\n }\n\n p = p + s;\n x = p / s;\n y = q / s;\n z = r / s;\n q = q / p;\n r = r / p;\n\n for (j = k; j < nn; j++) {\n p = H[k][j] + q * H[k + 1][j];\n if (notlast) {\n p = p + r * H[k + 2][j];\n H[k + 2][j] = H[k + 2][j] - p * z;\n }\n\n H[k][j] = H[k][j] - p * x;\n H[k + 1][j] = H[k + 1][j] - p * y;\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H[i][k] + y * H[i][k + 1];\n if (notlast) {\n p = p + z * H[i][k + 2];\n H[i][k + 2] = H[i][k + 2] - p * r;\n }\n\n H[i][k] = H[i][k] - p;\n H[i][k + 1] = H[i][k + 1] - p * q;\n }\n\n for (i = low; i <= high; i++) {\n p = x * V[i][k] + y * V[i][k + 1];\n if (notlast) {\n p = p + z * V[i][k + 2];\n V[i][k + 2] = V[i][k + 2] - p * r;\n }\n\n V[i][k] = V[i][k] - p;\n V[i][k + 1] = V[i][k + 1] - p * q;\n }\n }\n }\n }\n }\n\n if (norm === 0) {\n return;\n }\n\n for (n = nn - 1; n >= 0; n--) {\n p = d[n];\n q = e[n];\n\n if (q === 0) {\n l = n;\n H[n][n] = 1;\n for (i = n - 1; i >= 0; i--) {\n w = H[i][i] - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H[i][j] * H[j][n];\n }\n\n if (e[i] < 0) {\n z = w;\n s = r;\n } else {\n l = i;\n if (e[i] === 0) {\n H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm));\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H[i][n] = t;\n H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z);\n }\n\n t = Math.abs(H[i][n]);\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\n H[n - 1][n - 1] = q / H[n][n - 1];\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\n } else {\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\n H[n - 1][n - 1] = cdivres[0];\n H[n - 1][n] = cdivres[1];\n }\n\n H[n][n - 1] = 0;\n H[n][n] = 1;\n for (i = n - 2; i >= 0; i--) {\n ra = 0;\n sa = 0;\n for (j = l; j <= n; j++) {\n ra = ra + H[i][j] * H[j][n - 1];\n sa = sa + H[i][j] * H[j][n];\n }\n\n w = H[i][i] - p;\n\n if (e[i] < 0) {\n z = w;\n r = ra;\n s = sa;\n } else {\n l = i;\n if (e[i] === 0) {\n cdivres = cdiv(-ra, -sa, w, q);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\n vi = (d[i] - p) * 2 * q;\n if (vr === 0 && vi === 0) {\n vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z));\n }\n cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) {\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\n } else {\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\n H[i + 1][n - 1] = cdivres[0];\n H[i + 1][n] = cdivres[1];\n }\n }\n\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n - 1] = H[j][n - 1] / t;\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n for (j = i; j < nn; j++) {\n V[i][j] = H[i][j];\n }\n }\n }\n\n for (j = nn - 1; j >= low; j--) {\n for (i = low; i <= high; i++) {\n z = 0;\n for (k = low; k <= Math.min(j, high); k++) {\n z = z + V[i][k] * H[k][j];\n }\n V[i][j] = z;\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n var r, d;\n if (Math.abs(yr) > Math.abs(yi)) {\n r = yi / yr;\n d = yr + r * yi;\n return [(xr + r * xi) / d, (xi - r * xr) / d];\n } else {\n r = yr / yi;\n d = yi + r * yr;\n return [(r * xr + xi) / d, (r * xi - xr) / d];\n }\n}\n\nexport default EigenvalueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/dc/evd.js\n// module id = 160\n// module chunks = 0","import Matrix from './matrix';\n\nimport LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\n\nexport function inverse(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n return solve(matrix, Matrix.eye(matrix.rows));\n}\n\nexport function solve(leftHandSide, rightHandSide) {\n leftHandSide = Matrix.checkMatrix(leftHandSide);\n rightHandSide = Matrix.checkMatrix(rightHandSide);\n return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/decompositions.js\n// module id = 161\n// module chunks = 0","export {default as default, default as Matrix} from './matrix';\nexport {default as abstractMatrix} from './abstractMatrix';\n\nexport {solve, inverse} from './decompositions';\nexport {default as SingularValueDecomposition, default as SVD} from './dc/svd.js';\nexport {default as EigenvalueDecomposition, default as EVD} from './dc/evd.js';\nexport {default as CholeskyDecomposition, default as CHO} from './dc/cholesky.js';\nexport {default as LuDecomposition, default as LU} from './dc/lu.js';\nexport {default as QrDecomposition, default as QR} from './dc/qr.js';\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/index.js\n// module id = 162\n// module chunks = 0","if (!Symbol.species) {\n Symbol.species = Symbol.for('@@species');\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/symbol-species.js\n// module id = 163\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n super(matrix, matrix.rows, 1);\n this.column = column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.column, value);\n return this;\n }\n\n get(rowIndex) {\n return this.matrix.get(rowIndex, this.column);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/views/column.js\n// module id = 164\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixFlipColumnView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/views/flipColumn.js\n// module id = 165\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixFlipRowView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/views/flipRow.js\n// module id = 166\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n super(matrix, 1, matrix.columns);\n this.row = row;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.row, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.row, columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/views/row.js\n// module id = 167\n// module chunks = 0","import BaseView from './base';\nimport {checkIndices} from '../util';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n var indices = checkIndices(matrix, rowIndices, columnIndices);\n super(matrix, indices.row.length, indices.column.length);\n this.rowIndices = indices.row;\n this.columnIndices = indices.column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/views/selection.js\n// module id = 168\n// module chunks = 0","import BaseView from './base';\nimport {checkRange} from '../util';\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(this.startRow + rowIndex, this.startColumn + columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/views/sub.js\n// module id = 169\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixTransposeView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.columns, matrix.rows);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(columnIndex, rowIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(columnIndex, rowIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/~/ml-matrix/src/views/transpose.js\n// module id = 170\n// module chunks = 0","'use strict';\n\nconst defaultOptions = {\n sigma: 1,\n degree: 1\n};\n\nclass ANOVAKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.degree = options.degree;\n }\n\n compute(x, y) {\n var sum = 0;\n var len = Math.min(x.length, y.length);\n for (var i = 1; i <= len; ++i) {\n sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) -\n Math.pow(y[i - 1], i), 2)), this.degree);\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/anova-kernel.js\n// module id = 171\n// module chunks = 0","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass CauchyKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma));\n }\n}\n\nmodule.exports = CauchyKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/cauchy-kernel.js\n// module id = 172\n// module chunks = 0","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass ExponentialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = ExponentialKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/exponential-kernel.js\n// module id = 173\n// module chunks = 0","'use strict';\n\nclass HistogramIntersectionKernel {\n compute(x, y) {\n var min = Math.min(x.length, y.length);\n var sum = 0;\n for (var i = 0; i < min; ++i) {\n sum += Math.min(x[i], y[i]);\n }\n\n return sum;\n }\n}\n\nmodule.exports = HistogramIntersectionKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/histogram-intersection-kernel.js\n// module id = 174\n// module chunks = 0","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass LaplacianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.sigma);\n }\n}\n\nmodule.exports = LaplacianKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/laplacian-kernel.js\n// module id = 175\n// module chunks = 0","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass MultiquadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant);\n }\n}\n\nmodule.exports = MultiquadraticKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/multiquadratic-kernel.js\n// module id = 176\n// module chunks = 0","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass RationalQuadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return 1 - (distance / (distance + this.constant));\n }\n}\n\nmodule.exports = RationalQuadraticKernel;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kernel/src/kernels/rational-quadratic-kernel.js\n// module id = 177\n// module chunks = 0","'use strict';\n\nconst utils = require('./utils');\nconst distanceSymbol = Symbol('distance');\n\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 */\nfunction KMeansResult(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 */\nKMeansResult.prototype.nearest = function (data) {\n var clusterID = new Array(data.length);\n var centroids = this.centroids.map(function (centroid) {\n return centroid.centroid;\n });\n return utils.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 */\nKMeansResult.prototype.computeInformation = function (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](data[i], this.centroids[this.clusters[i]]);\n enrichedCentroids[this.clusters[i]].size++;\n }\n\n for (var j = 0; j < this.centroids.length; j++) {\n enrichedCentroids[j].error /= enrichedCentroids[j].size;\n }\n\n return new KMeansResult(this.clusters, enrichedCentroids, this.converged, this.iterations, this[distanceSymbol]);\n};\n\nmodule.exports = KMeansResult;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kmeans/src/KMeansResult.js\n// module id = 178\n// module chunks = 0","'use strict';\n\nconst Picker = require('RandomSelection').Picker;\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 * @return {Array>} - Initial random points\n */\nfunction random(data, K) {\n const rand = new Picker(data);\n var ans = new Array(K);\n\n for (var i = 0; i < K; ++i) {\n ans[i] = rand.pick();\n }\n return ans;\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 * @return {Array>} - Initial random points\n */\nfunction mostDistant(data, K, distanceMatrix) {\n var ans = new Array(K);\n\n // chooses a random point as initial cluster\n ans[0] = Math.floor(Math.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\n // minimum distance to centers\n var minDistCent = {dist: Number.MAX_VALUE, index: -1};\n for (var n = 0; n < k; ++n) {\n if (distanceMatrix[n][m] < minDistCent.dist && ans.indexOf(m) === -1) {\n minDistCent = {\n dist: distanceMatrix[n][m],\n index: m\n };\n }\n }\n\n if (minDistCent.dist !== Number.MAX_VALUE && minDistCent.dist > center.dist) {\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\nexports.random = random;\nexports.mostDistant = mostDistant;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-kmeans/src/initialization.js\n// module id = 179\n// module chunks = 0","'use strict';\n\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\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\nfunction kdTree(points, metric, dimensions) {\n\n var self = this;\n\n function buildTree(points, depth, parent) {\n var dim = depth % dimensions.length,\n median,\n node;\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(function (a, b) {\n return a[dimensions[dim]] - b[dimensions[dim]];\n });\n\n median = Math.floor(points.length / 2);\n node = new Node(points[median], dim, parent);\n node.left = buildTree(points.slice(0, median), depth + 1, node);\n node.right = buildTree(points.slice(median + 1), depth + 1, node);\n\n return node;\n }\n\n // Reloads a serialied tree\n function loadTree (data) {\n // Just need to restore the `parent` parameter\n self.root = data;\n\n function 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 restoreParent(self.root);\n }\n\n // If points is not an array, assume we're loading a pre-built tree\n if (!Array.isArray(points)) loadTree(points, metric, dimensions);\n else this.root = buildTree(points, 0, null);\n\n // Convert to a JSON serializable structure; this just requires removing\n // the `parent` property\n this.toJSON = function (src) {\n if (!src) src = this.root;\n var dest = new Node(src.obj, src.dimension, null);\n if (src.left) dest.left = self.toJSON(src.left);\n if (src.right) dest.right = self.toJSON(src.right);\n return dest;\n };\n\n this.insert = function (point) {\n function innerSearch(node, parent) {\n\n if (node === null) {\n return parent;\n }\n\n var dimension = dimensions[node.dimension];\n if (point[dimension] < node.obj[dimension]) {\n return innerSearch(node.left, node);\n } else {\n return innerSearch(node.right, node);\n }\n }\n\n var insertPosition = innerSearch(this.root, null),\n newNode,\n dimension;\n\n if (insertPosition === null) {\n this.root = new Node(point, 0, null);\n return;\n }\n\n newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition);\n dimension = dimensions[insertPosition.dimension];\n\n if (point[dimension] < insertPosition.obj[dimension]) {\n insertPosition.left = newNode;\n } else {\n insertPosition.right = newNode;\n }\n };\n\n this.remove = function (point) {\n var node;\n\n function nodeSearch(node) {\n if (node === null) {\n return null;\n }\n\n if (node.obj === point) {\n return node;\n }\n\n var dimension = dimensions[node.dimension];\n\n if (point[dimension] < node.obj[dimension]) {\n return nodeSearch(node.left, node);\n } else {\n return nodeSearch(node.right, node);\n }\n }\n\n function removeNode(node) {\n var nextNode,\n nextObj,\n pDimension;\n\n function findMin(node, dim) {\n var dimension,\n own,\n left,\n right,\n min;\n\n if (node === null) {\n return null;\n }\n\n dimension = dimensions[dim];\n\n if (node.dimension === dim) {\n if (node.left !== null) {\n return findMin(node.left, dim);\n }\n return node;\n }\n\n own = node.obj[dimension];\n left = findMin(node.left, dim);\n right = findMin(node.right, dim);\n min = node;\n\n if (left !== null && left.obj[dimension] < own) {\n min = left;\n }\n if (right !== null && right.obj[dimension] < min.obj[dimension]) {\n min = right;\n }\n return min;\n }\n\n if (node.left === null && node.right === null) {\n if (node.parent === null) {\n self.root = null;\n return;\n }\n\n pDimension = dimensions[node.parent.dimension];\n\n if (node.obj[pDimension] < node.parent.obj[pDimension]) {\n node.parent.left = null;\n } else {\n node.parent.right = null;\n }\n return;\n }\n\n // If the right subtree is not empty, swap with the minimum element on the\n // node's dimension. If it is empty, we swap the left and right subtrees and\n // do the same.\n if (node.right !== null) {\n nextNode = findMin(node.right, node.dimension);\n nextObj = nextNode.obj;\n removeNode(nextNode);\n node.obj = nextObj;\n } else {\n nextNode = findMin(node.left, node.dimension);\n nextObj = nextNode.obj;\n removeNode(nextNode);\n node.right = node.left;\n node.left = null;\n node.obj = nextObj;\n }\n\n }\n\n node = nodeSearch(self.root);\n\n if (node === null) { return; }\n\n removeNode(node);\n };\n\n this.nearest = function (point, maxNodes, maxDistance) {\n var i,\n result,\n bestNodes;\n\n bestNodes = new BinaryHeap(\n function (e) { return -e[1]; }\n );\n\n function nearestSearch(node) {\n var bestChild,\n dimension = dimensions[node.dimension],\n ownDistance = metric(point, node.obj),\n linearPoint = {},\n linearDistance,\n otherChild,\n i;\n\n function saveNode(node, distance) {\n bestNodes.push([node, distance]);\n if (bestNodes.size() > maxNodes) {\n bestNodes.pop();\n }\n }\n\n for (i = 0; i < dimensions.length; i += 1) {\n if (i === node.dimension) {\n linearPoint[dimensions[i]] = point[dimensions[i]];\n } else {\n linearPoint[dimensions[i]] = node.obj[dimensions[i]];\n }\n }\n\n linearDistance = metric(linearPoint, node.obj);\n\n if (node.right === null && node.left === null) {\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n return;\n }\n\n if (node.right === null) {\n bestChild = node.left;\n } else if (node.left === null) {\n bestChild = node.right;\n } else {\n if (point[dimension] < node.obj[dimension]) {\n bestChild = node.left;\n } else {\n bestChild = node.right;\n }\n }\n\n nearestSearch(bestChild);\n\n if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {\n saveNode(node, ownDistance);\n }\n\n if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {\n if (bestChild === node.left) {\n otherChild = node.right;\n } else {\n otherChild = node.left;\n }\n if (otherChild !== null) {\n nearestSearch(otherChild);\n }\n }\n }\n\n if (maxDistance) {\n for (i = 0; i < maxNodes; i += 1) {\n bestNodes.push([null, maxDistance]);\n }\n }\n\n if(self.root)\n nearestSearch(self.root);\n\n result = [];\n\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 this.balanceFactor = function () {\n function height(node) {\n if (node === null) {\n return 0;\n }\n return Math.max(height(node.left), height(node.right)) + 1;\n }\n\n function count(node) {\n if (node === null) {\n return 0;\n }\n return count(node.left) + count(node.right) + 1;\n }\n\n return height(self.root) / (Math.log(count(self.root)) / Math.log(2));\n };\n}\n\n// Binary heap implementation from:\n// http://eloquentjavascript.net/appendix2.html\n\nfunction BinaryHeap(scoreFunction){\n this.content = [];\n this.scoreFunction = scoreFunction;\n}\n\nBinaryHeap.prototype = {\n push: function(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: function() {\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: function() {\n return this.content[0];\n },\n\n remove: function(node) {\n var len = this.content.length;\n // To remove a value, we must search through the array to find\n // it.\n for (var i = 0; i < len; i++) {\n if (this.content[i] == node) {\n // When it is found, the process seen in 'pop' is repeated\n // to fill up the hole.\n var end = this.content.pop();\n if (i != len - 1) {\n this.content[i] = end;\n if (this.scoreFunction(end) < this.scoreFunction(node))\n this.bubbleUp(i);\n else\n this.sinkDown(i);\n }\n return;\n }\n }\n throw new Error(\"Node not found.\");\n },\n\n size: function() {\n return this.content.length;\n },\n\n bubbleUp: function(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 var parentN = Math.floor((n + 1) / 2) - 1,\n 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 }\n // Found a parent that is less, no need to move it further.\n else {\n break;\n }\n }\n },\n\n sinkDown: function(n) {\n // Look up the target element and its score.\n var length = this.content.length,\n element = this.content[n],\n elemScore = this.scoreFunction(element);\n\n while(true) {\n // Compute the indices of the child elements.\n var child2N = (n + 1) * 2, 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 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 // Do the same checks for the other child.\n if (child2N < length) {\n var child2 = this.content[child2N],\n 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 }\n // Otherwise, we are done.\n else {\n break;\n }\n }\n }\n};\n\nthis.kdTree = kdTree;\n\nexports.kdTree = kdTree;\nexports.BinaryHeap = BinaryHeap;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-knn/src/kdtree.js\n// module id = 180\n// module chunks = 0","'use strict';\n\nmodule.exports = KNN;\n\nvar KDTree = require('./kdtree').kdTree;\nvar Distances = require('ml-distance');\n\n/**\n * K-Nearest neighboor constructor.\n *\n * @param reload - loading purposes.\n * @param model - loading purposes\n * @constructor\n */\nfunction KNN(reload, model) {\n if(reload) {\n this.kdtree = model.kdtree;\n this.k = model.k;\n this.classes = model.classes;\n }\n}\n\n/**\n * Function that trains the KNN with the given trainingSet and trainingLabels.\n * The third argument is an object with the following options.\n * * distance: that represent the distance function applied (default: euclidean)\n * * k: the number of neighboors to take in count for classify (default: number of features + 1)\n *\n * @param trainingSet\n * @param trainingLabels\n * @param options\n */\nKNN.prototype.train = function (trainingSet, trainingLabels, options) {\n if(options === undefined) options = {};\n if(options.distance === undefined) options.distance = Distances.distance.euclidean;\n if(options.k === undefined) options.k = trainingSet[0].length + 1;\n\n var classes = 0;\n var exist = new Array(1000);\n var j = 0;\n for(var i = 0; i < trainingLabels.length; ++i) {\n if(exist.indexOf(trainingLabels[i]) === -1) {\n classes++;\n exist[j] = trainingLabels[i];\n j++;\n }\n }\n\n // copy dataset\n var points = new Array(trainingSet.length);\n for(i = 0; i < points.length; ++i) {\n points[i] = trainingSet[i].slice();\n }\n\n this.features = trainingSet[0].length;\n for(i = 0; i < trainingLabels.length; ++i) {\n points[i].push(trainingLabels[i]);\n }\n\n var dimensions = new Array(trainingSet[0].length);\n for(i = 0; i < dimensions.length; ++i) {\n dimensions[i] = i;\n }\n\n this.kdtree = new KDTree(points, options.distance, dimensions);\n this.k = options.k;\n this.classes = classes;\n};\n\n/**\n * Function that returns the predictions given the dataset.\n * \n * @param dataset\n * @returns {Array}\n */\nKNN.prototype.predict = function (dataset) {\n var predictions = new Array(dataset.length);\n for(var i = 0; i < dataset.length; ++i) {\n predictions[i] = this.getSinglePrediction(dataset[i]);\n }\n\n return predictions;\n};\n\n/**\n * function that returns a prediction for a single case.\n * @param currentCase\n * @returns {number}\n */\nKNN.prototype.getSinglePrediction = function (currentCase) {\n var nearestPoints = this.kdtree.nearest(currentCase, this.k);\n var pointsPerClass = new Array(this.classes);\n var predictedClass = -1;\n var maxPoints = -1;\n var lastElement = nearestPoints[0][0].length - 1;\n\n for(var i = 0; i < pointsPerClass.length; ++i) {\n pointsPerClass[i] = 0;\n }\n\n for(i = 0; i < nearestPoints.length; ++i) {\n var currentClass = nearestPoints[i][0][lastElement];\n var currentPoints = ++pointsPerClass[currentClass];\n if(currentPoints > maxPoints) {\n predictedClass = currentClass;\n maxPoints = currentPoints;\n }\n }\n\n return predictedClass;\n};\n\n/**\n * function that returns a KNN classifier with the given model.\n *\n * @param model\n */\nKNN.load = function (model) {\n if(model.modelName !== \"KNN\")\n throw new RangeError(\"The given model is invalid!\");\n\n return new KNN(true, model);\n};\n\n/**\n * function that exports the current KNN classifier.\n */\nKNN.prototype.export = function () {\n return {\n modelName: \"KNN\",\n kdtree: this.kdtree,\n k: this.k,\n classes: this.classes\n };\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-knn/src/knn.js\n// module id = 181\n// module chunks = 0","'use strict';\n\n/**\n * Calculate current error\n * @ignore\n * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param {Array} parameters - Array of current parameter values\n * @param {function} parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {number}\n */\nfunction errorCalculation(data, parameters, parameterizedFunction) {\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\nmodule.exports = errorCalculation;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-levenberg-marquardt/src/errorCalculation.js\n// module id = 182\n// module chunks = 0","'use strict';\n\nconst Matrix = require('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} 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(data, params, gradientDifference, paramFunction) {\n const n = paramFunction.length;\n const m = data.x.length;\n\n var ans = new Array(n);\n const func = paramFunction(...params);\n\n for (var param = 0; param < n; param++) {\n ans[param] = new Array(m);\n\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] = func(data.x[point]) - funcParam(data.x[point]);\n }\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} params - Array of previous parameter values\n * @param {function} paramFunction - The parameters and returns a function with the independent variable as a parameter\n * @return {Matrix}\n */\nfunction matrixFunction(data, params, paramFunction) {\n const m = data.x.length;\n\n var ans = new Array(m);\n const func = paramFunction(...params);\n\n for (var point = 0; point < m; point++) {\n ans[point] = data.y[point] - func(data.x[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 */\nfunction step(data, params, damping, gradientDifference, parameterizedFunction) {\n var identity = Matrix.eye(parameterizedFunction.length)\n .mul(damping * gradientDifference * gradientDifference);\n var gradientFunc = gradientFunction(data, params, gradientDifference, parameterizedFunction);\n var matrixFunc = matrixFunction(data, params, parameterizedFunction).transpose();\n params = new Matrix([params]);\n\n var inverse = Matrix.inv(identity.add(gradientFunc.mmul(gradientFunc.transposeView())));\n params = params.sub(\n ((inverse.mmul(gradientFunc)).mmul(matrixFunc).mul(gradientDifference)).transposeView()\n );\n return params.to1DArray();\n}\n\nmodule.exports = step;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-levenberg-marquardt/src/step.js\n// module id = 183\n// module chunks = 0","'use strict';\n\nvar Matrix = require('../matrix').Matrix;\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\nfunction CholeskyDecomposition(value) {\n if (!(this instanceof CholeskyDecomposition)) {\n return new CholeskyDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n if (!value.isSymmetric()) {\n throw new Error('Matrix is not symmetric');\n }\n\n var a = value,\n dimension = a.rows,\n l = new Matrix(dimension, dimension),\n positiveDefinite = true,\n i, j, k;\n\n for (j = 0; j < dimension; j++) {\n var Lrowj = l[j];\n var d = 0;\n for (k = 0; k < j; k++) {\n var Lrowk = l[k];\n var s = 0;\n for (i = 0; i < k; i++) {\n s += Lrowk[i] * Lrowj[i];\n }\n Lrowj[k] = s = (a[j][k] - s) / l[k][k];\n d = d + s * s;\n }\n\n d = a[j][j] - d;\n\n positiveDefinite &= (d > 0);\n l[j][j] = Math.sqrt(Math.max(d, 0));\n for (k = j + 1; k < dimension; k++) {\n l[j][k] = 0;\n }\n }\n\n if (!positiveDefinite) {\n throw new Error('Matrix is not positive definite');\n }\n\n this.L = l;\n}\n\nCholeskyDecomposition.prototype = {\n get lowerTriangularMatrix() {\n return this.L;\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var l = this.L,\n dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n\n var count = value.columns,\n B = value.clone(),\n i, j, k;\n\n for (k = 0; k < dimension; k++) {\n for (j = 0; j < count; j++) {\n for (i = 0; i < k; i++) {\n B[k][j] -= B[i][j] * l[k][i];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n for (k = dimension - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n for (i = k + 1; i < dimension; i++) {\n B[k][j] -= B[i][j] * l[i][k];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n return B;\n }\n};\n\nmodule.exports = CholeskyDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/cholesky.js\n// module id = 184\n// module chunks = 0","'use strict';\n\nconst Matrix = require('../matrix').Matrix;\nconst util = require('./util');\nconst hypotenuse = util.hypotenuse;\nconst getFilled2DArray = util.getFilled2DArray;\n\nconst defaultOptions = {\n assumeSymmetric: false\n};\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\nfunction EigenvalueDecomposition(matrix, options) {\n options = Object.assign({}, defaultOptions, options);\n if (!(this instanceof EigenvalueDecomposition)) {\n return new EigenvalueDecomposition(matrix, options);\n }\n matrix = Matrix.checkMatrix(matrix);\n if (!matrix.isSquare()) {\n throw new Error('Matrix is not a square matrix');\n }\n\n var n = matrix.columns,\n V = getFilled2DArray(n, n, 0),\n d = new Array(n),\n e = new Array(n),\n value = matrix,\n i, j;\n\n var isSymmetric = false;\n if (options.assumeSymmetric) {\n isSymmetric = true;\n } else {\n isSymmetric = matrix.isSymmetric();\n }\n\n if (isSymmetric) {\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = value.get(i, j);\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n var H = getFilled2DArray(n, n, 0),\n ort = new Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H[i][j] = value.get(i, j);\n }\n }\n orthes(n, H, ort, V);\n hqr2(n, e, d, V, H);\n }\n\n this.n = n;\n this.e = e;\n this.d = d;\n this.V = V;\n}\n\nEigenvalueDecomposition.prototype = {\n get realEigenvalues() {\n return this.d;\n },\n get imaginaryEigenvalues() {\n return this.e;\n },\n get eigenvectorMatrix() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n var n = this.n,\n e = this.e,\n d = this.d,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X[i][j] = 0;\n }\n X[i][i] = d[i];\n if (e[i] > 0) {\n X[i][i + 1] = e[i];\n } else if (e[i] < 0) {\n X[i][i - 1] = e[i];\n }\n }\n return X;\n }\n};\n\nfunction tred2(n, e, d, V) {\n\n var f, g, h, i, j, k,\n hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n }\n\n for (i = n - 1; i > 0; i--) {\n scale = 0;\n h = 0;\n for (k = 0; k < i; k++) {\n scale = scale + Math.abs(d[k]);\n }\n\n if (scale === 0) {\n e[i] = d[i - 1];\n for (j = 0; j < i; j++) {\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n V[j][i] = 0;\n }\n } else {\n for (k = 0; k < i; k++) {\n d[k] /= scale;\n h += d[k] * d[k];\n }\n\n f = d[i - 1];\n g = Math.sqrt(h);\n if (f > 0) {\n g = -g;\n }\n\n e[i] = scale * g;\n h = h - f * g;\n d[i - 1] = f - g;\n for (j = 0; j < i; j++) {\n e[j] = 0;\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n V[j][i] = f;\n g = e[j] + V[j][j] * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V[k][j] * d[k];\n e[k] += V[k][j] * f;\n }\n e[j] = g;\n }\n\n f = 0;\n for (j = 0; j < i; j++) {\n e[j] /= h;\n f += e[j] * d[j];\n }\n\n hh = f / (h + h);\n for (j = 0; j < i; j++) {\n e[j] -= hh * d[j];\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n g = e[j];\n for (k = j; k <= i - 1; k++) {\n V[k][j] -= (f * e[k] + g * d[k]);\n }\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V[n - 1][i] = V[i][i];\n V[i][i] = 1;\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V[k][i + 1] / h;\n }\n\n for (j = 0; j <= i; j++) {\n g = 0;\n for (k = 0; k <= i; k++) {\n g += V[k][i + 1] * V[k][j];\n }\n for (k = 0; k <= i; k++) {\n V[k][j] -= g * d[k];\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V[k][i + 1] = 0;\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n V[n - 1][j] = 0;\n }\n\n V[n - 1][n - 1] = 1;\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n\n var g, h, i, j, k, l, m, p, r,\n dl1, c, c2, c3, el1, s, s2,\n iter;\n\n for (i = 1; i < n; i++) {\n e[i - 1] = e[i];\n }\n\n e[n - 1] = 0;\n\n var f = 0,\n tst1 = 0,\n eps = Math.pow(2, -52);\n\n for (l = 0; l < n; l++) {\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\n m = l;\n while (m < n) {\n if (Math.abs(e[m]) <= eps * tst1) {\n break;\n }\n m++;\n }\n\n if (m > l) {\n iter = 0;\n do {\n iter = iter + 1;\n\n g = d[l];\n p = (d[l + 1] - g) / (2 * e[l]);\n r = hypotenuse(p, 1);\n if (p < 0) {\n r = -r;\n }\n\n d[l] = e[l] / (p + r);\n d[l + 1] = e[l] * (p + r);\n dl1 = d[l + 1];\n h = g - d[l];\n for (i = l + 2; i < n; i++) {\n d[i] -= h;\n }\n\n f = f + h;\n\n p = d[m];\n c = 1;\n c2 = c;\n c3 = c;\n el1 = e[l + 1];\n s = 0;\n s2 = 0;\n for (i = m - 1; i >= l; i--) {\n c3 = c2;\n c2 = c;\n s2 = s;\n g = c * e[i];\n h = c * p;\n r = hypotenuse(p, e[i]);\n e[i + 1] = s * r;\n s = e[i] / r;\n c = p / r;\n p = c * d[i] - s * g;\n d[i + 1] = h + s * (c * g + s * d[i]);\n\n for (k = 0; k < n; k++) {\n h = V[k][i + 1];\n V[k][i + 1] = s * V[k][i] + c * h;\n V[k][i] = c * V[k][i] - s * h;\n }\n }\n\n p = -s * s2 * c3 * el1 * e[l] / dl1;\n e[l] = s * p;\n d[l] = c * p;\n\n }\n while (Math.abs(e[l]) > eps * tst1);\n }\n d[l] = d[l] + f;\n e[l] = 0;\n }\n\n for (i = 0; i < n - 1; i++) {\n k = i;\n p = d[i];\n for (j = i + 1; j < n; j++) {\n if (d[j] < p) {\n k = j;\n p = d[j];\n }\n }\n\n if (k !== i) {\n d[k] = d[i];\n d[i] = p;\n for (j = 0; j < n; j++) {\n p = V[j][i];\n V[j][i] = V[j][k];\n V[j][k] = p;\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n\n var low = 0,\n high = n - 1,\n f, g, h, i, j, m,\n scale;\n\n for (m = low + 1; m <= high - 1; m++) {\n scale = 0;\n for (i = m; i <= high; i++) {\n scale = scale + Math.abs(H[i][m - 1]);\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H[i][m - 1] / scale;\n h += ort[i] * ort[i];\n }\n\n g = Math.sqrt(h);\n if (ort[m] > 0) {\n g = -g;\n }\n\n h = h - ort[m] * g;\n ort[m] = ort[m] - g;\n\n for (j = m; j < n; j++) {\n f = 0;\n for (i = high; i >= m; i--) {\n f += ort[i] * H[i][j];\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H[i][j] -= f * ort[i];\n }\n }\n\n for (i = 0; i <= high; i++) {\n f = 0;\n for (j = high; j >= m; j--) {\n f += ort[j] * H[i][j];\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H[i][j] -= f * ort[j];\n }\n }\n\n ort[m] = scale * ort[m];\n H[m][m - 1] = scale * g;\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = (i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H[m][m - 1] !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H[i][m - 1];\n }\n\n for (j = m; j <= high; j++) {\n g = 0;\n for (i = m; i <= high; i++) {\n g += ort[i] * V[i][j];\n }\n\n g = (g / ort[m]) / H[m][m - 1];\n for (i = m; i <= high; i++) {\n V[i][j] += g * ort[i];\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n var n = nn - 1,\n low = 0,\n high = nn - 1,\n eps = Math.pow(2, -52),\n exshift = 0,\n norm = 0,\n p = 0,\n q = 0,\n r = 0,\n s = 0,\n z = 0,\n iter = 0,\n i, j, k, l, m, t, w, x, y,\n ra, sa, vr, vi,\n notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H[i][i];\n e[i] = 0;\n }\n\n for (j = Math.max(i - 1, 0); j < nn; j++) {\n norm = norm + Math.abs(H[i][j]);\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H[l][l - 1]) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H[n][n] = H[n][n] + exshift;\n d[n] = H[n][n];\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H[n][n - 1] * H[n - 1][n];\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H[n][n] = H[n][n] + exshift;\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\n x = H[n][n];\n\n if (q >= 0) {\n z = (p >= 0) ? (p + z) : (p - z);\n d[n - 1] = x + z;\n d[n] = d[n - 1];\n if (z !== 0) {\n d[n] = x - w / z;\n }\n e[n - 1] = 0;\n e[n] = 0;\n x = H[n][n - 1];\n s = Math.abs(x) + Math.abs(z);\n p = x / s;\n q = z / s;\n r = Math.sqrt(p * p + q * q);\n p = p / r;\n q = q / r;\n\n for (j = n - 1; j < nn; j++) {\n z = H[n - 1][j];\n H[n - 1][j] = q * z + p * H[n][j];\n H[n][j] = q * H[n][j] - p * z;\n }\n\n for (i = 0; i <= n; i++) {\n z = H[i][n - 1];\n H[i][n - 1] = q * z + p * H[i][n];\n H[i][n] = q * H[i][n] - p * z;\n }\n\n for (i = low; i <= high; i++) {\n z = V[i][n - 1];\n V[i][n - 1] = q * z + p * V[i][n];\n V[i][n] = q * V[i][n] - p * z;\n }\n } else {\n d[n - 1] = x + p;\n d[n] = x + p;\n e[n - 1] = z;\n e[n] = -z;\n }\n\n n = n - 2;\n iter = 0;\n } else {\n x = H[n][n];\n y = 0;\n w = 0;\n if (l < n) {\n y = H[n - 1][n - 1];\n w = H[n][n - 1] * H[n - 1][n];\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H[i][i] -= x;\n }\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\n x = y = 0.75 * s;\n w = -0.4375 * s * s;\n }\n\n if (iter === 30) {\n s = (y - x) / 2;\n s = s * s + w;\n if (s > 0) {\n s = Math.sqrt(s);\n if (y < x) {\n s = -s;\n }\n s = x - w / ((y - x) / 2 + s);\n for (i = low; i <= n; i++) {\n H[i][i] -= s;\n }\n exshift += s;\n x = y = w = 0.964;\n }\n }\n\n iter = iter + 1;\n\n m = n - 2;\n while (m >= l) {\n z = H[m][m];\n r = x - z;\n s = y - z;\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\n q = H[m + 1][m + 1] - z - r - s;\n r = H[m + 2][m + 1];\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\n p = p / s;\n q = q / s;\n r = r / s;\n if (m === l) {\n break;\n }\n if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H[i][i - 2] = 0;\n if (i > m + 2) {\n H[i][i - 3] = 0;\n }\n }\n\n for (k = m; k <= n - 1; k++) {\n notlast = (k !== n - 1);\n if (k !== m) {\n p = H[k][k - 1];\n q = H[k + 1][k - 1];\n r = (notlast ? H[k + 2][k - 1] : 0);\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\n if (x !== 0) {\n p = p / x;\n q = q / x;\n r = r / x;\n }\n }\n\n if (x === 0) {\n break;\n }\n\n s = Math.sqrt(p * p + q * q + r * r);\n if (p < 0) {\n s = -s;\n }\n\n if (s !== 0) {\n if (k !== m) {\n H[k][k - 1] = -s * x;\n } else if (l !== m) {\n H[k][k - 1] = -H[k][k - 1];\n }\n\n p = p + s;\n x = p / s;\n y = q / s;\n z = r / s;\n q = q / p;\n r = r / p;\n\n for (j = k; j < nn; j++) {\n p = H[k][j] + q * H[k + 1][j];\n if (notlast) {\n p = p + r * H[k + 2][j];\n H[k + 2][j] = H[k + 2][j] - p * z;\n }\n\n H[k][j] = H[k][j] - p * x;\n H[k + 1][j] = H[k + 1][j] - p * y;\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H[i][k] + y * H[i][k + 1];\n if (notlast) {\n p = p + z * H[i][k + 2];\n H[i][k + 2] = H[i][k + 2] - p * r;\n }\n\n H[i][k] = H[i][k] - p;\n H[i][k + 1] = H[i][k + 1] - p * q;\n }\n\n for (i = low; i <= high; i++) {\n p = x * V[i][k] + y * V[i][k + 1];\n if (notlast) {\n p = p + z * V[i][k + 2];\n V[i][k + 2] = V[i][k + 2] - p * r;\n }\n\n V[i][k] = V[i][k] - p;\n V[i][k + 1] = V[i][k + 1] - p * q;\n }\n }\n }\n }\n }\n\n if (norm === 0) {\n return;\n }\n\n for (n = nn - 1; n >= 0; n--) {\n p = d[n];\n q = e[n];\n\n if (q === 0) {\n l = n;\n H[n][n] = 1;\n for (i = n - 1; i >= 0; i--) {\n w = H[i][i] - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H[i][j] * H[j][n];\n }\n\n if (e[i] < 0) {\n z = w;\n s = r;\n } else {\n l = i;\n if (e[i] === 0) {\n H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm));\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H[i][n] = t;\n H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z);\n }\n\n t = Math.abs(H[i][n]);\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\n H[n - 1][n - 1] = q / H[n][n - 1];\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\n } else {\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\n H[n - 1][n - 1] = cdivres[0];\n H[n - 1][n] = cdivres[1];\n }\n\n H[n][n - 1] = 0;\n H[n][n] = 1;\n for (i = n - 2; i >= 0; i--) {\n ra = 0;\n sa = 0;\n for (j = l; j <= n; j++) {\n ra = ra + H[i][j] * H[j][n - 1];\n sa = sa + H[i][j] * H[j][n];\n }\n\n w = H[i][i] - p;\n\n if (e[i] < 0) {\n z = w;\n r = ra;\n s = sa;\n } else {\n l = i;\n if (e[i] === 0) {\n cdivres = cdiv(-ra, -sa, w, q);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\n vi = (d[i] - p) * 2 * q;\n if (vr === 0 && vi === 0) {\n vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z));\n }\n cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) {\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\n } else {\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\n H[i + 1][n - 1] = cdivres[0];\n H[i + 1][n] = cdivres[1];\n }\n }\n\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n - 1] = H[j][n - 1] / t;\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n for (j = i; j < nn; j++) {\n V[i][j] = H[i][j];\n }\n }\n }\n\n for (j = nn - 1; j >= low; j--) {\n for (i = low; i <= high; i++) {\n z = 0;\n for (k = low; k <= Math.min(j, high); k++) {\n z = z + V[i][k] * H[k][j];\n }\n V[i][j] = z;\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n var r, d;\n if (Math.abs(yr) > Math.abs(yi)) {\n r = yi / yr;\n d = yr + r * yi;\n return [(xr + r * xi) / d, (xi - r * xr) / d];\n } else {\n r = yr / yi;\n d = yi + r * yr;\n return [(r * xr + xi) / d, (r * xi - xr) / d];\n }\n}\n\nmodule.exports = EigenvalueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/evd.js\n// module id = 185\n// module chunks = 0","'use strict';\n\nvar Matrix = require('../matrix').Matrix;\nvar hypotenuse = require('./util').hypotenuse;\n\n//https://github.com/lutzroeder/Mapack/blob/master/Source/QrDecomposition.cs\nfunction QrDecomposition(value) {\n if (!(this instanceof QrDecomposition)) {\n return new QrDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n\n var qr = value.clone(),\n m = value.rows,\n n = value.columns,\n rdiag = new Array(n),\n i, j, k, s;\n\n for (k = 0; k < n; k++) {\n var nrm = 0;\n for (i = k; i < m; i++) {\n nrm = hypotenuse(nrm, qr[i][k]);\n }\n if (nrm !== 0) {\n if (qr[k][k] < 0) {\n nrm = -nrm;\n }\n for (i = k; i < m; i++) {\n qr[i][k] /= nrm;\n }\n qr[k][k] += 1;\n for (j = k + 1; j < n; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * qr[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n qr[i][j] += s * qr[i][k];\n }\n }\n }\n rdiag[k] = -nrm;\n }\n\n this.QR = qr;\n this.Rdiag = rdiag;\n}\n\nQrDecomposition.prototype = {\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var qr = this.QR,\n m = qr.rows;\n\n if (value.rows !== m) {\n throw new Error('Matrix row dimensions must agree');\n }\n if (!this.isFullRank()) {\n throw new Error('Matrix is rank deficient');\n }\n\n var count = value.columns;\n var X = value.clone();\n var n = qr.columns;\n var i, j, k, s;\n\n for (k = 0; k < n; k++) {\n for (j = 0; j < count; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr[i][k] * X[i][j];\n }\n s = -s / qr[k][k];\n for (i = k; i < m; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X[k][j] /= this.Rdiag[k];\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X[i][j] -= X[k][j] * qr[i][k];\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n },\n isFullRank: function () {\n var columns = this.QR.columns;\n for (var i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n },\n get upperTriangularMatrix() {\n var qr = this.QR,\n n = qr.columns,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X[i][j] = qr[i][j];\n } else if (i === j) {\n X[i][j] = this.Rdiag[i];\n } else {\n X[i][j] = 0;\n }\n }\n }\n return X;\n },\n get orthogonalMatrix() {\n var qr = this.QR,\n rows = qr.rows,\n columns = qr.columns,\n X = new Matrix(rows, columns),\n i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X[i][k] = 0;\n }\n X[k][k] = 1;\n for (j = k; j < columns; j++) {\n if (qr[k][k] !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr[i][k] * X[i][j];\n }\n\n s = -s / qr[k][k];\n\n for (i = k; i < rows; i++) {\n X[i][j] += s * qr[i][k];\n }\n }\n }\n }\n return X;\n }\n};\n\nmodule.exports = QrDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/dc/qr.js\n// module id = 186\n// module chunks = 0","'use strict';\n\nvar Matrix = require('./matrix').Matrix;\n\nvar SingularValueDecomposition = require('./dc/svd');\nvar EigenvalueDecomposition = require('./dc/evd');\nvar LuDecomposition = require('./dc/lu');\nvar QrDecomposition = require('./dc/qr');\nvar CholeskyDecomposition = require('./dc/cholesky');\n\nfunction inverse(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n return solve(matrix, Matrix.eye(matrix.rows));\n}\n\n/**\n * Returns the inverse\n * @memberOf Matrix\n * @static\n * @param {Matrix} matrix\n * @return {Matrix} matrix\n * @alias inv\n */\nMatrix.inverse = Matrix.inv = inverse;\n\n/**\n * Returns the inverse\n * @memberOf Matrix\n * @static\n * @param {Matrix} matrix\n * @return {Matrix} matrix\n * @alias inv\n */\nMatrix.prototype.inverse = Matrix.prototype.inv = function () {\n return inverse(this);\n};\n\nfunction solve(leftHandSide, rightHandSide) {\n leftHandSide = Matrix.checkMatrix(leftHandSide);\n rightHandSide = Matrix.checkMatrix(rightHandSide);\n return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide);\n}\n\nMatrix.solve = solve;\nMatrix.prototype.solve = function (other) {\n return solve(this, other);\n};\n\nmodule.exports = {\n SingularValueDecomposition: SingularValueDecomposition,\n SVD: SingularValueDecomposition,\n EigenvalueDecomposition: EigenvalueDecomposition,\n EVD: EigenvalueDecomposition,\n LuDecomposition: LuDecomposition,\n LU: LuDecomposition,\n QrDecomposition: QrDecomposition,\n QR: QrDecomposition,\n CholeskyDecomposition: CholeskyDecomposition,\n CHO: CholeskyDecomposition,\n inverse: inverse,\n solve: solve\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/decompositions.js\n// module id = 187\n// module chunks = 0","'use strict';\n\nif (!Symbol.species) {\n Symbol.species = Symbol.for('@@species');\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/symbol-species.js\n// module id = 188\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n super(matrix, matrix.rows, 1);\n this.column = column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.column, value);\n return this;\n }\n\n get(rowIndex) {\n return this.matrix.get(rowIndex, this.column);\n }\n}\n\nmodule.exports = MatrixColumnView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/column.js\n// module id = 189\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass 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\nmodule.exports = MatrixFlipColumnView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/flipColumn.js\n// module id = 190\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass 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\nmodule.exports = MatrixFlipRowView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/flipRow.js\n// module id = 191\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass MatrixRowView extends BaseView {\n constructor(matrix, row) {\n super(matrix, 1, matrix.columns);\n this.row = row;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.row, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.row, columnIndex);\n }\n}\n\nmodule.exports = MatrixRowView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/row.js\n// module id = 192\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\nvar util = require('../util');\n\nclass MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n var indices = util.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(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]);\n }\n}\n\nmodule.exports = MatrixSelectionView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/selection.js\n// module id = 193\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\nvar util = require('../util');\n\nclass MatrixSubView extends BaseView {\n constructor(matrix, startRow, endRow, startColumn, endColumn) {\n util.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(this.startRow + rowIndex, this.startColumn + columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex);\n }\n}\n\nmodule.exports = MatrixSubView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/sub.js\n// module id = 194\n// module chunks = 0","'use strict';\n\nvar BaseView = require('./base');\n\nclass 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\nmodule.exports = MatrixTransposeView;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-matrix/src/views/transpose.js\n// module id = 195\n// module chunks = 0","'use strict';\n\nconst squaredDistance = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n distanceFunction: squaredDistance,\n similarityFunction: false,\n returnVector: false\n};\n\n/**\n * Find the nearest vector in a list to a sample vector\n * @param {Array>} listVectors - List of vectors with same dimensions\n * @param {Array} vector - Reference vector to \"classify\"\n * @param {object} [options] - Options object\n * @param {function} [options.distanceFunction = squaredDistance] - Function that receives two vectors and return their distance value as number\n * @param {function} [options.similarityFunction = undefined] - Function that receives two vectors and return their similarity value as number\n * @param {boolean} [options.returnVector = false] - Return the nearest vector instead of its index\n * @return {number|Array} - The index or the content of the nearest vector\n */\nfunction nearestVector(listVectors, vector, options) {\n options = options || defaultOptions;\n const distanceFunction = options.distanceFunction || defaultOptions.distanceFunction;\n const similarityFunction = options.similarityFunction || defaultOptions.similarityFunction;\n const returnVector = options.returnVector || defaultOptions.returnVector;\n\n var vectorIndex = -1;\n if (typeof similarityFunction === 'function') {\n\n // maximum similarity\n var maxSim = Number.MIN_VALUE;\n for (var j = 0; j < listVectors.length; j++) {\n var sim = similarityFunction(vector, listVectors[j]);\n if (sim > maxSim) {\n maxSim = sim;\n vectorIndex = j;\n }\n }\n } else if (typeof distanceFunction === 'function') {\n\n // minimum distance\n var minDist = Number.MAX_VALUE;\n for (var i = 0; i < listVectors.length; i++) {\n var dist = distanceFunction(vector, listVectors[i]);\n if (dist < minDist) {\n minDist = dist;\n vectorIndex = i;\n }\n }\n } else {\n throw new Error('A similarity or distance function it\\'s required');\n }\n\n if (returnVector) {\n return listVectors[vectorIndex];\n } else {\n return vectorIndex;\n }\n}\n\nmodule.exports = nearestVector;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-nearest-vector/src/index.js\n// module id = 196\n// module chunks = 0","'use strict';\n\n// Accuracy\nexports.acc = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1);\n }\n return result;\n};\n\n// Error rate\nexports.err = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.fp[i] / (l - 1));\n }\n return result;\n};\n\n// False positive rate\nexports.fpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fp[i] / pred.nNeg;\n }\n return result;\n};\n\n// True positive rate\nexports.tpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tp[i] / pred.nPos;\n }\n return result;\n};\n\n// False negative rate\nexports.fnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fn[i] / pred.nPos;\n }\n return result;\n};\n\n// True negative rate\nexports.tnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tn[i] / pred.nNeg;\n }\n return result;\n};\n\n// Positive predictive value\nexports.ppv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 0;\n }\n return result;\n};\n\n// Negative predictive value\nexports.npv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 0;\n }\n return result;\n};\n\n// Prediction conditioned fallout\nexports.pcfall = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1;\n }\n return result;\n};\n\n// Prediction conditioned miss\nexports.pcmiss = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1;\n }\n return result;\n};\n\n// Lift value\nexports.lift = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.nPosPred[i] !== 0) ? ((pred.tp[i] / pred.nPos) / (pred.nPosPred[i] / pred.nSamples)) : 0;\n }\n return result;\n};\n\n// Rate of positive predictions\nexports.rpp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nPosPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Rate of negative predictions\nexports.rnp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nNegPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Threshold\nexports.threshold = pred => {\n const clone = pred.cutoffs.slice();\n clone[0] = clone[1]; // Remove the infinite value\n return clone;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-performance/src/measures.js\n// module id = 197\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\nvar Utils = require('./utils');\n\nmodule.exports = OPLS;\n\nfunction OPLS(dataset, predictions, numberOSC) {\n var X = new Matrix(dataset);\n var y = new Matrix(predictions);\n\n X = Utils.featureNormalize(X).result;\n y = Utils.featureNormalize(y).result;\n\n var rows = X.rows;\n var columns = X.columns;\n\n var sumOfSquaresX = X.clone().mul(X).sum();\n var w = X.transpose().mmul(y);\n w.div(Utils.norm(w));\n\n var orthoW = new Array(numberOSC);\n var orthoT = new Array(numberOSC);\n var orthoP = new Array(numberOSC);\n for (var i = 0; i < numberOSC; i++) {\n var t = X.mmul(w);\n\n var numerator = X.transpose().mmul(t);\n var denominator = t.transpose().mmul(t)[0][0];\n var p = numerator.div(denominator);\n\n numerator = w.transpose().mmul(p)[0][0];\n denominator = w.transpose().mmul(w)[0][0];\n var wOsc = p.sub(w.clone().mul(numerator / denominator));\n wOsc.div(Utils.norm(wOsc));\n\n var tOsc = X.mmul(wOsc);\n\n numerator = X.transpose().mmul(tOsc);\n denominator = tOsc.transpose().mmul(tOsc)[0][0];\n var pOsc = numerator.div(denominator);\n\n X.sub(tOsc.mmul(pOsc.transpose()));\n orthoW[i] = wOsc.getColumn(0);\n orthoT[i] = tOsc.getColumn(0);\n orthoP[i] = pOsc.getColumn(0);\n }\n\n this.Xosc = X;\n\n var sumOfSquaresXosx = this.Xosc.clone().mul(this.Xosc).sum();\n this.R2X = 1 - sumOfSquaresXosx/sumOfSquaresX;\n\n this.W = orthoW;\n this.T = orthoT;\n this.P = orthoP;\n this.numberOSC = numberOSC;\n}\n\nOPLS.prototype.correctDataset = function (dataset) {\n var X = new Matrix(dataset);\n\n var sumOfSquaresX = X.clone().mul(X).sum();\n for (var i = 0; i < this.numberOSC; i++) {\n var currentW = this.W.getColumnVector(i);\n var currentP = this.P.getColumnVector(i);\n\n var t = X.mmul(currentW);\n X.sub(t.mmul(currentP));\n }\n var sumOfSquaresXosx = X.clone().mul(X).sum();\n\n var R2X = 1 - sumOfSquaresXosx / sumOfSquaresX;\n\n return {\n datasetOsc: X,\n R2Dataset: R2X\n };\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pls/src/opls.js\n// module id = 198\n// module chunks = 0","'use strict';\n\nvar Matrix = require('ml-matrix');\nvar Utils = require('./utils');\n\nclass PLS {\n constructor(X, Y) {\n if (X === true) {\n const model = Y;\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 } else {\n if (X.length !== Y.length)\n throw new RangeError('The number of X rows must be equal to the number of Y rows');\n\n const resultX = Utils.featureNormalize(X);\n this.X = resultX.result;\n this.meanX = resultX.means;\n this.stdDevX = resultX.std;\n\n const resultY = Utils.featureNormalize(Y);\n this.Y = resultY.result;\n this.meanY = resultY.means;\n this.stdDevY = resultY.std;\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 {Object} options - recieves the latentVectors and the tolerance of each step of the PLS\n */\n train(options) {\n if(options === undefined) options = {};\n\n var latentVectors = options.latentVectors;\n if (latentVectors === undefined) {\n latentVectors = Math.min(this.X.length - 1, this.X[0].length);\n }\n\n var tolerance = options.tolerance;\n if (tolerance === undefined) {\n tolerance = 1e-5;\n }\n \n var X = this.X;\n var Y = this.Y;\n\n var rx = X.rows;\n var cx = X.columns;\n var ry = Y.rows;\n var cy = Y.columns;\n\n var ssqXcal = X.clone().mul(X).sum(); // for the r²\n var sumOfSquaresY = Y.clone().mul(Y).sum();\n\n var n = latentVectors; //Math.max(cx, cy); // components of the pls\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(Y) > tolerance && k < n) {\n var transposeX = X.transpose();\n var transposeY = Y.transpose();\n\n var tIndex = maxSumColIndex(X.clone().mulM(X));\n var uIndex = maxSumColIndex(Y.clone().mulM(Y));\n\n var t1 = X.getColumnVector(tIndex);\n var u = Y.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 = X.mmul(w);\n var q = transposeY.mmul(t1);\n q.div(Utils.norm(q));\n u = Y.mmul(q);\n }\n\n t = t1;\n var num = transposeX.mmul(t);\n var den = (t.transpose().mmul(t))[0][0];\n var p = num.div(den);\n var pnorm = Utils.norm(p);\n p.div(pnorm);\n t.mul(pnorm);\n w.mul(pnorm);\n\n num = u.transpose().mmul(t);\n den = (t.transpose().mmul(t))[0][0];\n var b = (num.div(den))[0][0];\n X.sub(t.mmul(p.transpose()));\n Y.sub(t.clone().mul(b).mmul(q.transpose()));\n\n T.setColumn(k, t);\n P.setColumn(k, p);\n U.setColumn(k, u);\n Q.setColumn(k, q);\n W.setColumn(k, w);\n\n B[k][k] = b;\n k++;\n }\n\n k--;\n T = T.subMatrix(0, T.rows - 1, 0, k);\n P = P.subMatrix(0, P.rows - 1, 0, k);\n U = U.subMatrix(0, U.rows - 1, 0, k);\n Q = Q.subMatrix(0, Q.rows - 1, 0, k);\n W = W.subMatrix(0, W.rows - 1, 0, k);\n B = B.subMatrix(0, k, 0, k);\n\n // TODO: review of R2Y\n //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0];\n\n this.ssqYcal = sumOfSquaresY;\n this.E = X;\n this.F = Y;\n this.T = T;\n this.P = P;\n this.U = U;\n this.Q = Q;\n this.W = W;\n this.B = B;\n this.PBQ = P.mmul(B).mmul(Q.transpose());\n this.R2X = t.transpose().mmul(t).mmul(p.transpose().mmul(p)).div(ssqXcal)[0][0];\n }\n\n /**\n * Predicts the behavior of the given dataset.\n * @param dataset - data to be predicted.\n * @returns {Matrix} - predictions of each element of the dataset.\n */\n predict(dataset) {\n var X = Matrix.checkMatrix(dataset);\n X = X.subRowVector(this.meanX).divRowVector(this.stdDevX);\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 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 };\n }\n\n /**\n * Load a PLS model from a JSON Object\n * @param 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 return new PLS(true, model);\n }\n}\n\nmodule.exports = PLS;\n\n/**\n * Retrieves the sum at the column of the given matrix.\n * @param matrix\n * @param column\n * @returns {number}\n */\nfunction getColSum(matrix, column) {\n var sum = 0;\n for (var i = 0; i < matrix.rows; i++) {\n sum += matrix[i][column];\n }\n return sum;\n}\n\n/**\n * Function that returns the index where the sum of each\n * column vector is maximum.\n * @param {Matrix} data\n * @returns {number} index of the maximum\n */\nfunction maxSumColIndex(data) {\n var maxIndex = 0;\n var maxSum = -Infinity;\n for(var i = 0; i < data.columns; ++i) {\n var currentSum = getColSum(data, i);\n if(currentSum > maxSum) {\n maxSum = currentSum;\n maxIndex = i;\n }\n }\n return maxIndex;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-pls/src/pls.js\n// module id = 199\n// module chunks = 0","export default function checkArraySize(x, y) {\n if (!Array.isArray(x) || !Array.isArray(y)) {\n throw new TypeError('x and y must be arrays');\n }\n if (x.length !== y.length) {\n throw new RangeError('x and y arrays must have the same length');\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-base/src/checkArrayLength.js\n// module id = 200\n// module chunks = 0","export default function maybeToPrecision(value, digits) {\n if (value < 0) {\n value = 0 - value;\n if (typeof digits === 'number') {\n return '- ' + value.toPrecision(digits);\n } else {\n return '- ' + value.toString();\n }\n } else {\n if (typeof digits === 'number') {\n return value.toPrecision(digits);\n } else {\n return value.toString();\n }\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-base/src/maybeToPrecision.js\n// module id = 201\n// module chunks = 0","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class ExponentialRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) {\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(input) {\n return this.B * Math.exp(input * this.A);\n }\n\n toJSON() {\n return {\n name: 'exponentialRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + ' * e^(' + maybeToPrecision(this.A, precision) + ' * x)';\n }\n\n toLaTeX(precision) {\n if (this.A >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.B, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.B, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}';\n }\n\n }\n\n static load(json) {\n if (json.name !== 'exponentialRegression') {\n throw new TypeError('not a exponential regression model');\n }\n return new ExponentialRegression(true, json);\n }\n}\n\nfunction regress(er, x, y) {\n const n = x.length;\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(x, yl);\n er.A = linear.slope;\n er.B = Math.exp(linear.intercept);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-exponential/src/index.js\n// module id = 202\n// module chunks = 0","import Matrix from '../matrix';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\nfunction CholeskyDecomposition(value) {\n if (!(this instanceof CholeskyDecomposition)) {\n return new CholeskyDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n if (!value.isSymmetric()) {\n throw new Error('Matrix is not symmetric');\n }\n\n var a = value,\n dimension = a.rows,\n l = new Matrix(dimension, dimension),\n positiveDefinite = true,\n i, j, k;\n\n for (j = 0; j < dimension; j++) {\n var Lrowj = l[j];\n var d = 0;\n for (k = 0; k < j; k++) {\n var Lrowk = l[k];\n var s = 0;\n for (i = 0; i < k; i++) {\n s += Lrowk[i] * Lrowj[i];\n }\n Lrowj[k] = s = (a[j][k] - s) / l[k][k];\n d = d + s * s;\n }\n\n d = a[j][j] - d;\n\n positiveDefinite &= (d > 0);\n l[j][j] = Math.sqrt(Math.max(d, 0));\n for (k = j + 1; k < dimension; k++) {\n l[j][k] = 0;\n }\n }\n\n if (!positiveDefinite) {\n throw new Error('Matrix is not positive definite');\n }\n\n this.L = l;\n}\n\nCholeskyDecomposition.prototype = {\n get lowerTriangularMatrix() {\n return this.L;\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var l = this.L,\n dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n\n var count = value.columns,\n B = value.clone(),\n i, j, k;\n\n for (k = 0; k < dimension; k++) {\n for (j = 0; j < count; j++) {\n for (i = 0; i < k; i++) {\n B[k][j] -= B[i][j] * l[k][i];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n for (k = dimension - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n for (i = k + 1; i < dimension; i++) {\n B[k][j] -= B[i][j] * l[i][k];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n return B;\n }\n};\n\nexport default CholeskyDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/dc/cholesky.js\n// module id = 203\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse, getFilled2DArray} from './util';\n\nconst defaultOptions = {\n assumeSymmetric: false\n};\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\nfunction EigenvalueDecomposition(matrix, options) {\n options = Object.assign({}, defaultOptions, options);\n if (!(this instanceof EigenvalueDecomposition)) {\n return new EigenvalueDecomposition(matrix, options);\n }\n matrix = Matrix.checkMatrix(matrix);\n if (!matrix.isSquare()) {\n throw new Error('Matrix is not a square matrix');\n }\n\n var n = matrix.columns,\n V = getFilled2DArray(n, n, 0),\n d = new Array(n),\n e = new Array(n),\n value = matrix,\n i, j;\n\n var isSymmetric = false;\n if (options.assumeSymmetric) {\n isSymmetric = true;\n } else {\n isSymmetric = matrix.isSymmetric();\n }\n\n if (isSymmetric) {\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = value.get(i, j);\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n var H = getFilled2DArray(n, n, 0),\n ort = new Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H[i][j] = value.get(i, j);\n }\n }\n orthes(n, H, ort, V);\n hqr2(n, e, d, V, H);\n }\n\n this.n = n;\n this.e = e;\n this.d = d;\n this.V = V;\n}\n\nEigenvalueDecomposition.prototype = {\n get realEigenvalues() {\n return this.d;\n },\n get imaginaryEigenvalues() {\n return this.e;\n },\n get eigenvectorMatrix() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n var n = this.n,\n e = this.e,\n d = this.d,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X[i][j] = 0;\n }\n X[i][i] = d[i];\n if (e[i] > 0) {\n X[i][i + 1] = e[i];\n } else if (e[i] < 0) {\n X[i][i - 1] = e[i];\n }\n }\n return X;\n }\n};\n\nfunction tred2(n, e, d, V) {\n\n var f, g, h, i, j, k,\n hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n }\n\n for (i = n - 1; i > 0; i--) {\n scale = 0;\n h = 0;\n for (k = 0; k < i; k++) {\n scale = scale + Math.abs(d[k]);\n }\n\n if (scale === 0) {\n e[i] = d[i - 1];\n for (j = 0; j < i; j++) {\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n V[j][i] = 0;\n }\n } else {\n for (k = 0; k < i; k++) {\n d[k] /= scale;\n h += d[k] * d[k];\n }\n\n f = d[i - 1];\n g = Math.sqrt(h);\n if (f > 0) {\n g = -g;\n }\n\n e[i] = scale * g;\n h = h - f * g;\n d[i - 1] = f - g;\n for (j = 0; j < i; j++) {\n e[j] = 0;\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n V[j][i] = f;\n g = e[j] + V[j][j] * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V[k][j] * d[k];\n e[k] += V[k][j] * f;\n }\n e[j] = g;\n }\n\n f = 0;\n for (j = 0; j < i; j++) {\n e[j] /= h;\n f += e[j] * d[j];\n }\n\n hh = f / (h + h);\n for (j = 0; j < i; j++) {\n e[j] -= hh * d[j];\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n g = e[j];\n for (k = j; k <= i - 1; k++) {\n V[k][j] -= (f * e[k] + g * d[k]);\n }\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V[n - 1][i] = V[i][i];\n V[i][i] = 1;\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V[k][i + 1] / h;\n }\n\n for (j = 0; j <= i; j++) {\n g = 0;\n for (k = 0; k <= i; k++) {\n g += V[k][i + 1] * V[k][j];\n }\n for (k = 0; k <= i; k++) {\n V[k][j] -= g * d[k];\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V[k][i + 1] = 0;\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n V[n - 1][j] = 0;\n }\n\n V[n - 1][n - 1] = 1;\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n\n var g, h, i, j, k, l, m, p, r,\n dl1, c, c2, c3, el1, s, s2,\n iter;\n\n for (i = 1; i < n; i++) {\n e[i - 1] = e[i];\n }\n\n e[n - 1] = 0;\n\n var f = 0,\n tst1 = 0,\n eps = Math.pow(2, -52);\n\n for (l = 0; l < n; l++) {\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\n m = l;\n while (m < n) {\n if (Math.abs(e[m]) <= eps * tst1) {\n break;\n }\n m++;\n }\n\n if (m > l) {\n iter = 0;\n do {\n iter = iter + 1;\n\n g = d[l];\n p = (d[l + 1] - g) / (2 * e[l]);\n r = hypotenuse(p, 1);\n if (p < 0) {\n r = -r;\n }\n\n d[l] = e[l] / (p + r);\n d[l + 1] = e[l] * (p + r);\n dl1 = d[l + 1];\n h = g - d[l];\n for (i = l + 2; i < n; i++) {\n d[i] -= h;\n }\n\n f = f + h;\n\n p = d[m];\n c = 1;\n c2 = c;\n c3 = c;\n el1 = e[l + 1];\n s = 0;\n s2 = 0;\n for (i = m - 1; i >= l; i--) {\n c3 = c2;\n c2 = c;\n s2 = s;\n g = c * e[i];\n h = c * p;\n r = hypotenuse(p, e[i]);\n e[i + 1] = s * r;\n s = e[i] / r;\n c = p / r;\n p = c * d[i] - s * g;\n d[i + 1] = h + s * (c * g + s * d[i]);\n\n for (k = 0; k < n; k++) {\n h = V[k][i + 1];\n V[k][i + 1] = s * V[k][i] + c * h;\n V[k][i] = c * V[k][i] - s * h;\n }\n }\n\n p = -s * s2 * c3 * el1 * e[l] / dl1;\n e[l] = s * p;\n d[l] = c * p;\n\n }\n while (Math.abs(e[l]) > eps * tst1);\n }\n d[l] = d[l] + f;\n e[l] = 0;\n }\n\n for (i = 0; i < n - 1; i++) {\n k = i;\n p = d[i];\n for (j = i + 1; j < n; j++) {\n if (d[j] < p) {\n k = j;\n p = d[j];\n }\n }\n\n if (k !== i) {\n d[k] = d[i];\n d[i] = p;\n for (j = 0; j < n; j++) {\n p = V[j][i];\n V[j][i] = V[j][k];\n V[j][k] = p;\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n\n var low = 0,\n high = n - 1,\n f, g, h, i, j, m,\n scale;\n\n for (m = low + 1; m <= high - 1; m++) {\n scale = 0;\n for (i = m; i <= high; i++) {\n scale = scale + Math.abs(H[i][m - 1]);\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H[i][m - 1] / scale;\n h += ort[i] * ort[i];\n }\n\n g = Math.sqrt(h);\n if (ort[m] > 0) {\n g = -g;\n }\n\n h = h - ort[m] * g;\n ort[m] = ort[m] - g;\n\n for (j = m; j < n; j++) {\n f = 0;\n for (i = high; i >= m; i--) {\n f += ort[i] * H[i][j];\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H[i][j] -= f * ort[i];\n }\n }\n\n for (i = 0; i <= high; i++) {\n f = 0;\n for (j = high; j >= m; j--) {\n f += ort[j] * H[i][j];\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H[i][j] -= f * ort[j];\n }\n }\n\n ort[m] = scale * ort[m];\n H[m][m - 1] = scale * g;\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = (i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H[m][m - 1] !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H[i][m - 1];\n }\n\n for (j = m; j <= high; j++) {\n g = 0;\n for (i = m; i <= high; i++) {\n g += ort[i] * V[i][j];\n }\n\n g = (g / ort[m]) / H[m][m - 1];\n for (i = m; i <= high; i++) {\n V[i][j] += g * ort[i];\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n var n = nn - 1,\n low = 0,\n high = nn - 1,\n eps = Math.pow(2, -52),\n exshift = 0,\n norm = 0,\n p = 0,\n q = 0,\n r = 0,\n s = 0,\n z = 0,\n iter = 0,\n i, j, k, l, m, t, w, x, y,\n ra, sa, vr, vi,\n notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H[i][i];\n e[i] = 0;\n }\n\n for (j = Math.max(i - 1, 0); j < nn; j++) {\n norm = norm + Math.abs(H[i][j]);\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H[l][l - 1]) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H[n][n] = H[n][n] + exshift;\n d[n] = H[n][n];\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H[n][n - 1] * H[n - 1][n];\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H[n][n] = H[n][n] + exshift;\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\n x = H[n][n];\n\n if (q >= 0) {\n z = (p >= 0) ? (p + z) : (p - z);\n d[n - 1] = x + z;\n d[n] = d[n - 1];\n if (z !== 0) {\n d[n] = x - w / z;\n }\n e[n - 1] = 0;\n e[n] = 0;\n x = H[n][n - 1];\n s = Math.abs(x) + Math.abs(z);\n p = x / s;\n q = z / s;\n r = Math.sqrt(p * p + q * q);\n p = p / r;\n q = q / r;\n\n for (j = n - 1; j < nn; j++) {\n z = H[n - 1][j];\n H[n - 1][j] = q * z + p * H[n][j];\n H[n][j] = q * H[n][j] - p * z;\n }\n\n for (i = 0; i <= n; i++) {\n z = H[i][n - 1];\n H[i][n - 1] = q * z + p * H[i][n];\n H[i][n] = q * H[i][n] - p * z;\n }\n\n for (i = low; i <= high; i++) {\n z = V[i][n - 1];\n V[i][n - 1] = q * z + p * V[i][n];\n V[i][n] = q * V[i][n] - p * z;\n }\n } else {\n d[n - 1] = x + p;\n d[n] = x + p;\n e[n - 1] = z;\n e[n] = -z;\n }\n\n n = n - 2;\n iter = 0;\n } else {\n x = H[n][n];\n y = 0;\n w = 0;\n if (l < n) {\n y = H[n - 1][n - 1];\n w = H[n][n - 1] * H[n - 1][n];\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H[i][i] -= x;\n }\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\n x = y = 0.75 * s;\n w = -0.4375 * s * s;\n }\n\n if (iter === 30) {\n s = (y - x) / 2;\n s = s * s + w;\n if (s > 0) {\n s = Math.sqrt(s);\n if (y < x) {\n s = -s;\n }\n s = x - w / ((y - x) / 2 + s);\n for (i = low; i <= n; i++) {\n H[i][i] -= s;\n }\n exshift += s;\n x = y = w = 0.964;\n }\n }\n\n iter = iter + 1;\n\n m = n - 2;\n while (m >= l) {\n z = H[m][m];\n r = x - z;\n s = y - z;\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\n q = H[m + 1][m + 1] - z - r - s;\n r = H[m + 2][m + 1];\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\n p = p / s;\n q = q / s;\n r = r / s;\n if (m === l) {\n break;\n }\n if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H[i][i - 2] = 0;\n if (i > m + 2) {\n H[i][i - 3] = 0;\n }\n }\n\n for (k = m; k <= n - 1; k++) {\n notlast = (k !== n - 1);\n if (k !== m) {\n p = H[k][k - 1];\n q = H[k + 1][k - 1];\n r = (notlast ? H[k + 2][k - 1] : 0);\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\n if (x !== 0) {\n p = p / x;\n q = q / x;\n r = r / x;\n }\n }\n\n if (x === 0) {\n break;\n }\n\n s = Math.sqrt(p * p + q * q + r * r);\n if (p < 0) {\n s = -s;\n }\n\n if (s !== 0) {\n if (k !== m) {\n H[k][k - 1] = -s * x;\n } else if (l !== m) {\n H[k][k - 1] = -H[k][k - 1];\n }\n\n p = p + s;\n x = p / s;\n y = q / s;\n z = r / s;\n q = q / p;\n r = r / p;\n\n for (j = k; j < nn; j++) {\n p = H[k][j] + q * H[k + 1][j];\n if (notlast) {\n p = p + r * H[k + 2][j];\n H[k + 2][j] = H[k + 2][j] - p * z;\n }\n\n H[k][j] = H[k][j] - p * x;\n H[k + 1][j] = H[k + 1][j] - p * y;\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H[i][k] + y * H[i][k + 1];\n if (notlast) {\n p = p + z * H[i][k + 2];\n H[i][k + 2] = H[i][k + 2] - p * r;\n }\n\n H[i][k] = H[i][k] - p;\n H[i][k + 1] = H[i][k + 1] - p * q;\n }\n\n for (i = low; i <= high; i++) {\n p = x * V[i][k] + y * V[i][k + 1];\n if (notlast) {\n p = p + z * V[i][k + 2];\n V[i][k + 2] = V[i][k + 2] - p * r;\n }\n\n V[i][k] = V[i][k] - p;\n V[i][k + 1] = V[i][k + 1] - p * q;\n }\n }\n }\n }\n }\n\n if (norm === 0) {\n return;\n }\n\n for (n = nn - 1; n >= 0; n--) {\n p = d[n];\n q = e[n];\n\n if (q === 0) {\n l = n;\n H[n][n] = 1;\n for (i = n - 1; i >= 0; i--) {\n w = H[i][i] - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H[i][j] * H[j][n];\n }\n\n if (e[i] < 0) {\n z = w;\n s = r;\n } else {\n l = i;\n if (e[i] === 0) {\n H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm));\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H[i][n] = t;\n H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z);\n }\n\n t = Math.abs(H[i][n]);\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\n H[n - 1][n - 1] = q / H[n][n - 1];\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\n } else {\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\n H[n - 1][n - 1] = cdivres[0];\n H[n - 1][n] = cdivres[1];\n }\n\n H[n][n - 1] = 0;\n H[n][n] = 1;\n for (i = n - 2; i >= 0; i--) {\n ra = 0;\n sa = 0;\n for (j = l; j <= n; j++) {\n ra = ra + H[i][j] * H[j][n - 1];\n sa = sa + H[i][j] * H[j][n];\n }\n\n w = H[i][i] - p;\n\n if (e[i] < 0) {\n z = w;\n r = ra;\n s = sa;\n } else {\n l = i;\n if (e[i] === 0) {\n cdivres = cdiv(-ra, -sa, w, q);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\n vi = (d[i] - p) * 2 * q;\n if (vr === 0 && vi === 0) {\n vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z));\n }\n cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) {\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\n } else {\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\n H[i + 1][n - 1] = cdivres[0];\n H[i + 1][n] = cdivres[1];\n }\n }\n\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n - 1] = H[j][n - 1] / t;\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n for (j = i; j < nn; j++) {\n V[i][j] = H[i][j];\n }\n }\n }\n\n for (j = nn - 1; j >= low; j--) {\n for (i = low; i <= high; i++) {\n z = 0;\n for (k = low; k <= Math.min(j, high); k++) {\n z = z + V[i][k] * H[k][j];\n }\n V[i][j] = z;\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n var r, d;\n if (Math.abs(yr) > Math.abs(yi)) {\n r = yi / yr;\n d = yr + r * yi;\n return [(xr + r * xi) / d, (xi - r * xr) / d];\n } else {\n r = yr / yi;\n d = yi + r * yr;\n return [(r * xr + xi) / d, (r * xi - xr) / d];\n }\n}\n\nexport default EigenvalueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/dc/evd.js\n// module id = 204\n// module chunks = 0","import Matrix from './matrix';\n\nimport LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\n\nexport function inverse(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n return solve(matrix, Matrix.eye(matrix.rows));\n}\n\nexport function solve(leftHandSide, rightHandSide) {\n leftHandSide = Matrix.checkMatrix(leftHandSide);\n rightHandSide = Matrix.checkMatrix(rightHandSide);\n return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/decompositions.js\n// module id = 205\n// module chunks = 0","export {default as default, default as Matrix} from './matrix';\nexport {default as abstractMatrix} from './abstractMatrix';\n\nexport {solve, inverse} from './decompositions';\nexport {default as SingularValueDecomposition, default as SVD} from './dc/svd.js';\nexport {default as EigenvalueDecomposition, default as EVD} from './dc/evd.js';\nexport {default as CholeskyDecomposition, default as CHO} from './dc/cholesky.js';\nexport {default as LuDecomposition, default as LU} from './dc/lu.js';\nexport {default as QrDecomposition, default as QR} from './dc/qr.js';\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/index.js\n// module id = 206\n// module chunks = 0","if (!Symbol.species) {\n Symbol.species = Symbol.for('@@species');\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/symbol-species.js\n// module id = 207\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n super(matrix, matrix.rows, 1);\n this.column = column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.column, value);\n return this;\n }\n\n get(rowIndex) {\n return this.matrix.get(rowIndex, this.column);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/views/column.js\n// module id = 208\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixFlipColumnView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/views/flipColumn.js\n// module id = 209\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixFlipRowView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/views/flipRow.js\n// module id = 210\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n super(matrix, 1, matrix.columns);\n this.row = row;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.row, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.row, columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/views/row.js\n// module id = 211\n// module chunks = 0","import BaseView from './base';\nimport {checkIndices} from '../util';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n var indices = checkIndices(matrix, rowIndices, columnIndices);\n super(matrix, indices.row.length, indices.column.length);\n this.rowIndices = indices.row;\n this.columnIndices = indices.column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/views/selection.js\n// module id = 212\n// module chunks = 0","import BaseView from './base';\nimport {checkRange} from '../util';\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(this.startRow + rowIndex, this.startColumn + columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/views/sub.js\n// module id = 213\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixTransposeView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.columns, matrix.rows);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(columnIndex, rowIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(columnIndex, rowIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-polynomial/~/ml-matrix/src/views/transpose.js\n// module id = 214\n// module chunks = 0","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport SimpleLinearRegression from 'ml-regression-simple-linear';\n\nexport default class PowerRegression extends BaseRegression {\n constructor(x, y) {\n super();\n if (x === true) { // reloading model\n this.A = y.A;\n this.B = y.B;\n } else {\n checkArrayLength(x, y);\n regress(this, x, y);\n }\n }\n\n _predict(newInputs) {\n return this.A * Math.pow(newInputs, this.B);\n }\n\n toJSON() {\n return {\n name: 'powerRegression',\n A: this.A,\n B: this.B\n };\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + maybeToPrecision(this.B, precision);\n }\n\n toLaTeX(precision) {\n if (this.B >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + maybeToPrecision(-this.B, precision) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'powerRegression') {\n throw new TypeError('not a power regression model');\n }\n return new PowerRegression(true, json);\n }\n}\n\nfunction regress(pr, x, y) {\n const n = x.length;\n const xl = new Array(n);\n const yl = new Array(n);\n for (let i = 0; i < n; i++) {\n xl[i] = Math.log(x[i]);\n yl[i] = Math.log(y[i]);\n }\n\n const linear = new SimpleLinearRegression(xl, yl);\n pr.A = Math.exp(linear.intercept);\n pr.B = linear.slope;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-power/src/index.js\n// module id = 215\n// module chunks = 0","import Matrix from '../matrix';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\nfunction CholeskyDecomposition(value) {\n if (!(this instanceof CholeskyDecomposition)) {\n return new CholeskyDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n if (!value.isSymmetric()) {\n throw new Error('Matrix is not symmetric');\n }\n\n var a = value,\n dimension = a.rows,\n l = new Matrix(dimension, dimension),\n positiveDefinite = true,\n i, j, k;\n\n for (j = 0; j < dimension; j++) {\n var Lrowj = l[j];\n var d = 0;\n for (k = 0; k < j; k++) {\n var Lrowk = l[k];\n var s = 0;\n for (i = 0; i < k; i++) {\n s += Lrowk[i] * Lrowj[i];\n }\n Lrowj[k] = s = (a[j][k] - s) / l[k][k];\n d = d + s * s;\n }\n\n d = a[j][j] - d;\n\n positiveDefinite &= (d > 0);\n l[j][j] = Math.sqrt(Math.max(d, 0));\n for (k = j + 1; k < dimension; k++) {\n l[j][k] = 0;\n }\n }\n\n if (!positiveDefinite) {\n throw new Error('Matrix is not positive definite');\n }\n\n this.L = l;\n}\n\nCholeskyDecomposition.prototype = {\n get lowerTriangularMatrix() {\n return this.L;\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var l = this.L,\n dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n\n var count = value.columns,\n B = value.clone(),\n i, j, k;\n\n for (k = 0; k < dimension; k++) {\n for (j = 0; j < count; j++) {\n for (i = 0; i < k; i++) {\n B[k][j] -= B[i][j] * l[k][i];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n for (k = dimension - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n for (i = k + 1; i < dimension; i++) {\n B[k][j] -= B[i][j] * l[i][k];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n return B;\n }\n};\n\nexport default CholeskyDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/cholesky.js\n// module id = 216\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse, getFilled2DArray} from './util';\n\nconst defaultOptions = {\n assumeSymmetric: false\n};\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\nfunction EigenvalueDecomposition(matrix, options) {\n options = Object.assign({}, defaultOptions, options);\n if (!(this instanceof EigenvalueDecomposition)) {\n return new EigenvalueDecomposition(matrix, options);\n }\n matrix = Matrix.checkMatrix(matrix);\n if (!matrix.isSquare()) {\n throw new Error('Matrix is not a square matrix');\n }\n\n var n = matrix.columns,\n V = getFilled2DArray(n, n, 0),\n d = new Array(n),\n e = new Array(n),\n value = matrix,\n i, j;\n\n var isSymmetric = false;\n if (options.assumeSymmetric) {\n isSymmetric = true;\n } else {\n isSymmetric = matrix.isSymmetric();\n }\n\n if (isSymmetric) {\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = value.get(i, j);\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n var H = getFilled2DArray(n, n, 0),\n ort = new Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H[i][j] = value.get(i, j);\n }\n }\n orthes(n, H, ort, V);\n hqr2(n, e, d, V, H);\n }\n\n this.n = n;\n this.e = e;\n this.d = d;\n this.V = V;\n}\n\nEigenvalueDecomposition.prototype = {\n get realEigenvalues() {\n return this.d;\n },\n get imaginaryEigenvalues() {\n return this.e;\n },\n get eigenvectorMatrix() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n var n = this.n,\n e = this.e,\n d = this.d,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X[i][j] = 0;\n }\n X[i][i] = d[i];\n if (e[i] > 0) {\n X[i][i + 1] = e[i];\n } else if (e[i] < 0) {\n X[i][i - 1] = e[i];\n }\n }\n return X;\n }\n};\n\nfunction tred2(n, e, d, V) {\n\n var f, g, h, i, j, k,\n hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n }\n\n for (i = n - 1; i > 0; i--) {\n scale = 0;\n h = 0;\n for (k = 0; k < i; k++) {\n scale = scale + Math.abs(d[k]);\n }\n\n if (scale === 0) {\n e[i] = d[i - 1];\n for (j = 0; j < i; j++) {\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n V[j][i] = 0;\n }\n } else {\n for (k = 0; k < i; k++) {\n d[k] /= scale;\n h += d[k] * d[k];\n }\n\n f = d[i - 1];\n g = Math.sqrt(h);\n if (f > 0) {\n g = -g;\n }\n\n e[i] = scale * g;\n h = h - f * g;\n d[i - 1] = f - g;\n for (j = 0; j < i; j++) {\n e[j] = 0;\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n V[j][i] = f;\n g = e[j] + V[j][j] * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V[k][j] * d[k];\n e[k] += V[k][j] * f;\n }\n e[j] = g;\n }\n\n f = 0;\n for (j = 0; j < i; j++) {\n e[j] /= h;\n f += e[j] * d[j];\n }\n\n hh = f / (h + h);\n for (j = 0; j < i; j++) {\n e[j] -= hh * d[j];\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n g = e[j];\n for (k = j; k <= i - 1; k++) {\n V[k][j] -= (f * e[k] + g * d[k]);\n }\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V[n - 1][i] = V[i][i];\n V[i][i] = 1;\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V[k][i + 1] / h;\n }\n\n for (j = 0; j <= i; j++) {\n g = 0;\n for (k = 0; k <= i; k++) {\n g += V[k][i + 1] * V[k][j];\n }\n for (k = 0; k <= i; k++) {\n V[k][j] -= g * d[k];\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V[k][i + 1] = 0;\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n V[n - 1][j] = 0;\n }\n\n V[n - 1][n - 1] = 1;\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n\n var g, h, i, j, k, l, m, p, r,\n dl1, c, c2, c3, el1, s, s2,\n iter;\n\n for (i = 1; i < n; i++) {\n e[i - 1] = e[i];\n }\n\n e[n - 1] = 0;\n\n var f = 0,\n tst1 = 0,\n eps = Math.pow(2, -52);\n\n for (l = 0; l < n; l++) {\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\n m = l;\n while (m < n) {\n if (Math.abs(e[m]) <= eps * tst1) {\n break;\n }\n m++;\n }\n\n if (m > l) {\n iter = 0;\n do {\n iter = iter + 1;\n\n g = d[l];\n p = (d[l + 1] - g) / (2 * e[l]);\n r = hypotenuse(p, 1);\n if (p < 0) {\n r = -r;\n }\n\n d[l] = e[l] / (p + r);\n d[l + 1] = e[l] * (p + r);\n dl1 = d[l + 1];\n h = g - d[l];\n for (i = l + 2; i < n; i++) {\n d[i] -= h;\n }\n\n f = f + h;\n\n p = d[m];\n c = 1;\n c2 = c;\n c3 = c;\n el1 = e[l + 1];\n s = 0;\n s2 = 0;\n for (i = m - 1; i >= l; i--) {\n c3 = c2;\n c2 = c;\n s2 = s;\n g = c * e[i];\n h = c * p;\n r = hypotenuse(p, e[i]);\n e[i + 1] = s * r;\n s = e[i] / r;\n c = p / r;\n p = c * d[i] - s * g;\n d[i + 1] = h + s * (c * g + s * d[i]);\n\n for (k = 0; k < n; k++) {\n h = V[k][i + 1];\n V[k][i + 1] = s * V[k][i] + c * h;\n V[k][i] = c * V[k][i] - s * h;\n }\n }\n\n p = -s * s2 * c3 * el1 * e[l] / dl1;\n e[l] = s * p;\n d[l] = c * p;\n\n }\n while (Math.abs(e[l]) > eps * tst1);\n }\n d[l] = d[l] + f;\n e[l] = 0;\n }\n\n for (i = 0; i < n - 1; i++) {\n k = i;\n p = d[i];\n for (j = i + 1; j < n; j++) {\n if (d[j] < p) {\n k = j;\n p = d[j];\n }\n }\n\n if (k !== i) {\n d[k] = d[i];\n d[i] = p;\n for (j = 0; j < n; j++) {\n p = V[j][i];\n V[j][i] = V[j][k];\n V[j][k] = p;\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n\n var low = 0,\n high = n - 1,\n f, g, h, i, j, m,\n scale;\n\n for (m = low + 1; m <= high - 1; m++) {\n scale = 0;\n for (i = m; i <= high; i++) {\n scale = scale + Math.abs(H[i][m - 1]);\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H[i][m - 1] / scale;\n h += ort[i] * ort[i];\n }\n\n g = Math.sqrt(h);\n if (ort[m] > 0) {\n g = -g;\n }\n\n h = h - ort[m] * g;\n ort[m] = ort[m] - g;\n\n for (j = m; j < n; j++) {\n f = 0;\n for (i = high; i >= m; i--) {\n f += ort[i] * H[i][j];\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H[i][j] -= f * ort[i];\n }\n }\n\n for (i = 0; i <= high; i++) {\n f = 0;\n for (j = high; j >= m; j--) {\n f += ort[j] * H[i][j];\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H[i][j] -= f * ort[j];\n }\n }\n\n ort[m] = scale * ort[m];\n H[m][m - 1] = scale * g;\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = (i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H[m][m - 1] !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H[i][m - 1];\n }\n\n for (j = m; j <= high; j++) {\n g = 0;\n for (i = m; i <= high; i++) {\n g += ort[i] * V[i][j];\n }\n\n g = (g / ort[m]) / H[m][m - 1];\n for (i = m; i <= high; i++) {\n V[i][j] += g * ort[i];\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n var n = nn - 1,\n low = 0,\n high = nn - 1,\n eps = Math.pow(2, -52),\n exshift = 0,\n norm = 0,\n p = 0,\n q = 0,\n r = 0,\n s = 0,\n z = 0,\n iter = 0,\n i, j, k, l, m, t, w, x, y,\n ra, sa, vr, vi,\n notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H[i][i];\n e[i] = 0;\n }\n\n for (j = Math.max(i - 1, 0); j < nn; j++) {\n norm = norm + Math.abs(H[i][j]);\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H[l][l - 1]) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H[n][n] = H[n][n] + exshift;\n d[n] = H[n][n];\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H[n][n - 1] * H[n - 1][n];\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H[n][n] = H[n][n] + exshift;\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\n x = H[n][n];\n\n if (q >= 0) {\n z = (p >= 0) ? (p + z) : (p - z);\n d[n - 1] = x + z;\n d[n] = d[n - 1];\n if (z !== 0) {\n d[n] = x - w / z;\n }\n e[n - 1] = 0;\n e[n] = 0;\n x = H[n][n - 1];\n s = Math.abs(x) + Math.abs(z);\n p = x / s;\n q = z / s;\n r = Math.sqrt(p * p + q * q);\n p = p / r;\n q = q / r;\n\n for (j = n - 1; j < nn; j++) {\n z = H[n - 1][j];\n H[n - 1][j] = q * z + p * H[n][j];\n H[n][j] = q * H[n][j] - p * z;\n }\n\n for (i = 0; i <= n; i++) {\n z = H[i][n - 1];\n H[i][n - 1] = q * z + p * H[i][n];\n H[i][n] = q * H[i][n] - p * z;\n }\n\n for (i = low; i <= high; i++) {\n z = V[i][n - 1];\n V[i][n - 1] = q * z + p * V[i][n];\n V[i][n] = q * V[i][n] - p * z;\n }\n } else {\n d[n - 1] = x + p;\n d[n] = x + p;\n e[n - 1] = z;\n e[n] = -z;\n }\n\n n = n - 2;\n iter = 0;\n } else {\n x = H[n][n];\n y = 0;\n w = 0;\n if (l < n) {\n y = H[n - 1][n - 1];\n w = H[n][n - 1] * H[n - 1][n];\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H[i][i] -= x;\n }\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\n x = y = 0.75 * s;\n w = -0.4375 * s * s;\n }\n\n if (iter === 30) {\n s = (y - x) / 2;\n s = s * s + w;\n if (s > 0) {\n s = Math.sqrt(s);\n if (y < x) {\n s = -s;\n }\n s = x - w / ((y - x) / 2 + s);\n for (i = low; i <= n; i++) {\n H[i][i] -= s;\n }\n exshift += s;\n x = y = w = 0.964;\n }\n }\n\n iter = iter + 1;\n\n m = n - 2;\n while (m >= l) {\n z = H[m][m];\n r = x - z;\n s = y - z;\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\n q = H[m + 1][m + 1] - z - r - s;\n r = H[m + 2][m + 1];\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\n p = p / s;\n q = q / s;\n r = r / s;\n if (m === l) {\n break;\n }\n if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H[i][i - 2] = 0;\n if (i > m + 2) {\n H[i][i - 3] = 0;\n }\n }\n\n for (k = m; k <= n - 1; k++) {\n notlast = (k !== n - 1);\n if (k !== m) {\n p = H[k][k - 1];\n q = H[k + 1][k - 1];\n r = (notlast ? H[k + 2][k - 1] : 0);\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\n if (x !== 0) {\n p = p / x;\n q = q / x;\n r = r / x;\n }\n }\n\n if (x === 0) {\n break;\n }\n\n s = Math.sqrt(p * p + q * q + r * r);\n if (p < 0) {\n s = -s;\n }\n\n if (s !== 0) {\n if (k !== m) {\n H[k][k - 1] = -s * x;\n } else if (l !== m) {\n H[k][k - 1] = -H[k][k - 1];\n }\n\n p = p + s;\n x = p / s;\n y = q / s;\n z = r / s;\n q = q / p;\n r = r / p;\n\n for (j = k; j < nn; j++) {\n p = H[k][j] + q * H[k + 1][j];\n if (notlast) {\n p = p + r * H[k + 2][j];\n H[k + 2][j] = H[k + 2][j] - p * z;\n }\n\n H[k][j] = H[k][j] - p * x;\n H[k + 1][j] = H[k + 1][j] - p * y;\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H[i][k] + y * H[i][k + 1];\n if (notlast) {\n p = p + z * H[i][k + 2];\n H[i][k + 2] = H[i][k + 2] - p * r;\n }\n\n H[i][k] = H[i][k] - p;\n H[i][k + 1] = H[i][k + 1] - p * q;\n }\n\n for (i = low; i <= high; i++) {\n p = x * V[i][k] + y * V[i][k + 1];\n if (notlast) {\n p = p + z * V[i][k + 2];\n V[i][k + 2] = V[i][k + 2] - p * r;\n }\n\n V[i][k] = V[i][k] - p;\n V[i][k + 1] = V[i][k + 1] - p * q;\n }\n }\n }\n }\n }\n\n if (norm === 0) {\n return;\n }\n\n for (n = nn - 1; n >= 0; n--) {\n p = d[n];\n q = e[n];\n\n if (q === 0) {\n l = n;\n H[n][n] = 1;\n for (i = n - 1; i >= 0; i--) {\n w = H[i][i] - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H[i][j] * H[j][n];\n }\n\n if (e[i] < 0) {\n z = w;\n s = r;\n } else {\n l = i;\n if (e[i] === 0) {\n H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm));\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H[i][n] = t;\n H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z);\n }\n\n t = Math.abs(H[i][n]);\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\n H[n - 1][n - 1] = q / H[n][n - 1];\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\n } else {\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\n H[n - 1][n - 1] = cdivres[0];\n H[n - 1][n] = cdivres[1];\n }\n\n H[n][n - 1] = 0;\n H[n][n] = 1;\n for (i = n - 2; i >= 0; i--) {\n ra = 0;\n sa = 0;\n for (j = l; j <= n; j++) {\n ra = ra + H[i][j] * H[j][n - 1];\n sa = sa + H[i][j] * H[j][n];\n }\n\n w = H[i][i] - p;\n\n if (e[i] < 0) {\n z = w;\n r = ra;\n s = sa;\n } else {\n l = i;\n if (e[i] === 0) {\n cdivres = cdiv(-ra, -sa, w, q);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\n vi = (d[i] - p) * 2 * q;\n if (vr === 0 && vi === 0) {\n vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z));\n }\n cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) {\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\n } else {\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\n H[i + 1][n - 1] = cdivres[0];\n H[i + 1][n] = cdivres[1];\n }\n }\n\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n - 1] = H[j][n - 1] / t;\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n for (j = i; j < nn; j++) {\n V[i][j] = H[i][j];\n }\n }\n }\n\n for (j = nn - 1; j >= low; j--) {\n for (i = low; i <= high; i++) {\n z = 0;\n for (k = low; k <= Math.min(j, high); k++) {\n z = z + V[i][k] * H[k][j];\n }\n V[i][j] = z;\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n var r, d;\n if (Math.abs(yr) > Math.abs(yi)) {\n r = yi / yr;\n d = yr + r * yi;\n return [(xr + r * xi) / d, (xi - r * xr) / d];\n } else {\n r = yr / yi;\n d = yi + r * yr;\n return [(r * xr + xi) / d, (r * xi - xr) / d];\n }\n}\n\nexport default EigenvalueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/dc/evd.js\n// module id = 217\n// module chunks = 0","import Matrix from './matrix';\n\nimport LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\n\nexport function inverse(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n return solve(matrix, Matrix.eye(matrix.rows));\n}\n\nexport function solve(leftHandSide, rightHandSide) {\n leftHandSide = Matrix.checkMatrix(leftHandSide);\n rightHandSide = Matrix.checkMatrix(rightHandSide);\n return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/decompositions.js\n// module id = 218\n// module chunks = 0","export {default as default, default as Matrix} from './matrix';\nexport {default as abstractMatrix} from './abstractMatrix';\n\nexport {solve, inverse} from './decompositions';\nexport {default as SingularValueDecomposition, default as SVD} from './dc/svd.js';\nexport {default as EigenvalueDecomposition, default as EVD} from './dc/evd.js';\nexport {default as CholeskyDecomposition, default as CHO} from './dc/cholesky.js';\nexport {default as LuDecomposition, default as LU} from './dc/lu.js';\nexport {default as QrDecomposition, default as QR} from './dc/qr.js';\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/index.js\n// module id = 219\n// module chunks = 0","if (!Symbol.species) {\n Symbol.species = Symbol.for('@@species');\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/symbol-species.js\n// module id = 220\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n super(matrix, matrix.rows, 1);\n this.column = column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.column, value);\n return this;\n }\n\n get(rowIndex) {\n return this.matrix.get(rowIndex, this.column);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/column.js\n// module id = 221\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixFlipColumnView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/flipColumn.js\n// module id = 222\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixFlipRowView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/flipRow.js\n// module id = 223\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n super(matrix, 1, matrix.columns);\n this.row = row;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.row, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.row, columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/row.js\n// module id = 224\n// module chunks = 0","import BaseView from './base';\nimport {checkIndices} from '../util';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n var indices = checkIndices(matrix, rowIndices, columnIndices);\n super(matrix, indices.row.length, indices.column.length);\n this.rowIndices = indices.row;\n this.columnIndices = indices.column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/selection.js\n// module id = 225\n// module chunks = 0","import BaseView from './base';\nimport {checkRange} from '../util';\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(this.startRow + rowIndex, this.startColumn + columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/sub.js\n// module id = 226\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixTransposeView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.columns, matrix.rows);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(columnIndex, rowIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(columnIndex, rowIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/~/ml-matrix/src/views/transpose.js\n// module id = 227\n// module chunks = 0","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {solve} from 'ml-matrix';\n\nexport default class RobustPolynomialRegression extends BaseRegression {\n constructor(x, y, degree) {\n super();\n if (x === true) {\n this.degree = y.degree;\n this.powers = y.powers;\n this.coefficients = y.coefficients;\n } else {\n checkArrayLength(x, y);\n robustPolynomial(this, x, y, degree);\n }\n }\n\n toJSON() {\n return {\n name: 'robustPolynomialRegression',\n degree: this.degree,\n powers: this.powers,\n coefficients: this.coefficients\n };\n }\n\n _predict(x) {\n return predict(x, this.powers, this.coefficients);\n }\n\n toString(precision) {\n return this._toFormula(precision, false);\n }\n\n toLaTeX(precision) {\n return this._toFormula(precision, true);\n }\n\n _toFormula(precision, isLaTeX) {\n let sup = '^';\n let closeSup = '';\n let times = ' * ';\n if (isLaTeX) {\n sup = '^{';\n closeSup = '}';\n times = '';\n }\n\n let fn = '';\n let str = '';\n for (let k = 0; k < this.coefficients.length; k++) {\n str = '';\n if (this.coefficients[k] !== 0) {\n if (this.powers[k] === 0) {\n str = maybeToPrecision(this.coefficients[k], precision);\n } else {\n if (this.powers[k] === 1) {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x';\n } else {\n str = maybeToPrecision(this.coefficients[k], precision) + times + 'x' + sup + this.powers[k] + closeSup;\n }\n }\n\n if (this.coefficients[k] > 0 && k !== (this.coefficients.length - 1)) {\n str = ' + ' + str;\n } else if (k !== (this.coefficients.length - 1)) {\n str = ' ' + str;\n }\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'f(x) = ' + fn;\n }\n\n static load(json) {\n if (json.name !== 'robustPolynomialRegression') {\n throw new TypeError('not a RobustPolynomialRegression model');\n }\n return new RobustPolynomialRegression(true, json);\n }\n}\n\nfunction robustPolynomial(regression, x, y, degree) {\n let powers = new Array(degree);\n for (let k = 0; k < degree; k++) {\n powers[k] = k;\n }\n\n const tuples = getRandomTuples(x, y, degree);\n var min;\n\n for (var i = 0; i < tuples.length; i++) {\n var tuple = tuples[i];\n var coefficients = calcCoefficients(tuple, powers);\n\n var residuals = x.slice();\n for (var j = 0; j < x.length; j++) {\n residuals[j] = y[j] - predict(x[j], powers, coefficients);\n residuals[j] = {\n residual: residuals[j] * residuals[j],\n coefficients\n };\n }\n\n var median = residualsMedian(residuals);\n if (!min || median.residual < min.residual) {\n min = median;\n }\n }\n\n regression.degree = degree;\n regression.powers = powers;\n regression.coefficients = min.coefficients;\n}\n\n/**\n * @ignore\n * @param {Array} x\n * @param {Array} y\n * @param {number} degree\n * @return {Array<{x:number,y:number}>}\n */\nfunction getRandomTuples(x, y, degree) {\n var len = Math.floor(x.length / degree);\n var tuples = new Array(len);\n\n for (var i = 0; i < x.length; i++) {\n var pos = Math.floor(Math.random() * len);\n\n var counter = 0;\n while (counter < x.length) {\n if (!tuples[pos]) {\n tuples[pos] = [{\n x: x[i],\n y: y[i]\n }];\n break;\n } else if (tuples[pos].length < degree) {\n tuples[pos].push({\n x: x[i],\n y: y[i]\n });\n break;\n } else {\n counter++;\n pos = (pos + 1) % len;\n }\n }\n\n if (counter === x.length) {\n return tuples;\n }\n }\n return tuples;\n}\n\n/**\n * @ignore\n * @param {{x:number,y:number}} tuple\n * @param {Array} powers\n * @return {Array}\n */\nfunction calcCoefficients(tuple, powers) {\n var X = tuple.slice();\n var Y = tuple.slice();\n for (var i = 0; i < X.length; i++) {\n Y[i] = [tuple[i].y];\n X[i] = new Array(powers.length);\n for (var j = 0; j < powers.length; j++) {\n X[i][j] = Math.pow(tuple[i].x, powers[j]);\n }\n }\n\n return solve(X, Y).to1DArray();\n}\n\nfunction predict(x, powers, coefficients) {\n let y = 0;\n for (let k = 0; k < powers.length; k++) {\n y += coefficients[k] * Math.pow(x, powers[k]);\n }\n return y;\n}\n\nfunction residualsMedian(residuals) {\n residuals.sort((a, b) => a.residual - b.residual);\n\n var l = residuals.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return residuals[half - 1];\n } else {\n return residuals[half];\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-robust-polynomial/src/index.js\n// module id = 228\n// module chunks = 0","import BaseRegression, {checkArrayLength, maybeToPrecision} from 'ml-regression-base';\nimport {array} from 'ml-stat';\nconst median = array.median;\n\nexport default class TheilSenRegression extends BaseRegression {\n\n /**\n * Theil–Sen estimator\n * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n * @param {Array|boolean} x\n * @param {Array|object} y\n * @constructor\n */\n constructor(x, y) {\n super();\n if (x === true) {\n // loads the model\n this.slope = y.slope;\n this.intercept = y.intercept;\n this.coefficients = y.coefficients;\n } else {\n // creates the model\n checkArrayLength(x, y);\n theilSen(this, x, y);\n }\n\n }\n\n toJSON() {\n return {\n name: 'TheilSenRegression',\n slope: this.slope,\n intercept: this.intercept\n };\n }\n\n _predict(input) {\n return this.slope * input + this.intercept;\n }\n\n computeX(input) {\n return (input - this.intercept) / this.slope;\n }\n\n toString(precision) {\n var result = 'f(x) = ';\n if (this.slope) {\n var xFactor = maybeToPrecision(this.slope, precision);\n result += (Math.abs(xFactor - 1) < 1e-5 ? '' : xFactor + ' * ') + 'x';\n if (this.intercept) {\n var absIntercept = Math.abs(this.intercept);\n var operator = absIntercept === this.intercept ? '+' : '-';\n result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision);\n }\n } else {\n result += maybeToPrecision(this.intercept, precision);\n }\n return result;\n }\n\n toLaTeX(precision) {\n return this.toString(precision);\n }\n\n static load(json) {\n if (json.name !== 'TheilSenRegression') {\n throw new TypeError('not a Theil-Sen model');\n }\n return new TheilSenRegression(true, json);\n }\n}\n\nfunction theilSen(regression, x, y) {\n let len = x.length;\n let slopes = new Array(len * len);\n let count = 0;\n for (let i = 0; i < len; ++i) {\n for (let j = i + 1; j < len; ++j) {\n if (x[i] !== x[j]) {\n slopes[count++] = (y[j] - y[i]) / (x[j] - x[i]);\n }\n }\n }\n slopes.length = count;\n let medianSlope = median(slopes);\n\n let cuts = new Array(len);\n for (let i = 0; i < len; ++i) {\n cuts[i] = y[i] - medianSlope * x[i];\n }\n\n regression.slope = medianSlope;\n regression.intercept = median(cuts);\n regression.coefficients = [regression.intercept, regression.slope];\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression-theil-sen/src/index.js\n// module id = 229\n// module chunks = 0","import Matrix from '../matrix';\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/CholeskyDecomposition.cs\nfunction CholeskyDecomposition(value) {\n if (!(this instanceof CholeskyDecomposition)) {\n return new CholeskyDecomposition(value);\n }\n value = Matrix.checkMatrix(value);\n if (!value.isSymmetric()) {\n throw new Error('Matrix is not symmetric');\n }\n\n var a = value,\n dimension = a.rows,\n l = new Matrix(dimension, dimension),\n positiveDefinite = true,\n i, j, k;\n\n for (j = 0; j < dimension; j++) {\n var Lrowj = l[j];\n var d = 0;\n for (k = 0; k < j; k++) {\n var Lrowk = l[k];\n var s = 0;\n for (i = 0; i < k; i++) {\n s += Lrowk[i] * Lrowj[i];\n }\n Lrowj[k] = s = (a[j][k] - s) / l[k][k];\n d = d + s * s;\n }\n\n d = a[j][j] - d;\n\n positiveDefinite &= (d > 0);\n l[j][j] = Math.sqrt(Math.max(d, 0));\n for (k = j + 1; k < dimension; k++) {\n l[j][k] = 0;\n }\n }\n\n if (!positiveDefinite) {\n throw new Error('Matrix is not positive definite');\n }\n\n this.L = l;\n}\n\nCholeskyDecomposition.prototype = {\n get lowerTriangularMatrix() {\n return this.L;\n },\n solve: function (value) {\n value = Matrix.checkMatrix(value);\n\n var l = this.L,\n dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n\n var count = value.columns,\n B = value.clone(),\n i, j, k;\n\n for (k = 0; k < dimension; k++) {\n for (j = 0; j < count; j++) {\n for (i = 0; i < k; i++) {\n B[k][j] -= B[i][j] * l[k][i];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n for (k = dimension - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n for (i = k + 1; i < dimension; i++) {\n B[k][j] -= B[i][j] * l[i][k];\n }\n B[k][j] /= l[k][k];\n }\n }\n\n return B;\n }\n};\n\nexport default CholeskyDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/dc/cholesky.js\n// module id = 230\n// module chunks = 0","import Matrix from '../matrix';\nimport {hypotenuse, getFilled2DArray} from './util';\n\nconst defaultOptions = {\n assumeSymmetric: false\n};\n\n// https://github.com/lutzroeder/Mapack/blob/master/Source/EigenvalueDecomposition.cs\nfunction EigenvalueDecomposition(matrix, options) {\n options = Object.assign({}, defaultOptions, options);\n if (!(this instanceof EigenvalueDecomposition)) {\n return new EigenvalueDecomposition(matrix, options);\n }\n matrix = Matrix.checkMatrix(matrix);\n if (!matrix.isSquare()) {\n throw new Error('Matrix is not a square matrix');\n }\n\n var n = matrix.columns,\n V = getFilled2DArray(n, n, 0),\n d = new Array(n),\n e = new Array(n),\n value = matrix,\n i, j;\n\n var isSymmetric = false;\n if (options.assumeSymmetric) {\n isSymmetric = true;\n } else {\n isSymmetric = matrix.isSymmetric();\n }\n\n if (isSymmetric) {\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = value.get(i, j);\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n var H = getFilled2DArray(n, n, 0),\n ort = new Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H[i][j] = value.get(i, j);\n }\n }\n orthes(n, H, ort, V);\n hqr2(n, e, d, V, H);\n }\n\n this.n = n;\n this.e = e;\n this.d = d;\n this.V = V;\n}\n\nEigenvalueDecomposition.prototype = {\n get realEigenvalues() {\n return this.d;\n },\n get imaginaryEigenvalues() {\n return this.e;\n },\n get eigenvectorMatrix() {\n if (!Matrix.isMatrix(this.V)) {\n this.V = new Matrix(this.V);\n }\n return this.V;\n },\n get diagonalMatrix() {\n var n = this.n,\n e = this.e,\n d = this.d,\n X = new Matrix(n, n),\n i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X[i][j] = 0;\n }\n X[i][i] = d[i];\n if (e[i] > 0) {\n X[i][i + 1] = e[i];\n } else if (e[i] < 0) {\n X[i][i - 1] = e[i];\n }\n }\n return X;\n }\n};\n\nfunction tred2(n, e, d, V) {\n\n var f, g, h, i, j, k,\n hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n }\n\n for (i = n - 1; i > 0; i--) {\n scale = 0;\n h = 0;\n for (k = 0; k < i; k++) {\n scale = scale + Math.abs(d[k]);\n }\n\n if (scale === 0) {\n e[i] = d[i - 1];\n for (j = 0; j < i; j++) {\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n V[j][i] = 0;\n }\n } else {\n for (k = 0; k < i; k++) {\n d[k] /= scale;\n h += d[k] * d[k];\n }\n\n f = d[i - 1];\n g = Math.sqrt(h);\n if (f > 0) {\n g = -g;\n }\n\n e[i] = scale * g;\n h = h - f * g;\n d[i - 1] = f - g;\n for (j = 0; j < i; j++) {\n e[j] = 0;\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n V[j][i] = f;\n g = e[j] + V[j][j] * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V[k][j] * d[k];\n e[k] += V[k][j] * f;\n }\n e[j] = g;\n }\n\n f = 0;\n for (j = 0; j < i; j++) {\n e[j] /= h;\n f += e[j] * d[j];\n }\n\n hh = f / (h + h);\n for (j = 0; j < i; j++) {\n e[j] -= hh * d[j];\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n g = e[j];\n for (k = j; k <= i - 1; k++) {\n V[k][j] -= (f * e[k] + g * d[k]);\n }\n d[j] = V[i - 1][j];\n V[i][j] = 0;\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V[n - 1][i] = V[i][i];\n V[i][i] = 1;\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V[k][i + 1] / h;\n }\n\n for (j = 0; j <= i; j++) {\n g = 0;\n for (k = 0; k <= i; k++) {\n g += V[k][i + 1] * V[k][j];\n }\n for (k = 0; k <= i; k++) {\n V[k][j] -= g * d[k];\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V[k][i + 1] = 0;\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V[n - 1][j];\n V[n - 1][j] = 0;\n }\n\n V[n - 1][n - 1] = 1;\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n\n var g, h, i, j, k, l, m, p, r,\n dl1, c, c2, c3, el1, s, s2,\n iter;\n\n for (i = 1; i < n; i++) {\n e[i - 1] = e[i];\n }\n\n e[n - 1] = 0;\n\n var f = 0,\n tst1 = 0,\n eps = Math.pow(2, -52);\n\n for (l = 0; l < n; l++) {\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\n m = l;\n while (m < n) {\n if (Math.abs(e[m]) <= eps * tst1) {\n break;\n }\n m++;\n }\n\n if (m > l) {\n iter = 0;\n do {\n iter = iter + 1;\n\n g = d[l];\n p = (d[l + 1] - g) / (2 * e[l]);\n r = hypotenuse(p, 1);\n if (p < 0) {\n r = -r;\n }\n\n d[l] = e[l] / (p + r);\n d[l + 1] = e[l] * (p + r);\n dl1 = d[l + 1];\n h = g - d[l];\n for (i = l + 2; i < n; i++) {\n d[i] -= h;\n }\n\n f = f + h;\n\n p = d[m];\n c = 1;\n c2 = c;\n c3 = c;\n el1 = e[l + 1];\n s = 0;\n s2 = 0;\n for (i = m - 1; i >= l; i--) {\n c3 = c2;\n c2 = c;\n s2 = s;\n g = c * e[i];\n h = c * p;\n r = hypotenuse(p, e[i]);\n e[i + 1] = s * r;\n s = e[i] / r;\n c = p / r;\n p = c * d[i] - s * g;\n d[i + 1] = h + s * (c * g + s * d[i]);\n\n for (k = 0; k < n; k++) {\n h = V[k][i + 1];\n V[k][i + 1] = s * V[k][i] + c * h;\n V[k][i] = c * V[k][i] - s * h;\n }\n }\n\n p = -s * s2 * c3 * el1 * e[l] / dl1;\n e[l] = s * p;\n d[l] = c * p;\n\n }\n while (Math.abs(e[l]) > eps * tst1);\n }\n d[l] = d[l] + f;\n e[l] = 0;\n }\n\n for (i = 0; i < n - 1; i++) {\n k = i;\n p = d[i];\n for (j = i + 1; j < n; j++) {\n if (d[j] < p) {\n k = j;\n p = d[j];\n }\n }\n\n if (k !== i) {\n d[k] = d[i];\n d[i] = p;\n for (j = 0; j < n; j++) {\n p = V[j][i];\n V[j][i] = V[j][k];\n V[j][k] = p;\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n\n var low = 0,\n high = n - 1,\n f, g, h, i, j, m,\n scale;\n\n for (m = low + 1; m <= high - 1; m++) {\n scale = 0;\n for (i = m; i <= high; i++) {\n scale = scale + Math.abs(H[i][m - 1]);\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H[i][m - 1] / scale;\n h += ort[i] * ort[i];\n }\n\n g = Math.sqrt(h);\n if (ort[m] > 0) {\n g = -g;\n }\n\n h = h - ort[m] * g;\n ort[m] = ort[m] - g;\n\n for (j = m; j < n; j++) {\n f = 0;\n for (i = high; i >= m; i--) {\n f += ort[i] * H[i][j];\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H[i][j] -= f * ort[i];\n }\n }\n\n for (i = 0; i <= high; i++) {\n f = 0;\n for (j = high; j >= m; j--) {\n f += ort[j] * H[i][j];\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H[i][j] -= f * ort[j];\n }\n }\n\n ort[m] = scale * ort[m];\n H[m][m - 1] = scale * g;\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V[i][j] = (i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H[m][m - 1] !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H[i][m - 1];\n }\n\n for (j = m; j <= high; j++) {\n g = 0;\n for (i = m; i <= high; i++) {\n g += ort[i] * V[i][j];\n }\n\n g = (g / ort[m]) / H[m][m - 1];\n for (i = m; i <= high; i++) {\n V[i][j] += g * ort[i];\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n var n = nn - 1,\n low = 0,\n high = nn - 1,\n eps = Math.pow(2, -52),\n exshift = 0,\n norm = 0,\n p = 0,\n q = 0,\n r = 0,\n s = 0,\n z = 0,\n iter = 0,\n i, j, k, l, m, t, w, x, y,\n ra, sa, vr, vi,\n notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H[i][i];\n e[i] = 0;\n }\n\n for (j = Math.max(i - 1, 0); j < nn; j++) {\n norm = norm + Math.abs(H[i][j]);\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H[l][l - 1]) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H[n][n] = H[n][n] + exshift;\n d[n] = H[n][n];\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H[n][n - 1] * H[n - 1][n];\n p = (H[n - 1][n - 1] - H[n][n]) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H[n][n] = H[n][n] + exshift;\n H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;\n x = H[n][n];\n\n if (q >= 0) {\n z = (p >= 0) ? (p + z) : (p - z);\n d[n - 1] = x + z;\n d[n] = d[n - 1];\n if (z !== 0) {\n d[n] = x - w / z;\n }\n e[n - 1] = 0;\n e[n] = 0;\n x = H[n][n - 1];\n s = Math.abs(x) + Math.abs(z);\n p = x / s;\n q = z / s;\n r = Math.sqrt(p * p + q * q);\n p = p / r;\n q = q / r;\n\n for (j = n - 1; j < nn; j++) {\n z = H[n - 1][j];\n H[n - 1][j] = q * z + p * H[n][j];\n H[n][j] = q * H[n][j] - p * z;\n }\n\n for (i = 0; i <= n; i++) {\n z = H[i][n - 1];\n H[i][n - 1] = q * z + p * H[i][n];\n H[i][n] = q * H[i][n] - p * z;\n }\n\n for (i = low; i <= high; i++) {\n z = V[i][n - 1];\n V[i][n - 1] = q * z + p * V[i][n];\n V[i][n] = q * V[i][n] - p * z;\n }\n } else {\n d[n - 1] = x + p;\n d[n] = x + p;\n e[n - 1] = z;\n e[n] = -z;\n }\n\n n = n - 2;\n iter = 0;\n } else {\n x = H[n][n];\n y = 0;\n w = 0;\n if (l < n) {\n y = H[n - 1][n - 1];\n w = H[n][n - 1] * H[n - 1][n];\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H[i][i] -= x;\n }\n s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);\n x = y = 0.75 * s;\n w = -0.4375 * s * s;\n }\n\n if (iter === 30) {\n s = (y - x) / 2;\n s = s * s + w;\n if (s > 0) {\n s = Math.sqrt(s);\n if (y < x) {\n s = -s;\n }\n s = x - w / ((y - x) / 2 + s);\n for (i = low; i <= n; i++) {\n H[i][i] -= s;\n }\n exshift += s;\n x = y = w = 0.964;\n }\n }\n\n iter = iter + 1;\n\n m = n - 2;\n while (m >= l) {\n z = H[m][m];\n r = x - z;\n s = y - z;\n p = (r * s - w) / H[m + 1][m] + H[m][m + 1];\n q = H[m + 1][m + 1] - z - r - s;\n r = H[m + 2][m + 1];\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\n p = p / s;\n q = q / s;\n r = r / s;\n if (m === l) {\n break;\n }\n if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H[i][i - 2] = 0;\n if (i > m + 2) {\n H[i][i - 3] = 0;\n }\n }\n\n for (k = m; k <= n - 1; k++) {\n notlast = (k !== n - 1);\n if (k !== m) {\n p = H[k][k - 1];\n q = H[k + 1][k - 1];\n r = (notlast ? H[k + 2][k - 1] : 0);\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\n if (x !== 0) {\n p = p / x;\n q = q / x;\n r = r / x;\n }\n }\n\n if (x === 0) {\n break;\n }\n\n s = Math.sqrt(p * p + q * q + r * r);\n if (p < 0) {\n s = -s;\n }\n\n if (s !== 0) {\n if (k !== m) {\n H[k][k - 1] = -s * x;\n } else if (l !== m) {\n H[k][k - 1] = -H[k][k - 1];\n }\n\n p = p + s;\n x = p / s;\n y = q / s;\n z = r / s;\n q = q / p;\n r = r / p;\n\n for (j = k; j < nn; j++) {\n p = H[k][j] + q * H[k + 1][j];\n if (notlast) {\n p = p + r * H[k + 2][j];\n H[k + 2][j] = H[k + 2][j] - p * z;\n }\n\n H[k][j] = H[k][j] - p * x;\n H[k + 1][j] = H[k + 1][j] - p * y;\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H[i][k] + y * H[i][k + 1];\n if (notlast) {\n p = p + z * H[i][k + 2];\n H[i][k + 2] = H[i][k + 2] - p * r;\n }\n\n H[i][k] = H[i][k] - p;\n H[i][k + 1] = H[i][k + 1] - p * q;\n }\n\n for (i = low; i <= high; i++) {\n p = x * V[i][k] + y * V[i][k + 1];\n if (notlast) {\n p = p + z * V[i][k + 2];\n V[i][k + 2] = V[i][k + 2] - p * r;\n }\n\n V[i][k] = V[i][k] - p;\n V[i][k + 1] = V[i][k + 1] - p * q;\n }\n }\n }\n }\n }\n\n if (norm === 0) {\n return;\n }\n\n for (n = nn - 1; n >= 0; n--) {\n p = d[n];\n q = e[n];\n\n if (q === 0) {\n l = n;\n H[n][n] = 1;\n for (i = n - 1; i >= 0; i--) {\n w = H[i][i] - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H[i][j] * H[j][n];\n }\n\n if (e[i] < 0) {\n z = w;\n s = r;\n } else {\n l = i;\n if (e[i] === 0) {\n H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm));\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H[i][n] = t;\n H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z);\n }\n\n t = Math.abs(H[i][n]);\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {\n H[n - 1][n - 1] = q / H[n][n - 1];\n H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];\n } else {\n cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q);\n H[n - 1][n - 1] = cdivres[0];\n H[n - 1][n] = cdivres[1];\n }\n\n H[n][n - 1] = 0;\n H[n][n] = 1;\n for (i = n - 2; i >= 0; i--) {\n ra = 0;\n sa = 0;\n for (j = l; j <= n; j++) {\n ra = ra + H[i][j] * H[j][n - 1];\n sa = sa + H[i][j] * H[j][n];\n }\n\n w = H[i][i] - p;\n\n if (e[i] < 0) {\n z = w;\n r = ra;\n s = sa;\n } else {\n l = i;\n if (e[i] === 0) {\n cdivres = cdiv(-ra, -sa, w, q);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n } else {\n x = H[i][i + 1];\n y = H[i + 1][i];\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\n vi = (d[i] - p) * 2 * q;\n if (vr === 0 && vi === 0) {\n vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z));\n }\n cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);\n H[i][n - 1] = cdivres[0];\n H[i][n] = cdivres[1];\n if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) {\n H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;\n H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;\n } else {\n cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);\n H[i + 1][n - 1] = cdivres[0];\n H[i + 1][n] = cdivres[1];\n }\n }\n\n t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));\n if ((eps * t) * t > 1) {\n for (j = i; j <= n; j++) {\n H[j][n - 1] = H[j][n - 1] / t;\n H[j][n] = H[j][n] / t;\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n for (j = i; j < nn; j++) {\n V[i][j] = H[i][j];\n }\n }\n }\n\n for (j = nn - 1; j >= low; j--) {\n for (i = low; i <= high; i++) {\n z = 0;\n for (k = low; k <= Math.min(j, high); k++) {\n z = z + V[i][k] * H[k][j];\n }\n V[i][j] = z;\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n var r, d;\n if (Math.abs(yr) > Math.abs(yi)) {\n r = yi / yr;\n d = yr + r * yi;\n return [(xr + r * xi) / d, (xi - r * xr) / d];\n } else {\n r = yr / yi;\n d = yi + r * yr;\n return [(r * xr + xi) / d, (r * xi - xr) / d];\n }\n}\n\nexport default EigenvalueDecomposition;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/dc/evd.js\n// module id = 231\n// module chunks = 0","import Matrix from './matrix';\n\nimport LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\n\nexport function inverse(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n return solve(matrix, Matrix.eye(matrix.rows));\n}\n\nexport function solve(leftHandSide, rightHandSide) {\n leftHandSide = Matrix.checkMatrix(leftHandSide);\n rightHandSide = Matrix.checkMatrix(rightHandSide);\n return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/decompositions.js\n// module id = 232\n// module chunks = 0","if (!Symbol.species) {\n Symbol.species = Symbol.for('@@species');\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/symbol-species.js\n// module id = 233\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n super(matrix, matrix.rows, 1);\n this.column = column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.column, value);\n return this;\n }\n\n get(rowIndex) {\n return this.matrix.get(rowIndex, this.column);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/views/column.js\n// module id = 234\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixFlipColumnView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/views/flipColumn.js\n// module id = 235\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixFlipRowView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/views/flipRow.js\n// module id = 236\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n super(matrix, 1, matrix.columns);\n this.row = row;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.row, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.row, columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/views/row.js\n// module id = 237\n// module chunks = 0","import BaseView from './base';\nimport {checkIndices} from '../util';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n var indices = checkIndices(matrix, rowIndices, columnIndices);\n super(matrix, indices.row.length, indices.column.length);\n this.rowIndices = indices.row;\n this.columnIndices = indices.column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/views/selection.js\n// module id = 238\n// module chunks = 0","import BaseView from './base';\nimport {checkRange} from '../util';\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(this.startRow + rowIndex, this.startColumn + columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/views/sub.js\n// module id = 239\n// module chunks = 0","import BaseView from './base';\n\nexport default class MatrixTransposeView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.columns, matrix.rows);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(columnIndex, rowIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(columnIndex, rowIndex);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/~/ml-matrix/src/views/transpose.js\n// module id = 240\n// module chunks = 0","'use strict';\n\nconst matrixLib = require('ml-matrix');\nconst Matrix = matrixLib.Matrix;\nconst solve = matrixLib.solve;\nconst Kernel = require('ml-kernel');\n\nconst BaseRegression = require('./base-regression');\n\nconst defaultOptions = {\n lambda: 0.1,\n kernelType: 'gaussian',\n kernelOptions: {},\n computeCoefficient: false\n};\n\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nclass KernelRidgeRegression extends BaseRegression {\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.alpha = outputs.alpha;\n this.inputs = outputs.inputs;\n this.kernelType = outputs.kernelType;\n this.kernelOptions = outputs.kernelOptions;\n this.kernel = new Kernel(outputs.kernelType, outputs.kernelOptions);\n\n if (outputs.quality) {\n this.quality = outputs.quality;\n }\n } else {\n options = Object.assign({}, defaultOptions, options);\n\n const kernelFunction = new Kernel(options.kernelType, options.kernelOptions);\n const K = kernelFunction.compute(inputs);\n const n = inputs.length;\n K.add(Matrix.eye(n, n).mul(options.lambda));\n\n this.alpha = solve(K, outputs);\n this.inputs = inputs;\n this.kernelType = options.kernelType;\n this.kernelOptions = options.kernelOptions;\n this.kernel = kernelFunction;\n\n if (options.computeQuality) {\n this.quality = this.modelQuality(inputs, outputs);\n }\n }\n }\n\n _predict(newInputs) {\n return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0];\n }\n\n toJSON() {\n var out = {\n name: 'kernelRidgeRegression',\n alpha: this.alpha,\n inputs: this.inputs,\n kernelType: this.kernelType,\n kernelOptions: this.kernelOptions\n };\n if (this.quality) {\n out.quality = this.quality;\n }\n return out;\n }\n\n static load(json) {\n if (json.name !== 'kernelRidgeRegression') {\n throw new TypeError('not a KRR model');\n }\n return new KernelRidgeRegression(true, json);\n }\n}\n\nmodule.exports = KernelRidgeRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/kernel-ridge-regression.js\n// module id = 241\n// module chunks = 0","'use strict';\n\nconst matrixLib = require('ml-matrix');\nconst Matrix = matrixLib.Matrix;\nconst SVD = matrixLib.SVD;\nconst BaseRegression = require('./base-regression');\n\nconst defaultOptions = {\n order: 2\n};\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nclass PolynomialFitRegression2D extends BaseRegression {\n /**\n * Constructor for the 2D polynomial fitting\n *\n * @param inputs\n * @param outputs\n * @param options\n * @constructor\n */\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) { // reloading model\n this.coefficients = Matrix.columnVector(outputs.coefficients);\n this.order = outputs.order;\n if (outputs.r) {\n this.r = outputs.r;\n this.r2 = outputs.r2;\n }\n if (outputs.chi2) {\n this.chi2 = outputs.chi2;\n }\n } else {\n options = Object.assign({}, defaultOptions, options);\n this.order = options.order;\n this.coefficients = [];\n this.X = inputs;\n this.y = outputs;\n\n this.train(this.X, this.y, options);\n\n if (options.computeQuality) {\n this.quality = this.modelQuality(inputs, outputs);\n }\n }\n }\n\n /**\n * Function that fits the model given the data(X) and predictions(y).\n * The third argument is an object with the following options:\n * * order: order of the polynomial to fit.\n *\n * @param {Matrix} X - A matrix with n rows and 2 columns.\n * @param {Matrix} y - A vector of the prediction values.\n */\n train(X, y) {\n if (!Matrix.isMatrix(X)) X = new Matrix(X);\n if (!Matrix.isMatrix(y)) y = Matrix.columnVector(y);\n\n //Perhaps y is transpose\n if (y.rows !== X.rows) {\n y = y.transpose();\n }\n\n if (X.columns !== 2) {\n throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2');\n }\n if (X.rows !== y.rows) {\n throw new RangeError('X and y must have the same rows');\n }\n\n var examples = X.rows;\n var coefficients = ((this.order + 2) * (this.order + 1)) / 2;\n this.coefficients = new Array(coefficients);\n\n var x1 = X.getColumnVector(0);\n var x2 = X.getColumnVector(1);\n\n var scaleX1 = 1.0 / x1.clone().apply(abs).max();\n var scaleX2 = 1.0 / x2.clone().apply(abs).max();\n var scaleY = 1.0 / y.clone().apply(abs).max();\n\n x1.mulColumn(0, scaleX1);\n x2.mulColumn(0, scaleX2);\n y.mulColumn(0, scaleY);\n\n var A = new Matrix(examples, coefficients);\n var col = 0;\n\n for (var i = 0; i <= this.order; ++i) {\n var limit = this.order - i;\n for (var j = 0; j <= limit; ++j) {\n var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j));\n A.setColumn(col, result);\n col++;\n }\n }\n\n var svd = new SVD(A.transpose(), {\n computeLeftSingularVectors: true,\n computeRightSingularVectors: true,\n autoTranspose: false\n });\n\n var qqs = Matrix.rowVector(svd.diagonal);\n qqs = qqs.apply(function (i, j) {\n if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j];\n else this[i][j] = 0;\n });\n\n var qqs1 = Matrix.zeros(examples, coefficients);\n for (i = 0; i < coefficients; ++i) {\n qqs1[i][i] = qqs[0][i];\n }\n\n qqs = qqs1;\n\n var U = svd.rightSingularVectors;\n var V = svd.leftSingularVectors;\n\n this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y);\n\n col = 0;\n\n for (i = 0; i <= coefficients; ++i) {\n limit = this.order - i;\n for (j = 0; j <= limit; ++j) {\n this.coefficients[col][0] = (this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j)) / scaleY;\n col++;\n }\n }\n }\n\n _predict(newInputs) {\n var x1 = newInputs[0];\n var x2 = newInputs[1];\n\n var y = 0;\n var column = 0;\n\n for (var i = 0; i <= this.order; i++) {\n for (var j = 0; j <= this.order - i; j++) {\n y += Math.pow(x1, i) * (Math.pow(x2, j)) * this.coefficients[column][0];\n column++;\n }\n }\n\n return y;\n }\n\n toJSON() {\n var out = {\n name: 'polyfit2D',\n order: this.order,\n coefficients: this.coefficients\n };\n if (this.quality) {\n out.quality = this.quality;\n }\n return out;\n }\n\n static load(json) {\n if (json.name !== 'polyfit2D') {\n throw new TypeError('not a polyfit2D model');\n }\n return new PolynomialFitRegression2D(true, json);\n }\n\n}\n\nmodule.exports = PolynomialFitRegression2D;\n\n\n/**\n * Function that given a column vector return this: vector^power\n *\n * @param x - Column vector.\n * @param power - Pow number.\n * @return {Suite|Matrix}\n */\nfunction powColVector(x, power) {\n var result = x.clone();\n for (var i = 0; i < x.rows; ++i) {\n result[i][0] = Math.pow(result[i][0], power);\n }\n return result;\n}\n\n/**\n * Function to use in the apply method to get the absolute value\n * of each element of the matrix\n *\n * @param i - current row.\n * @param j - current column.\n */\nfunction abs(i, j) {\n this[i][j] = Math.abs(this[i][j]);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/poly-fit-regression2d.js\n// module id = 242\n// module chunks = 0","'use strict';\n\n/*\n * Function that calculate the potential fit in the form f(x) = A*x^M\n * with a given M and return de A coefficient.\n *\n * @param {Vector} X - Vector of the x positions of the points.\n * @param {Vector} Y - Vector of the x positions of the points.\n * @param {Number, BigNumber} M - The exponent of the potential fit.\n * @return {Number|BigNumber} A - The A coefficient of the potential fit.\n * Created by acastillo on 5/12/16.\n */\n\nconst maybeToPrecision = require('./util').maybeToPrecision;\nconst PolynomialRegression = require('ml-regression-polynomial');\n// const PowerRegression = require('./power-regression');\nconst BaseRegression = require('./base-regression');\n\nclass PotentialRegression extends BaseRegression {\n /**\n * @constructor\n * @param x: Independent variable\n * @param y: Dependent variable\n * @param M\n * @param options\n */\n constructor(x, y, M, options) {\n super();\n let opt = options || {};\n if (x === true) { // reloading model\n this.A = y.A;\n this.M = y.M;\n if (y.quality) {\n this.quality = y.quality;\n }\n } else {\n var n = x.length;\n if (n !== y.length) {\n throw new RangeError('input and output array have a different length');\n }\n\n var linear = new PolynomialRegression(x, y, [M]);\n this.A = linear.coefficients[0];\n this.M = M;\n if (opt.computeQuality) {\n this.quality = this.modelQuality(x, y);\n }\n }\n }\n\n _predict(x) {\n return this.A * Math.pow(x, this.M);\n }\n\n toJSON() {\n var out = {name: 'potentialRegression', A: this.A, M: this.M};\n if (this.quality) {\n out.quality = this.quality;\n }\n return out;\n }\n\n toString(precision) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + this.M;\n }\n\n toLaTeX(precision) {\n\n if (this.M >= 0) {\n return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}';\n } else {\n return 'f(x) = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + (-this.M) + '}}';\n }\n }\n\n static load(json) {\n if (json.name !== 'potentialRegression') {\n throw new TypeError('not a potential regression model');\n }\n return new PotentialRegression(true, json);\n }\n}\n\nmodule.exports = PotentialRegression;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/potential-regression.js\n// module id = 243\n// module chunks = 0","'use strict';\n\nexports.maybeToPrecision = function maybeToPrecision(value, digits) {\n if (value < 0) {\n value = -1 * value;\n if (digits) {\n return '- ' + value.toPrecision(digits);\n } else {\n return '- ' + value.toString();\n }\n } else {\n if (digits) {\n return value.toPrecision(digits);\n } else {\n return value.toString();\n }\n }\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-regression/src/regression/util.js\n// module id = 244\n// module chunks = 0","'use strict';\n\nexports.array = require('./array');\nexports.matrix = require('./matrix');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-savitzky-golay-generalized/~/ml-stat/index.js\n// module id = 245\n// module chunks = 0","'use strict';\nvar arrayStat = require('./array');\n\n// https://github.com/accord-net/framework/blob/development/Sources/Accord.Statistics/Tools.cs\n\nfunction entropy(matrix, eps) {\n if (typeof(eps) === 'undefined') {\n eps = 0;\n }\n var sum = 0,\n l1 = matrix.length,\n l2 = matrix[0].length;\n for (var i = 0; i < l1; i++) {\n for (var j = 0; j < l2; j++) {\n sum += matrix[i][j] * Math.log(matrix[i][j] + eps);\n }\n }\n return -sum;\n}\n\nfunction mean(matrix, dimension) {\n if (typeof(dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theMean, N, i, j;\n\n if (dimension === -1) {\n theMean = [0];\n N = rows * cols;\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theMean[0] += matrix[i][j];\n }\n }\n theMean[0] /= N;\n } else if (dimension === 0) {\n theMean = new Array(cols);\n N = rows;\n for (j = 0; j < cols; j++) {\n theMean[j] = 0;\n for (i = 0; i < rows; i++) {\n theMean[j] += matrix[i][j];\n }\n theMean[j] /= N;\n }\n } else if (dimension === 1) {\n theMean = new Array(rows);\n N = cols;\n for (j = 0; j < rows; j++) {\n theMean[j] = 0;\n for (i = 0; i < cols; i++) {\n theMean[j] += matrix[j][i];\n }\n theMean[j] /= N;\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theMean;\n}\n\nfunction standardDeviation(matrix, means, unbiased) {\n var vari = variance(matrix, means, unbiased), l = vari.length;\n for (var i = 0; i < l; i++) {\n vari[i] = Math.sqrt(vari[i]);\n }\n return vari;\n}\n\nfunction variance(matrix, means, unbiased) {\n if (typeof(unbiased) === 'undefined') {\n unbiased = true;\n }\n means = means || mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum1 = 0, sum2 = 0, x = 0;\n for (var i = 0; i < rows; i++) {\n x = matrix[i][j] - means[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1);\n } else {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows;\n }\n }\n return vari;\n}\n\nfunction median(matrix) {\n var rows = matrix.length, cols = matrix[0].length;\n var medians = new Array(cols);\n\n for (var i = 0; i < cols; i++) {\n var data = new Array(rows);\n for (var j = 0; j < rows; j++) {\n data[j] = matrix[j][i];\n }\n data.sort();\n var N = data.length;\n if (N % 2 === 0) {\n medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5;\n } else {\n medians[i] = data[Math.floor(N / 2)];\n }\n }\n return medians;\n}\n\nfunction mode(matrix) {\n var rows = matrix.length,\n cols = matrix[0].length,\n modes = new Array(cols),\n i, j;\n for (i = 0; i < cols; i++) {\n var itemCount = new Array(rows);\n for (var k = 0; k < rows; k++) {\n itemCount[k] = 0;\n }\n var itemArray = new Array(rows);\n var count = 0;\n\n for (j = 0; j < rows; j++) {\n var index = itemArray.indexOf(matrix[j][i]);\n if (index >= 0) {\n itemCount[index]++;\n } else {\n itemArray[count] = matrix[j][i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (j = 0; j < count; j++) {\n if (itemCount[j] > maxValue) {\n maxValue = itemCount[j];\n maxIndex = j;\n }\n }\n\n modes[i] = itemArray[maxIndex];\n }\n return modes;\n}\n\nfunction skewness(matrix, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var means = mean(matrix);\n var n = matrix.length, l = means.length;\n var skew = new Array(l);\n\n for (var j = 0; j < l; j++) {\n var s2 = 0, s3 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n\n var m2 = s2 / n;\n var m3 = s3 / n;\n var g = m3 / Math.pow(m2, 3 / 2);\n\n if (unbiased) {\n var a = Math.sqrt(n * (n - 1));\n var b = n - 2;\n skew[j] = (a / b) * g;\n } else {\n skew[j] = g;\n }\n }\n return skew;\n}\n\nfunction kurtosis(matrix, unbiased) {\n if (typeof(unbiased) === 'undefined') unbiased = true;\n var means = mean(matrix);\n var n = matrix.length, m = matrix[0].length;\n var kurt = new Array(m);\n\n for (var j = 0; j < m; j++) {\n var s2 = 0, s4 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n kurt[j] = a * b - 3 * c;\n } else {\n kurt[j] = m4 / (m2 * m2) - 3;\n }\n }\n return kurt;\n}\n\nfunction standardError(matrix) {\n var samples = matrix.length;\n var standardDeviations = standardDeviation(matrix), l = standardDeviations.length;\n var standardErrors = new Array(l);\n var sqrtN = Math.sqrt(samples);\n\n for (var i = 0; i < l; i++) {\n standardErrors[i] = standardDeviations[i] / sqrtN;\n }\n return standardErrors;\n}\n\nfunction covariance(matrix, dimension) {\n return scatter(matrix, undefined, dimension);\n}\n\nfunction scatter(matrix, divisor, dimension) {\n if (typeof(dimension) === 'undefined') {\n dimension = 0;\n }\n if (typeof(divisor) === 'undefined') {\n if (dimension === 0) {\n divisor = matrix.length - 1;\n } else if (dimension === 1) {\n divisor = matrix[0].length - 1;\n }\n }\n var means = mean(matrix, dimension),\n rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, s, k;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n}\n\nfunction correlation(matrix) {\n var means = mean(matrix),\n standardDeviations = standardDeviation(matrix, true, means),\n scores = zScores(matrix, means, standardDeviations),\n rows = matrix.length,\n cols = matrix[0].length,\n i, j;\n\n var cor = new Array(cols);\n for (i = 0; i < cols; i++) {\n cor[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n var c = 0;\n for (var k = 0, l = scores.length; k < l; k++) {\n c += scores[k][j] * scores[k][i];\n }\n c /= rows - 1;\n cor[i][j] = c;\n cor[j][i] = c;\n }\n }\n return cor;\n}\n\nfunction zScores(matrix, means, standardDeviations) {\n means = means || mean(matrix);\n if (typeof(standardDeviations) === 'undefined') standardDeviations = standardDeviation(matrix, true, means);\n return standardize(center(matrix, means, false), standardDeviations, true);\n}\n\nfunction center(matrix, means, inPlace) {\n means = means || mean(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var row = result[i];\n for (j = 0, jj = row.length; j < jj; j++) {\n row[j] = matrix[i][j] - means[j];\n }\n }\n return result;\n}\n\nfunction standardize(matrix, standardDeviations, inPlace) {\n if (typeof(standardDeviations) === 'undefined') standardDeviations = standardDeviation(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var resultRow = result[i];\n var sourceRow = matrix[i];\n for (j = 0, jj = resultRow.length; j < jj; j++) {\n if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {\n resultRow[j] = sourceRow[j] / standardDeviations[j];\n }\n }\n }\n return result;\n}\n\nfunction weightedVariance(matrix, weights) {\n var means = mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum = 0;\n var a = 0, b = 0;\n\n for (var i = 0; i < rows; i++) {\n var z = matrix[i][j] - means[j];\n var w = weights[i];\n\n sum += w * (z * z);\n b += w;\n a += w * w;\n }\n\n vari[j] = sum * (b / (b * b - a));\n }\n\n return vari;\n}\n\nfunction weightedMean(matrix, weights, dimension) {\n if (typeof(dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length,\n means, i, ii, j, w, row;\n\n if (dimension === 0) {\n means = new Array(cols);\n for (i = 0; i < cols; i++) {\n means[i] = 0;\n }\n for (i = 0; i < rows; i++) {\n row = matrix[i];\n w = weights[i];\n for (j = 0; j < cols; j++) {\n means[j] += row[j] * w;\n }\n }\n } else if (dimension === 1) {\n means = new Array(rows);\n for (i = 0; i < rows; i++) {\n means[i] = 0;\n }\n for (j = 0; j < rows; j++) {\n row = matrix[j];\n w = weights[j];\n for (i = 0; i < cols; i++) {\n means[j] += row[i] * w;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n var weightSum = arrayStat.sum(weights);\n if (weightSum !== 0) {\n for (i = 0, ii = means.length; i < ii; i++) {\n means[i] /= weightSum;\n }\n }\n return means;\n}\n\nfunction weightedCovariance(matrix, weights, means, dimension) {\n dimension = dimension || 0;\n means = means || weightedMean(matrix, weights, dimension);\n var s1 = 0, s2 = 0;\n for (var i = 0, ii = weights.length; i < ii; i++) {\n s1 += weights[i];\n s2 += weights[i] * weights[i];\n }\n var factor = s1 / (s1 * s1 - s2);\n return weightedScatter(matrix, weights, means, factor, dimension);\n}\n\nfunction weightedScatter(matrix, weights, means, factor, dimension) {\n dimension = dimension || 0;\n means = means || weightedMean(matrix, weights, dimension);\n if (typeof(factor) === 'undefined') {\n factor = 1;\n }\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, k, s;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n}\n\nmodule.exports = {\n entropy: entropy,\n mean: mean,\n standardDeviation: standardDeviation,\n variance: variance,\n median: median,\n mode: mode,\n skewness: skewness,\n kurtosis: kurtosis,\n standardError: standardError,\n covariance: covariance,\n scatter: scatter,\n correlation: correlation,\n zScores: zScores,\n center: center,\n standardize: standardize,\n weightedVariance: weightedVariance,\n weightedMean: weightedMean,\n weightedCovariance: weightedCovariance,\n weightedScatter: weightedScatter\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-savitzky-golay-generalized/~/ml-stat/matrix.js\n// module id = 246\n// module chunks = 0","var NodeSquare = require('./node-square');\n\nfunction NodeHexagonal(x, y, weights, som) {\n\n NodeSquare.call(this, x, y, weights, som);\n\n this.hX = x - Math.floor(y / 2);\n this.z = 0 - this.hX - y;\n\n}\n\nNodeHexagonal.prototype = new NodeSquare;\nNodeHexagonal.prototype.constructor = NodeHexagonal;\n\nNodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) {\n return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z));\n};\n\nNodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.hX - otherNode.hX),\n distY = Math.abs(this.y - otherNode.y),\n distZ = Math.abs(this.z - otherNode.z);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ));\n};\n\nNodeHexagonal.prototype.getPosition = function getPosition() {\n throw new Error('Unimplemented : cannot get position of the points for hexagonal grid');\n};\n\nmodule.exports = NodeHexagonal;\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-som/src/node-hexagonal.js\n// module id = 247\n// module chunks = 0","'use strict';\n\nvar arrayStat = require('./array');\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nexports.max = function max(matrix) {\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return max;\n};\n\nexports.min = function min(matrix) {\n var min = Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n }\n }\n return min;\n};\n\nexports.minMax = function minMax(matrix) {\n var min = Infinity;\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return {\n min:min,\n max:max\n };\n};\n\nexports.entropy = function entropy(matrix, eps) {\n if (typeof (eps) === 'undefined') {\n eps = 0;\n }\n var sum = 0,\n l1 = matrix.length,\n l2 = matrix[0].length;\n for (var i = 0; i < l1; i++) {\n for (var j = 0; j < l2; j++) {\n sum += matrix[i][j] * Math.log(matrix[i][j] + eps);\n }\n }\n return -sum;\n};\n\nexports.mean = function mean(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theMean, N, i, j;\n\n if (dimension === -1) {\n theMean = [0];\n N = rows * cols;\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theMean[0] += matrix[i][j];\n }\n }\n theMean[0] /= N;\n } else if (dimension === 0) {\n theMean = new Array(cols);\n N = rows;\n for (j = 0; j < cols; j++) {\n theMean[j] = 0;\n for (i = 0; i < rows; i++) {\n theMean[j] += matrix[i][j];\n }\n theMean[j] /= N;\n }\n } else if (dimension === 1) {\n theMean = new Array(rows);\n N = cols;\n for (j = 0; j < rows; j++) {\n theMean[j] = 0;\n for (i = 0; i < cols; i++) {\n theMean[j] += matrix[j][i];\n }\n theMean[j] /= N;\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theMean;\n};\n\nexports.sum = function sum(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theSum, i, j;\n\n if (dimension === -1) {\n theSum = [0];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theSum[0] += matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theSum = new Array(cols);\n for (j = 0; j < cols; j++) {\n theSum[j] = 0;\n for (i = 0; i < rows; i++) {\n theSum[j] += matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theSum = new Array(rows);\n for (j = 0; j < rows; j++) {\n theSum[j] = 0;\n for (i = 0; i < cols; i++) {\n theSum[j] += matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theSum;\n};\n\nexports.product = function product(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theProduct, i, j;\n\n if (dimension === -1) {\n theProduct = [1];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theProduct[0] *= matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theProduct = new Array(cols);\n for (j = 0; j < cols; j++) {\n theProduct[j] = 1;\n for (i = 0; i < rows; i++) {\n theProduct[j] *= matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theProduct = new Array(rows);\n for (j = 0; j < rows; j++) {\n theProduct[j] = 1;\n for (i = 0; i < cols; i++) {\n theProduct[j] *= matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theProduct;\n};\n\nexports.standardDeviation = function standardDeviation(matrix, means, unbiased) {\n var vari = exports.variance(matrix, means, unbiased), l = vari.length;\n for (var i = 0; i < l; i++) {\n vari[i] = Math.sqrt(vari[i]);\n }\n return vari;\n};\n\nexports.variance = function variance(matrix, means, unbiased) {\n if (typeof (unbiased) === 'undefined') {\n unbiased = true;\n }\n means = means || exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum1 = 0, sum2 = 0, x = 0;\n for (var i = 0; i < rows; i++) {\n x = matrix[i][j] - means[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1);\n } else {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows;\n }\n }\n return vari;\n};\n\nexports.median = function median(matrix) {\n var rows = matrix.length, cols = matrix[0].length;\n var medians = new Array(cols);\n\n for (var i = 0; i < cols; i++) {\n var data = new Array(rows);\n for (var j = 0; j < rows; j++) {\n data[j] = matrix[j][i];\n }\n data.sort(compareNumbers);\n var N = data.length;\n if (N % 2 === 0) {\n medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5;\n } else {\n medians[i] = data[Math.floor(N / 2)];\n }\n }\n return medians;\n};\n\nexports.mode = function mode(matrix) {\n var rows = matrix.length,\n cols = matrix[0].length,\n modes = new Array(cols),\n i, j;\n for (i = 0; i < cols; i++) {\n var itemCount = new Array(rows);\n for (var k = 0; k < rows; k++) {\n itemCount[k] = 0;\n }\n var itemArray = new Array(rows);\n var count = 0;\n\n for (j = 0; j < rows; j++) {\n var index = itemArray.indexOf(matrix[j][i]);\n if (index >= 0) {\n itemCount[index]++;\n } else {\n itemArray[count] = matrix[j][i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (j = 0; j < count; j++) {\n if (itemCount[j] > maxValue) {\n maxValue = itemCount[j];\n maxIndex = j;\n }\n }\n\n modes[i] = itemArray[maxIndex];\n }\n return modes;\n};\n\nexports.skewness = function skewness(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, l = means.length;\n var skew = new Array(l);\n\n for (var j = 0; j < l; j++) {\n var s2 = 0, s3 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n\n var m2 = s2 / n;\n var m3 = s3 / n;\n var g = m3 / Math.pow(m2, 3 / 2);\n\n if (unbiased) {\n var a = Math.sqrt(n * (n - 1));\n var b = n - 2;\n skew[j] = (a / b) * g;\n } else {\n skew[j] = g;\n }\n }\n return skew;\n};\n\nexports.kurtosis = function kurtosis(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, m = matrix[0].length;\n var kurt = new Array(m);\n\n for (var j = 0; j < m; j++) {\n var s2 = 0, s4 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n kurt[j] = a * b - 3 * c;\n } else {\n kurt[j] = m4 / (m2 * m2) - 3;\n }\n }\n return kurt;\n};\n\nexports.standardError = function standardError(matrix) {\n var samples = matrix.length;\n var standardDeviations = exports.standardDeviation(matrix);\n var l = standardDeviations.length;\n var standardErrors = new Array(l);\n var sqrtN = Math.sqrt(samples);\n\n for (var i = 0; i < l; i++) {\n standardErrors[i] = standardDeviations[i] / sqrtN;\n }\n return standardErrors;\n};\n\nexports.covariance = function covariance(matrix, dimension) {\n return exports.scatter(matrix, undefined, dimension);\n};\n\nexports.scatter = function scatter(matrix, divisor, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n if (typeof (divisor) === 'undefined') {\n if (dimension === 0) {\n divisor = matrix.length - 1;\n } else if (dimension === 1) {\n divisor = matrix[0].length - 1;\n }\n }\n var means = exports.mean(matrix, dimension);\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, s, k;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\nexports.correlation = function correlation(matrix) {\n var means = exports.mean(matrix),\n standardDeviations = exports.standardDeviation(matrix, true, means),\n scores = exports.zScores(matrix, means, standardDeviations),\n rows = matrix.length,\n cols = matrix[0].length,\n i, j;\n\n var cor = new Array(cols);\n for (i = 0; i < cols; i++) {\n cor[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n var c = 0;\n for (var k = 0, l = scores.length; k < l; k++) {\n c += scores[k][j] * scores[k][i];\n }\n c /= rows - 1;\n cor[i][j] = c;\n cor[j][i] = c;\n }\n }\n return cor;\n};\n\nexports.zScores = function zScores(matrix, means, standardDeviations) {\n means = means || exports.mean(matrix);\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means);\n return exports.standardize(exports.center(matrix, means, false), standardDeviations, true);\n};\n\nexports.center = function center(matrix, means, inPlace) {\n means = means || exports.mean(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var row = result[i];\n for (j = 0, jj = row.length; j < jj; j++) {\n row[j] = matrix[i][j] - means[j];\n }\n }\n return result;\n};\n\nexports.standardize = function standardize(matrix, standardDeviations, inPlace) {\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var resultRow = result[i];\n var sourceRow = matrix[i];\n for (j = 0, jj = resultRow.length; j < jj; j++) {\n if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {\n resultRow[j] = sourceRow[j] / standardDeviations[j];\n }\n }\n }\n return result;\n};\n\nexports.weightedVariance = function weightedVariance(matrix, weights) {\n var means = exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum = 0;\n var a = 0, b = 0;\n\n for (var i = 0; i < rows; i++) {\n var z = matrix[i][j] - means[j];\n var w = weights[i];\n\n sum += w * (z * z);\n b += w;\n a += w * w;\n }\n\n vari[j] = sum * (b / (b * b - a));\n }\n\n return vari;\n};\n\nexports.weightedMean = function weightedMean(matrix, weights, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length,\n means, i, ii, j, w, row;\n\n if (dimension === 0) {\n means = new Array(cols);\n for (i = 0; i < cols; i++) {\n means[i] = 0;\n }\n for (i = 0; i < rows; i++) {\n row = matrix[i];\n w = weights[i];\n for (j = 0; j < cols; j++) {\n means[j] += row[j] * w;\n }\n }\n } else if (dimension === 1) {\n means = new Array(rows);\n for (i = 0; i < rows; i++) {\n means[i] = 0;\n }\n for (j = 0; j < rows; j++) {\n row = matrix[j];\n w = weights[j];\n for (i = 0; i < cols; i++) {\n means[j] += row[i] * w;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n var weightSum = arrayStat.sum(weights);\n if (weightSum !== 0) {\n for (i = 0, ii = means.length; i < ii; i++) {\n means[i] /= weightSum;\n }\n }\n return means;\n};\n\nexports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n var s1 = 0, s2 = 0;\n for (var i = 0, ii = weights.length; i < ii; i++) {\n s1 += weights[i];\n s2 += weights[i] * weights[i];\n }\n var factor = s1 / (s1 * s1 - s2);\n return exports.weightedScatter(matrix, weights, means, factor, dimension);\n};\n\nexports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n if (typeof (factor) === 'undefined') {\n factor = 1;\n }\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, k, s;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-stat/matrix.js\n// module id = 248\n// module chunks = 0","\"use strict\";\n\n/**\n * Function that creates the tree\n * @param {Array } X - chemical shifts of the signal\n * @param {Array } Y - intensity of the signal\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {number} minWindow - smallest range to accept in x\n * @param {number} threshold - smallest range to accept in y\n * @returns {{sum: number, center: number, left: {json}, right: {json}}}\n * left and right have the same structure than the parent, or have a\n * undefined value if are leafs\n */\nfunction createTree (X, Y, from, to, minWindow, threshold) {\n minWindow = minWindow || 0.16;\n threshold = threshold || 0.01;\n if ((to - from) < minWindow)\n return undefined;\n var sum = 0;\n for (var i = 0; X[i] < to; i++) {\n if (X[i] > from)\n sum += Y[i];\n }\n if (sum < threshold) {\n return undefined;\n }\n var center = 0;\n for (var j = 0; X[j] < to; j++) {\n if (X[i] > from)\n center += X[j] * Y[j];\n }\n center = center / sum;\n if (((center - from) < 10e-6) || ((to - center) < 10e-6)) return undefined;\n if ((center - from) < (minWindow /4)) {\n return createTree(X, Y, center, to, minWindow, threshold);\n }\n else {\n if ((to - center) < (minWindow / 4)) {\n return createTree(X, Y, from, center, minWindow, threshold);\n }\n else {\n return {\n 'sum': sum,\n 'center': center,\n 'left': createTree(X, Y, from, center, minWindow, threshold),\n 'right': createTree(X, Y, center, to, minWindow, threshold)\n };\n }\n }\n}\n\n/**\n * Similarity between two nodes\n * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node\n * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node\n * @param {number} alpha - weights the relative importance of intensity vs. shift match\n * @param {number} beta - weights the relative importance of node matching and children matching\n * @param {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @returns {number} similarity measure between tree nodes\n */\nfunction S(a, b, alpha, beta, gamma) {\n if (a === undefined || b === undefined) {\n return 0;\n }\n else {\n var C = (alpha*Math.min(a.sum, b.sum)/Math.max(a.sum, b.sum)+ (1-alpha)*Math.exp(-gamma*Math.abs(a.center - b.center)));\n }\n return beta*C + (1-beta)*(S(a.left, b.left, alpha, beta, gamma)+S(a.right, b.right, alpha, beta, gamma));\n}\n\n/**\n * @type {number} alpha - weights the relative importance of intensity vs. shift match\n * @type {number} beta - weights the relative importance of node matching and children matching\n * @type {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @type {number} minWindow - smallest range to accept in x\n * @type {number} threshold - smallest range to accept in y\n */\nvar defaultOptions = {\n minWindow: 0.16,\n threshold : 0.01,\n alpha: 0.1,\n beta: 0.33,\n gamma: 0.001\n};\n\n/**\n * Builds a tree based in the spectra and compares this trees\n * @param {{x: Array, y: Array}} A - first spectra to be compared\n * @param {{x: Array, y: Array}} B - second spectra to be compared\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options\n * @returns {number} similarity measure between the spectra\n */\nfunction tree(A, B, from, to, options) {\n options = options || {};\n for (var o in defaultOptions)\n if (!options.hasOwnProperty(o)) {\n options[o] = defaultOptions[o];\n }\n var Atree, Btree;\n if (A.sum)\n Atree = A;\n else\n Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold);\n if (B.sum)\n Btree = B;\n else\n Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold);\n return S(Atree, Btree, options.alpha, options.beta, options.gamma);\n}\n\nmodule.exports = {\n calc: tree,\n createTree: createTree\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ml-tree-similarity/src/index.js\n// module id = 249\n// module chunks = 0","module.exports = newArray\n\nfunction newArray (n, value) {\n n = n || 0\n var array = new Array(n)\n for (var i = 0; i < n; i++) {\n array[i] = value\n }\n return array\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/new-array/index.js\n// module id = 250\n// module chunks = 0","'use strict';\nmodule.exports = Number.isNaN || function (x) {\n\treturn x !== x;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/number-is-nan/index.js\n// module id = 251\n// module chunks = 0","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/process/browser.js\n// module id = 252\n// module chunks = 0","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/util/~/inherits/inherits_browser.js\n// module id = 253\n// module chunks = 0","module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/util/support/isBufferBrowser.js\n// module id = 254\n// module chunks = 0","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n // Allow for deprecating things in the process of starting up.\n if (isUndefined(global.process)) {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n if (process.noDeprecation === true) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexports.debuglog = function(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/util/util.js\n// module id = 255\n// module chunks = 0","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/global.js\n// module id = 256\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/package.json b/package.json index 599c9be..a461db7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ml", - "version": "2.0.0", + "version": "2.1.0", "description": "Machine learning tools", "main": "src/index.js", "scripts": {