diff --git a/bower.json b/bower.json index c64082a..bf22311 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "ml", - "version": "1.4.0", + "version": "2.0.0", "main": [ "dist/ml.js", "dist/ml.min.js" diff --git a/dist/ml.js b/dist/ml.js index ae8c934..c4d0cd0 100644 --- a/dist/ml.js +++ b/dist/ml.js @@ -21,16 +21,16 @@ return /******/ (function(modules) { // webpackBootstrap /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false +/******/ 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.loaded = true; +/******/ module.l = true; /******/ // Return the exports of the module /******/ return module.exports; @@ -43,17229 +43,18322 @@ return /******/ (function(modules) { // webpackBootstrap /******/ // 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)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; + +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __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__(0); +/******/ return __webpack_require__(__webpack_require__.s = 169); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - // Root packages - exports.ArrayUtils = exports.AU = __webpack_require__(1); - exports.BitArray = __webpack_require__(9); - exports.HashTable = __webpack_require__(11); - exports.Matrix = __webpack_require__(14); - exports.PadArray = __webpack_require__(34); - exports.Regression = __webpack_require__(36); - exports.BinarySearch = __webpack_require__(8); - - - // Math packages - var Math = exports.Math = {}; - - var distance = __webpack_require__(59); - Math.Distance = distance.distance; - Math.Similarity = distance.similarity; - Math.SG = __webpack_require__(114); - Math.SGG = __webpack_require__(116); - Math.Matrix = exports.Matrix; - Math.SparseMatrix = __webpack_require__(120); - Math.BellOptimizer = __webpack_require__(121); - Math.CurveFitting = __webpack_require__(122); - Math.Kernel = __webpack_require__(45); - - - // Statistics packages - var Stat = exports.Stat = {}; - - Stat.array = __webpack_require__(3).array; - Stat.matrix = __webpack_require__(3).matrix; - Stat.PCA = __webpack_require__(125); - Stat.Performance = __webpack_require__(126); - - - // Random number generation - var RNG = exports.RNG = {}; - RNG.XSadd = __webpack_require__(128); - - - // Supervised learning - var SL = exports.SL = {}; - - SL.CV = __webpack_require__(129); - SL.CrossValidation = SL.CV; // Alias - SL.SVM = __webpack_require__(132); - SL.KNN = __webpack_require__(133); - SL.NaiveBayes = __webpack_require__(136); - SL.PLS = __webpack_require__(138); - - - // Clustering - var Clust = exports.Clust = {}; +/***/ (function(module, exports, __webpack_require__) { - Clust.kmeans = __webpack_require__(142); - Clust.hclust = __webpack_require__(144); +"use strict"; - // Neural networks - var NN = exports.NN = exports.nn = {}; +module.exports = __webpack_require__(3).Matrix; +module.exports.Decompositions = module.exports.DC = __webpack_require__(138); - NN.SOM = __webpack_require__(155); - NN.FNN = __webpack_require__(158); - -/***/ }, +/***/ }), /* 1 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = exports = __webpack_require__(2); - exports.getEquallySpacedData = __webpack_require__(6).getEquallySpacedData; - exports.SNV = __webpack_require__(7).SNV; - exports.binarySearch = __webpack_require__(8); +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -/***/ }, -/* 2 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const Stat = __webpack_require__(3).array; - /** - * Function that returns an array of points given 1D array as follows: - * - * [x1, y1, .. , x2, y2, ..] - * - * And receive the number of dimensions of each point. - * @param array - * @param dimensions - * @returns {Array} - Array of points. - */ - function 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); - - 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 pointsArr; - } +function squaredEuclidean(p, q) { + var d = 0; + for (var i = 0; i < p.length; i++) { + d += (p[i] - q[i]) * (p[i] - q[i]); + } + return d; +} - /** - * Function that given an array as follows: - * [x1, y1, .. , x2, y2, ..] - * - * Returns an array as follows: - * [[x1, x2, ..], [y1, y2, ..], [ .. ]] - * - * And receives the number of dimensions of each coordinate. - * @param array - * @param dimensions - * @returns {Array} - Matrix of coordinates - */ - function coordArrayToCoordMatrix(array, dimensions) { - if(array.length % dimensions !== 0) { - throw new RangeError('Dimensions number must be accordance with the size of the array.'); - } - - var coordinatesArray = new Array(dimensions); - var points = array.length / dimensions; - for (var i = 0; i < coordinatesArray.length; i++) { - coordinatesArray[i] = new Array(points); - } - - for(i = 0; i < array.length; i += dimensions) { - for(var j = 0; j < dimensions; ++j) { - var currentPoint = Math.floor(i / dimensions); - coordinatesArray[j][currentPoint] = array[i + j]; - } - } - - return coordinatesArray; - } +function euclidean(p, q) { + return Math.sqrt(squaredEuclidean(p, q)); +} - /** - * Function that receives a coordinate matrix as follows: - * [[x1, x2, ..], [y1, y2, ..], [ .. ]] - * - * Returns an array of coordinates as follows: - * [x1, y1, .. , x2, y2, ..] - * - * @param coordMatrix - * @returns {Array} - */ - function coordMatrixToCoordArray(coordMatrix) { - var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length); - var k = 0; - for(var i = 0; i < coordMatrix[0].length; ++i) { - for(var j = 0; j < coordMatrix.length; ++j) { - coodinatesArray[k] = coordMatrix[j][i]; - ++k; - } - } - - return coodinatesArray; - } +module.exports = euclidean; +euclidean.squared = squaredEuclidean; - /** - * 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); - } - - for (i = 0; i < matrix.length; ++i) { - for(var j = 0; j < matrix[0].length; ++j) { - resultMatrix[j][i] = matrix[i][j]; - } - } - - return resultMatrix; - } - /** - * Function that transform an array of points into a coordinates array - * as follows: - * [x1, y1, .. , x2, y2, ..] - * - * @param points - * @returns {Array} - */ - 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; - } +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Apply the dot product between the smaller vector and a subsets of the - * largest one. - * - * @param firstVector - * @param secondVector - * @returns {Array} each dot product of size of the difference between the - * larger and the smallest one. - */ - function applyDotProduct(firstVector, secondVector) { - var largestVector, smallestVector; - if(firstVector.length <= secondVector.length) { - smallestVector = firstVector; - largestVector = secondVector; - } 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; - } - - return dotProductApplied; - } - /** - * To scale the input array between the specified min and max values. The operation is performed inplace - * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling - * will multiply the input array by min/min(input) or max/max(input) - * @param input - * @param options - * @returns {*} - */ - function scale(input, options){ - var 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; - } - } - } - 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; - } +"use strict"; - module.exports = { - coordArrayToPoints: coordArrayToPoints, - coordArrayToCoordMatrix: coordArrayToCoordMatrix, - coordMatrixToCoordArray: coordMatrixToCoordArray, - coordMatrixToPoints: transpose, - pointsToCoordArray: pointsToCoordArray, - pointsToCoordMatrix: transpose, - applyDotProduct: applyDotProduct, - scale:scale - }; +exports.array = __webpack_require__(14); +exports.matrix = __webpack_require__(160); -/***/ }, +/***/ }), /* 3 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.array = __webpack_require__(4); - exports.matrix = __webpack_require__(5); - - -/***/ }, +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +__webpack_require__(139); +var abstractMatrix = __webpack_require__(37); +var util = __webpack_require__(7); + +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 { + throw new TypeError('First argument must be a positive number or an array'); + } + this.rows = nRows; + this.columns = nColumns; + return this; + } + + set(rowIndex, columnIndex, value) { + this[rowIndex][columnIndex] = value; + return this; + } + + get(rowIndex, columnIndex) { + return this[rowIndex][columnIndex]; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + util.checkRowIndex(this, index, true); + array = util.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) { + util.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; + } + 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; + } +} + +exports.Matrix = Matrix; +Matrix.abstractMatrix = abstractMatrix; + + +/***/ }), /* 4 */ -/***/ function(module, exports) { - - '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; - }; - - -/***/ }, +/***/ (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; + + +/***/ }), /* 5 */ -/***/ function(module, exports, __webpack_require__) { +/***/ (function(module, exports, __webpack_require__) { - 'use strict'; +"use strict"; - var arrayStat = __webpack_require__(4); - function compareNumbers(a, b) { - return a - b; - } +var abstractMatrix = __webpack_require__(37); +var Matrix = __webpack_require__(3); - exports.max = function max(matrix) { - var max = -Infinity; - for (var i = 0; i < matrix.length; i++) { - for (var j = 0; j < matrix[i].length; j++) { - if (matrix[i][j] > max) max = matrix[i][j]; - } - } - return max; - }; - - exports.min = function min(matrix) { - var min = Infinity; - for (var i = 0; i < matrix.length; i++) { - for (var j = 0; j < matrix[i].length; j++) { - if (matrix[i][j] < min) min = matrix[i][j]; - } - } - return min; - }; - - exports.minMax = function minMax(matrix) { - var min = Infinity; - var max = -Infinity; - for (var i = 0; i < matrix.length; i++) { - for (var j = 0; j < matrix[i].length; j++) { - if (matrix[i][j] < min) min = matrix[i][j]; - if (matrix[i][j] > max) max = matrix[i][j]; - } - } - return { - min:min, - max:max - }; - }; - - exports.entropy = function entropy(matrix, eps) { - if (typeof (eps) === 'undefined') { - eps = 0; - } - var sum = 0, - l1 = matrix.length, - l2 = matrix[0].length; - for (var i = 0; i < l1; i++) { - for (var j = 0; j < l2; j++) { - sum += matrix[i][j] * Math.log(matrix[i][j] + eps); - } - } - return -sum; - }; - - exports.mean = function mean(matrix, dimension) { - if (typeof (dimension) === 'undefined') { - dimension = 0; - } - var rows = matrix.length, - cols = matrix[0].length, - theMean, N, i, j; - - if (dimension === -1) { - theMean = [0]; - N = rows * cols; - for (i = 0; i < rows; i++) { - for (j = 0; j < cols; j++) { - theMean[0] += matrix[i][j]; - } - } - theMean[0] /= N; - } else if (dimension === 0) { - theMean = new Array(cols); - N = rows; - for (j = 0; j < cols; j++) { - theMean[j] = 0; - for (i = 0; i < rows; i++) { - theMean[j] += matrix[i][j]; - } - theMean[j] /= N; - } - } else if (dimension === 1) { - theMean = new Array(rows); - N = cols; - for (j = 0; j < rows; j++) { - theMean[j] = 0; - for (i = 0; i < cols; i++) { - theMean[j] += matrix[j][i]; - } - theMean[j] /= N; - } - } else { - throw new Error('Invalid dimension'); - } - return theMean; - }; - - exports.sum = function sum(matrix, dimension) { - if (typeof (dimension) === 'undefined') { - dimension = 0; - } - var rows = matrix.length, - cols = matrix[0].length, - theSum, i, j; - - if (dimension === -1) { - theSum = [0]; - for (i = 0; i < rows; i++) { - for (j = 0; j < cols; j++) { - theSum[0] += matrix[i][j]; - } - } - } else if (dimension === 0) { - theSum = new Array(cols); - for (j = 0; j < cols; j++) { - theSum[j] = 0; - for (i = 0; i < rows; i++) { - theSum[j] += matrix[i][j]; - } - } - } else if (dimension === 1) { - theSum = new Array(rows); - for (j = 0; j < rows; j++) { - theSum[j] = 0; - for (i = 0; i < cols; i++) { - theSum[j] += matrix[j][i]; - } - } - } else { - throw new Error('Invalid dimension'); - } - return theSum; - }; - - exports.product = function product(matrix, dimension) { - if (typeof (dimension) === 'undefined') { - dimension = 0; - } - var rows = matrix.length, - cols = matrix[0].length, - theProduct, i, j; - - if (dimension === -1) { - theProduct = [1]; - for (i = 0; i < rows; i++) { - for (j = 0; j < cols; j++) { - theProduct[0] *= matrix[i][j]; - } - } - } else if (dimension === 0) { - theProduct = new Array(cols); - for (j = 0; j < cols; j++) { - theProduct[j] = 1; - for (i = 0; i < rows; i++) { - theProduct[j] *= matrix[i][j]; - } - } - } else if (dimension === 1) { - theProduct = new Array(rows); - for (j = 0; j < rows; j++) { - theProduct[j] = 1; - for (i = 0; i < cols; i++) { - theProduct[j] *= matrix[j][i]; - } - } - } else { - throw new Error('Invalid dimension'); - } - return theProduct; - }; - - exports.standardDeviation = function standardDeviation(matrix, means, unbiased) { - var vari = exports.variance(matrix, means, unbiased), l = vari.length; - for (var i = 0; i < l; i++) { - vari[i] = Math.sqrt(vari[i]); - } - return vari; - }; - - exports.variance = function variance(matrix, means, unbiased) { - if (typeof (unbiased) === 'undefined') { - unbiased = true; - } - means = means || exports.mean(matrix); - var rows = matrix.length; - if (rows === 0) return []; - var cols = matrix[0].length; - var vari = new Array(cols); - - for (var j = 0; j < cols; j++) { - var sum1 = 0, sum2 = 0, x = 0; - for (var i = 0; i < rows; i++) { - x = matrix[i][j] - means[j]; - sum1 += x; - sum2 += x * x; - } - if (unbiased) { - vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1); - } else { - vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows; - } - } - return vari; - }; - - exports.median = function median(matrix) { - var rows = matrix.length, cols = matrix[0].length; - var medians = new Array(cols); - - for (var i = 0; i < cols; i++) { - var data = new Array(rows); - for (var j = 0; j < rows; j++) { - data[j] = matrix[j][i]; - } - data.sort(compareNumbers); - var N = data.length; - if (N % 2 === 0) { - medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5; - } else { - medians[i] = data[Math.floor(N / 2)]; - } - } - return medians; - }; - - exports.mode = function mode(matrix) { - var rows = matrix.length, - cols = matrix[0].length, - modes = new Array(cols), - i, j; - for (i = 0; i < cols; i++) { - var itemCount = new Array(rows); - for (var k = 0; k < rows; k++) { - itemCount[k] = 0; - } - var itemArray = new Array(rows); - var count = 0; - - for (j = 0; j < rows; j++) { - var index = itemArray.indexOf(matrix[j][i]); - if (index >= 0) { - itemCount[index]++; - } else { - itemArray[count] = matrix[j][i]; - itemCount[count] = 1; - count++; - } - } - - var maxValue = 0, maxIndex = 0; - for (j = 0; j < count; j++) { - if (itemCount[j] > maxValue) { - maxValue = itemCount[j]; - maxIndex = j; - } - } - - modes[i] = itemArray[maxIndex]; - } - return modes; - }; - - exports.skewness = function skewness(matrix, unbiased) { - if (typeof (unbiased) === 'undefined') unbiased = true; - var means = exports.mean(matrix); - var n = matrix.length, l = means.length; - var skew = new Array(l); - - for (var j = 0; j < l; j++) { - var s2 = 0, s3 = 0; - for (var i = 0; i < n; i++) { - var dev = matrix[i][j] - means[j]; - s2 += dev * dev; - s3 += dev * dev * dev; - } - - var m2 = s2 / n; - var m3 = s3 / n; - var g = m3 / Math.pow(m2, 3 / 2); - - if (unbiased) { - var a = Math.sqrt(n * (n - 1)); - var b = n - 2; - skew[j] = (a / b) * g; - } else { - skew[j] = g; - } - } - return skew; - }; - - exports.kurtosis = function kurtosis(matrix, unbiased) { - if (typeof (unbiased) === 'undefined') unbiased = true; - var means = exports.mean(matrix); - var n = matrix.length, m = matrix[0].length; - var kurt = new Array(m); - - for (var j = 0; j < m; j++) { - var s2 = 0, s4 = 0; - for (var i = 0; i < n; i++) { - var dev = matrix[i][j] - means[j]; - s2 += dev * dev; - s4 += dev * dev * dev * dev; - } - var m2 = s2 / n; - var m4 = s4 / n; - - if (unbiased) { - var v = s2 / (n - 1); - var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3)); - var b = s4 / (v * v); - var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3)); - kurt[j] = a * b - 3 * c; - } else { - kurt[j] = m4 / (m2 * m2) - 3; - } - } - return kurt; - }; - - exports.standardError = function standardError(matrix) { - var samples = matrix.length; - var standardDeviations = exports.standardDeviation(matrix); - var l = standardDeviations.length; - var standardErrors = new Array(l); - var sqrtN = Math.sqrt(samples); - - for (var i = 0; i < l; i++) { - standardErrors[i] = standardDeviations[i] / sqrtN; - } - return standardErrors; - }; - - exports.covariance = function covariance(matrix, dimension) { - return exports.scatter(matrix, undefined, dimension); - }; - - exports.scatter = function scatter(matrix, divisor, dimension) { - if (typeof (dimension) === 'undefined') { - dimension = 0; - } - if (typeof (divisor) === 'undefined') { - if (dimension === 0) { - divisor = matrix.length - 1; - } else if (dimension === 1) { - divisor = matrix[0].length - 1; - } - } - var means = exports.mean(matrix, dimension); - var rows = matrix.length; - if (rows === 0) { - return [[]]; - } - var cols = matrix[0].length, - cov, i, j, s, k; - - if (dimension === 0) { - cov = new Array(cols); - for (i = 0; i < cols; i++) { - cov[i] = new Array(cols); - } - for (i = 0; i < cols; i++) { - for (j = i; j < cols; j++) { - s = 0; - for (k = 0; k < rows; k++) { - s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); - } - s /= divisor; - cov[i][j] = s; - cov[j][i] = s; - } - } - } else if (dimension === 1) { - cov = new Array(rows); - for (i = 0; i < rows; i++) { - cov[i] = new Array(rows); - } - for (i = 0; i < rows; i++) { - for (j = i; j < rows; j++) { - s = 0; - for (k = 0; k < cols; k++) { - s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); - } - s /= divisor; - cov[i][j] = s; - cov[j][i] = s; - } - } - } else { - throw new Error('Invalid dimension'); - } - - return cov; - }; - - exports.correlation = function correlation(matrix) { - var means = exports.mean(matrix), - standardDeviations = exports.standardDeviation(matrix, true, means), - scores = exports.zScores(matrix, means, standardDeviations), - rows = matrix.length, - cols = matrix[0].length, - i, j; - - var cor = new Array(cols); - for (i = 0; i < cols; i++) { - cor[i] = new Array(cols); - } - for (i = 0; i < cols; i++) { - for (j = i; j < cols; j++) { - var c = 0; - for (var k = 0, l = scores.length; k < l; k++) { - c += scores[k][j] * scores[k][i]; - } - c /= rows - 1; - cor[i][j] = c; - cor[j][i] = c; - } - } - return cor; - }; - - exports.zScores = function zScores(matrix, means, standardDeviations) { - means = means || exports.mean(matrix); - if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means); - return exports.standardize(exports.center(matrix, means, false), standardDeviations, true); - }; - - exports.center = function center(matrix, means, inPlace) { - means = means || exports.mean(matrix); - var result = matrix, - l = matrix.length, - i, j, jj; - - if (!inPlace) { - result = new Array(l); - for (i = 0; i < l; i++) { - result[i] = new Array(matrix[i].length); - } - } - - for (i = 0; i < l; i++) { - var row = result[i]; - for (j = 0, jj = row.length; j < jj; j++) { - row[j] = matrix[i][j] - means[j]; - } - } - return result; - }; - - exports.standardize = function standardize(matrix, standardDeviations, inPlace) { - if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix); - var result = matrix, - l = matrix.length, - i, j, jj; - - if (!inPlace) { - result = new Array(l); - for (i = 0; i < l; i++) { - result[i] = new Array(matrix[i].length); - } - } - - for (i = 0; i < l; i++) { - var resultRow = result[i]; - var sourceRow = matrix[i]; - for (j = 0, jj = resultRow.length; j < jj; j++) { - if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) { - resultRow[j] = sourceRow[j] / standardDeviations[j]; - } - } - } - return result; - }; - - exports.weightedVariance = function weightedVariance(matrix, weights) { - var means = exports.mean(matrix); - var rows = matrix.length; - if (rows === 0) return []; - var cols = matrix[0].length; - var vari = new Array(cols); - - for (var j = 0; j < cols; j++) { - var sum = 0; - var a = 0, b = 0; - - for (var i = 0; i < rows; i++) { - var z = matrix[i][j] - means[j]; - var w = weights[i]; - - sum += w * (z * z); - b += w; - a += w * w; - } - - vari[j] = sum * (b / (b * b - a)); - } - - return vari; - }; - - exports.weightedMean = function weightedMean(matrix, weights, dimension) { - if (typeof (dimension) === 'undefined') { - dimension = 0; - } - var rows = matrix.length; - if (rows === 0) return []; - var cols = matrix[0].length, - means, i, ii, j, w, row; - - if (dimension === 0) { - means = new Array(cols); - for (i = 0; i < cols; i++) { - means[i] = 0; - } - for (i = 0; i < rows; i++) { - row = matrix[i]; - w = weights[i]; - for (j = 0; j < cols; j++) { - means[j] += row[j] * w; - } - } - } else if (dimension === 1) { - means = new Array(rows); - for (i = 0; i < rows; i++) { - means[i] = 0; - } - for (j = 0; j < rows; j++) { - row = matrix[j]; - w = weights[j]; - for (i = 0; i < cols; i++) { - means[j] += row[i] * w; - } - } - } else { - throw new Error('Invalid dimension'); - } - - var weightSum = arrayStat.sum(weights); - if (weightSum !== 0) { - for (i = 0, ii = means.length; i < ii; i++) { - means[i] /= weightSum; - } - } - return means; - }; - - exports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) { - dimension = dimension || 0; - means = means || exports.weightedMean(matrix, weights, dimension); - var s1 = 0, s2 = 0; - for (var i = 0, ii = weights.length; i < ii; i++) { - s1 += weights[i]; - s2 += weights[i] * weights[i]; - } - var factor = s1 / (s1 * s1 - s2); - return exports.weightedScatter(matrix, weights, means, factor, dimension); - }; - - exports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) { - dimension = dimension || 0; - means = means || exports.weightedMean(matrix, weights, dimension); - if (typeof (factor) === 'undefined') { - factor = 1; - } - var rows = matrix.length; - if (rows === 0) { - return [[]]; - } - var cols = matrix[0].length, - cov, i, j, k, s; - - if (dimension === 0) { - cov = new Array(cols); - for (i = 0; i < cols; i++) { - cov[i] = new Array(cols); - } - for (i = 0; i < cols; i++) { - for (j = i; j < cols; j++) { - s = 0; - for (k = 0; k < rows; k++) { - s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); - } - cov[i][j] = s * factor; - cov[j][i] = s * factor; - } - } - } else if (dimension === 1) { - cov = new Array(rows); - for (i = 0; i < rows; i++) { - cov[i] = new Array(rows); - } - for (i = 0; i < rows; i++) { - for (j = i; j < rows; j++) { - s = 0; - for (k = 0; k < cols; k++) { - s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); - } - cov[i][j] = s * factor; - cov[j][i] = s * factor; - } - } - } else { - throw new Error('Invalid dimension'); - } - - return cov; - }; - - -/***/ }, -/* 6 */ -/***/ function(module, exports) { - - 'use strict'; - - /** - * - * Function that returns a Number array of equally spaced numberOfPoints - * containing a representation of intensities of the spectra arguments x - * and y. - * - * The options parameter contains an object in the following form: - * from: starting point - * to: last point - * numberOfPoints: number of points between from and to - * variant: "slot" or "smooth" - smooth is the default option - * - * The slot variant consist that each point in the new array is calculated - * averaging the existing points between the slot that belongs to the current - * value. The smooth variant is the same but takes the integral of the range - * of the slot and divide by the step size between two points in the new array. - * - * @param x - sorted increasing x values - * @param y - * @param options - * @returns {Array} new array with the equally spaced data. - * - */ - function getEquallySpacedData(x, y, options) { - if (x.length>1 && x[0]>x[1]) { - x=x.slice().reverse(); - y=y.slice().reverse(); - } - - 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"); - } - - var reverse = from > to; - if(reverse) { - var temp = from; - from = to; - to = temp; - } - - 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; - } +class BaseView extends abstractMatrix() { + constructor(matrix, rows, columns) { + super(); + this.matrix = matrix; + this.rows = rows; + this.columns = columns; + } - /** - * function that retrieves the getEquallySpacedData with the variant "smooth" - * - * @param x - * @param y - * @param from - Initial point - * @param to - Final point - * @param numberOfPoints - * @returns {Array} - Array of y's equally spaced with the variant "smooth" - */ - function getEquallySpacedSmooth(x, y, from, to, numberOfPoints) { - var xLength = x.length; - - var step = (to - from) / (numberOfPoints - 1); - var halfStep = step / 2; - - var start = from - halfStep; - var output = new Array(numberOfPoints); - - var initialOriginalStep = x[1] - x[0]; - var lastOriginalStep = x[x.length - 1] - x[x.length - 2]; - - // Init main variables - var min = start; - var max = start + step; - - var previousX = Number.MIN_VALUE; - var previousY = 0; - var nextX = x[0] - initialOriginalStep; - var nextY = 0; - - var currentValue = 0; - var slope = 0; - var intercept = 0; - var sumAtMin = 0; - var sumAtMax = 0; - - var i = 0; // index of input - var j = 0; // index of output - - function getSlope(x0, y0, x1, y1) { - return (y1 - y0) / (x1 - x0); - } - - 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; - - output[j] = (sumAtMax - sumAtMin) / step; - j++; - - if (j === numberOfPoints) - break main; - - min = max; - max += step; - sumAtMin = sumAtMax; - } - - if(previousX <= min && min <= nextX) { - add = integral(0, min - previousX, slope, previousY); - sumAtMin = currentValue + add; - } - - currentValue += integral(previousX, nextX, slope, intercept); - - previousX = nextX; - previousY = nextY; - - 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; - } - - return output; - } + static get [Symbol.species]() { + return Matrix.Matrix; + } +} - /** - * 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 step = (to - from) / (numberOfPoints - 1); - var halfStep = step / 2; - var lastStep = x[x.length - 1] - x[x.length - 2]; - - var start = from - halfStep; - var output = new Array(numberOfPoints); - - // Init main variables - var min = start; - var max = start + step; - - var previousX = -Number.MAX_VALUE; - var previousY = 0; - var nextX = x[0]; - var nextY = y[0]; - var frontOutsideSpectra = 0; - var backOutsideSpectra = true; - - var currentValue = 0; - - // for slot algorithm - var currentPoints = 0; - - var i = 1; // index of input - var j = 0; // index of output - - main: while(true) { - if (previousX>=nextX) throw (new Error('x must be an increasing serie')); - while (previousX - max > 0) { - // no overlap with original point, just consume current value - if(backOutsideSpectra) { - currentPoints++; - backOutsideSpectra = false; - } - - output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints; - j++; - - if (j === numberOfPoints) - break main; - - min = max; - max += step; - currentValue = 0; - currentPoints = 0; - } - - if(previousX > min) { - currentValue += previousY; - currentPoints++; - } - - if(previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) - currentPoints--; - - previousX = nextX; - previousY = nextY; - - if (i < xLength) { - nextX = x[i]; - nextY = y[i]; - i++; - } else { - nextX += lastStep; - nextY = 0; - frontOutsideSpectra++; - } - } - - 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); - } +module.exports = BaseView; - exports.getEquallySpacedData = getEquallySpacedData; - exports.integral = integral; -/***/ }, +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"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(); + } + } +}; + + +/***/ }), /* 7 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.SNV = SNV; - var Stat = __webpack_require__(3).array; - - /** - * Function that applies the standard normal variate (SNV) to an array of values. - * - * @param data - Array of values. - * @returns {Array} - applied the SNV. - */ - 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; - } - - -/***/ }, +/***/ (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'); + } +}; + +/** + * @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'); + } +}; + +/** + * @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'); + } + 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'); + } + return vector; +}; + +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; + }); + + 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 + }; +}; + +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'); + } +}; + +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.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; +}; + +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; +}; + +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 v; +}; + + +/***/ }), /* 8 */ -/***/ function(module, exports) { - - /** - * Performs a binary search of value in array - * @param {number[]} array - Array in which value will be searched. It must be sorted. - * @param {number} value - Value to search in array - * @return {number} If value is found, returns its index in array. Otherwise, returns a negative number indicating where the value should be inserted: -(index + 1) - */ - function binarySearch(array, value, options) { - options = options || {}; - var low = options.from || 0; - var high = options.to || array.length - 1; - - while (low <= high) { - var mid = (low + high) >>> 1; - var midValue = array[mid]; - if (midValue < value) { - low = mid + 1; - } else if (midValue > value) { - high = mid - 1; - } else { - return mid; - } - } - - return -(low + 1); - } +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +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); + +const kernelType = { + gaussian: GaussianKernel, + rbf: GaussianKernel, + polynomial: PolynomialKernel, + poly: PolynomialKernel, + anova: ANOVAKernel, + cauchy: CauchyKernel, + exponential: ExponentialKernel, + histogram: HistogramKernel, + min: HistogramKernel, + laplacian: LaplacianKernel, + multiquadratic: MultiquadraticKernel, + rational: RationalKernel, + sigmoid: SigmoidKernel, + mlp: SigmoidKernel +}; + +class Kernel { + constructor(type, options) { + this.kernelType = type; + if (type === 'linear') return; + + if (typeof type === 'string') { + type = type.toLowerCase(); + + var KernelConstructor = kernelType[type]; + if (KernelConstructor) { + this.kernelFunction = new KernelConstructor(options); + } else { + throw new Error('unsupported kernel type: ' + type); + } + } else if (typeof type === 'object' && typeof type.compute === 'function') { + this.kernelFunction = type; + } else { + throw new TypeError('first argument must be a valid kernel type or instance'); + } + } + + compute(inputs, landmarks) { + if (landmarks === undefined) { + landmarks = inputs; + } + + if (this.kernelType === 'linear') { + var matrix = new Matrix(inputs); + return matrix.mmul(new Matrix(landmarks).transpose()); + } + + 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; + } +} + +module.exports = Kernel; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { - module.exports = binarySearch; +"use strict"; -/***/ }, -/* 9 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var eightBits = __webpack_require__(10); - - /** - * 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; - } +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; - /** - * 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; +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); } - /** - * 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; - } + return toStr.call(arr) === '[object Array]'; +}; - /** - * 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; +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; } - /** - * 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; + 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; } - /** - * 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); + // 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 = {}; } - /** - * 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; - } + 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]; + + // 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 : {}; + } - /** - * 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; - } + // Never move original objects, clone them + target[name] = extend(deep, clone, copy); - /** - * 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; + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + target[name] = copy; + } + } + } + } } - /** - * 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; - } + // Return the modified object + return target; +}; - /** - * 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 - }; - - -/***/ }, +/***/ }), /* 10 */ -/***/ function(module, exports) { - - // auxiliary file to create the 256 look at table elements - - var ans = new Array(256); - for (var i = 0; i < 256; i++) { - var num = i; - var c = 0; - while (num) { - num = num & (num - 1); - c++; - } - ans[i] = c; - } - - module.exports = ans; - -/***/ }, +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +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); + } + 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)); + } + + var root = new Cluster(); + root.children = heap.toArray(); + root.distance = this.distance; + + return root; +}; + +module.exports = Cluster; + + +/***/ }), /* 11 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const newArray = __webpack_require__(12); - - const primeFinder = __webpack_require__(13); - 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)); - } - - -/***/ }, +/***/ (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; +}; + + +/***/ }), /* 12 */ -/***/ function(module, exports) { - - module.exports = newArray - - function newArray (n, value) { - n = n || 0 - var array = new Array(n) - for (var i = 0; i < n; i++) { - array[i] = value - } - return array - } +/***/ (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 +}; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var maybeToPrecision = __webpack_require__(6).maybeToPrecision; +const BaseRegression = __webpack_require__(4); + + +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; + + var xSquared = 0; + var xY = 0; + + 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); + + + 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); + } + } + + } + + toJSON() { + var out = { + name: 'simpleLinearRegression', + slope: this.slope, + intercept: this.intercept + }; + if (this.quality) { + out.quality = this.quality; + } + + 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 { + result += 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); + } +} + +module.exports = SimpleLinearRegression; + + +/***/ }), +/* 14 */ +/***/ (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; +}; + + +/***/ }), +/* 15 */ +/***/ (function(module, exports) { +module.exports = function(haystack, needle, comparator, low, high) { + var mid, cmp; -/***/ }, -/* 13 */ -/***/ function(module, exports, __webpack_require__) { - - const binarySearch = __webpack_require__(8); - - const largestPrime = 0x7fffffff; - - const primeNumbers = [ - //chunk #0 - largestPrime, // 2^31-1 - - //chunk #1 - 5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759, - 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939, - 210719881, 421439783, 842879579, 1685759167, - - //chunk #2 - 433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107, - 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699, - 1854585413, - - //chunk #3 - 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341, - 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963, - 2004663929, - - //chunk #4 - 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963, - 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463, - - //chunk #5 - 31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953, - 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013, - 587742049, 1175484103, - - //chunk #6 - 599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729, - 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683, - - //chunk #7 - 311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867, - 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673, - 1344393353, - - //chunk #8 - 3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, - 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, - 359339171, 718678369, 1437356741, - - //chunk #9 - 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337, - 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741, - 759155483, 1518310967, - - //chunk #10 - 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611, - 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929, - 1600153859, - - //chunk #11 - 13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683, - 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407, - 276172823, 552345671, 1104691373, - - //chunk #12 - 19, 41, 83, 167, 337, 677, - 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, - 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, - 359339171, 718678369, 1437356741, - - //chunk #13 - 53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269, - 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781, - 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943 - ]; - - primeNumbers.sort((a, b) => a - b); - - function nextPrime(value) { - let index = binarySearch(primeNumbers, value); - if (index < 0) { - index = -index - 1; - } - return primeNumbers[index]; - } + if(low === undefined) + low = 0; - exports.nextPrime = nextPrime; - exports.largestPrime = largestPrime; + else { + low = low|0; + if(low < 0 || low >= haystack.length) + throw new RangeError("invalid lower bound"); + } + if(high === undefined) + high = haystack.length - 1; -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { + else { + high = high|0; + if(high < low || high >= haystack.length) + throw new RangeError("invalid upper bound"); + } - 'use strict'; + 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); - module.exports = __webpack_require__(15); - module.exports.Decompositions = module.exports.DC = __webpack_require__(27); + /* Too low. */ + if(cmp < 0.0) + low = mid + 1; + /* Too high. */ + else if(cmp > 0.0) + high = mid - 1; -/***/ }, -/* 15 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - __webpack_require__(16); - var abstractMatrix = __webpack_require__(17); - var util = __webpack_require__(18); - - class Matrix extends abstractMatrix(Array) { - constructor(nRows, nColumns) { - 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 (var 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 - var matrix = nRows; - nRows = matrix.length; - nColumns = matrix[0].length; - if (typeof nColumns !== 'number' || nColumns === 0) { - throw new TypeError('Data must be a 2D array with at least one element'); - } - super(nRows); - for (var 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; - } - - 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 - * @returns {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; - } - - /** - * Removes a row from the given index - * @param {number} index - Row index - * @returns {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; - } - - /** - * Adds a row at the given index - * @param {number} [index = this.rows] - Row index - * @param {Array|Matrix} array - Array or vector - * @returns {Matrix} this - */ - addRow(index, array) { - if (array === undefined) { - array = index; - index = this.rows; - } - util.checkRowIndex(this, index, true); - array = util.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 - * @returns {Matrix} this - */ - removeColumn(index) { - util.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 - * @returns {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; - } - } + /* Key found. */ + else + return mid; + } - module.exports = Matrix; - Matrix.abstractMatrix = abstractMatrix; + /* Key not found. */ + return ~low; +} -/***/ }, +/***/ }), /* 16 */ -/***/ function(module, exports) { +/***/ (function(module, exports, __webpack_require__) { - 'use strict'; +module.exports = exports = __webpack_require__(65); - if (!Symbol.species) { - Symbol.species = Symbol.for('@@species'); - } +exports.getEquallySpacedData = __webpack_require__(66).getEquallySpacedData; +exports.SNV = __webpack_require__(67).SNV; -/***/ }, -/* 17 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - module.exports = abstractMatrix; - - var arrayUtils = __webpack_require__(1); - var util = __webpack_require__(18); - var MatrixTransposeView = __webpack_require__(19); - var MatrixRowView = __webpack_require__(21); - var MatrixSubView = __webpack_require__(22); - var MatrixSelectionView = __webpack_require__(23); - var MatrixColumnView = __webpack_require__(24); - var MatrixFlipRowView = __webpack_require__(25); - var MatrixFlipColumnView = __webpack_require__(26); - - 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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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] - Random number generator (default: Math.random) - * @returns {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 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] - Number of columns (Default: rows) - * @returns {Matrix} - The new identity matrix - */ - static eye(rows, columns) { - if (columns === undefined) columns = rows; - var min = Math.min(rows, columns); - var matrix = this.zeros(rows, columns); - for (var i = 0; i < min; i++) { - matrix.set(i, i, 1); - } - 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) - * @returns {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 matrix1 - * @param matrix2 - * @returns {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 matrix1 - * @param matrix2 - * @returns {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 - * @returns {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'); - } - - /** - * @property {number} - 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) - * @returns {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 - * @returns {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 - * @returns {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; - } - - /** - * @returns {boolean} true if the matrix has one row - */ - isRowVector() { - return this.rows === 1; - } - - /** - * @returns {boolean} true if the matrix has one column - */ - isColumnVector() { - return this.columns === 1; - } - - /** - * @returns {boolean} true if the matrix has one row or one column - */ - isVector() { - return (this.rows === 1) || (this.columns === 1); - } - - /** - * @returns {boolean} true if the matrix has the same number of rows and columns - */ - isSquare() { - return this.rows === this.columns; - } - - /** - * @returns {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 - * @param {number} rowIndex - Index of the row - * @param {number} columnIndex - Index of the column - * @param {number} value - The new value for the element - * @returns {Matrix} this - */ - set(rowIndex, columnIndex, value) { - throw new Error('set method is unimplemented'); - } - - /** - * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4] - * @param {number} rowIndex - Index of the row - * @param {number} columnIndex - Index of the column - * @returns {number} - */ - get(rowIndex, columnIndex) { - 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 - * @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 - * @returns {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) - * @returns {Matrix} this - */ - neg() { - return this.mulS(-1); - } - - /** - * Returns a new array from the given row index - * @param {number} index - Row index - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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); - } - } - - /** - * Returns the maximum value of the matrix - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 of all elements of the matrix - * @returns {number} - */ - sum() { - var v = 0; - for (var i = 0; i < this.rows; i++) { - for (var j = 0; j < this.columns; j++) { - v += this.get(i, j); - } - } - return v; - } - - /** - * Returns the mean of all elements of the matrix - * @returns {number} - */ - mean() { - return this.sum() / this.size; - } - - /** - * Returns the product of all elements of the matrix - * @returns {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) - * @returns {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 - * @returns {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 - * @returns {Matrix} - */ - mmul(other) { - other = this.constructor.checkMatrix(other); - if (this.columns !== other.rows) - 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; - } - - /** - * Returns a row-by-row scaled matrix - * @param {Number} [min=0] - Minimum scaled value - * @param {Number} [max=1] - Maximum scaled value - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 - * @returns {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 startRow - The index of the first row to set - * @param startColumn - The index of the first column to set - * @returns {Matrix} - */ - setSubMatrix(matrix, startRow, startColumn) { - matrix = this.constructor.checkMatrix(matrix); - var endRow = startRow + matrix.rows - 1; - var endColumn = startColumn + matrix.columns - 1; - if ((startRow > endRow) || (startColumn > endColumn) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) { - throw new RangeError('Argument out of range'); - } - 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. - * @returns {Matrix} The new matrix - */ - selection(rowIndices, columnIndices) { - var indices = util.checkIndices(this, rowIndices, columnIndices); - var newMatrix = new this.constructor(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) - * @returns {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 - */ - transposeView() { - return new MatrixTransposeView(this); - } - - rowView(row) { - util.checkRowIndex(this, row); - return new MatrixRowView(this, row); - } - - columnView(column) { - util.checkColumnIndex(this, column); - return new MatrixColumnView(this, column); - } - - flipRowView() { - return new MatrixFlipRowView(this); - } - - flipColumnView() { - return new MatrixFlipColumnView(this); - } - - subMatrixView(startRow, endRow, startColumn, endColumn) { - return new MatrixSubView(this, startRow, endRow, startColumn, endColumn); - } - - selectionView(rowIndices, columnIndices) { - return new MatrixSelectionView(this, rowIndices, columnIndices); - } - } - - Matrix.prototype.klass = 'Matrix'; - - /** - * @private - * Check that two matrices have the same dimensions - * @param {Matrix} matrix - * @param {Matrix} otherMatrix - */ - function checkDimensions(matrix, otherMatrix) { - 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; - - /* - 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(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(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(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'] - ]; - - 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 (var 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 (var 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 (var 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 (var 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 inplaceMethod = eval(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar)); - var inplaceMethodS = eval(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar)); - var inplaceMethodM = eval(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar)); - var staticMethod = eval(fillTemplateFunction(staticMethodWithOneArg, tmplVar)); - for (var i = 2; i < methodWithArg.length; i++) { - Matrix.prototype[methodWithArg[i]] = inplaceMethod; - Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM; - Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS; - Matrix[methodWithArg[i]] = staticMethod; - } - } - } - - function fillTemplateFunction(template, values) { - for (var i in values) { - template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]); - } - return template; - } - - return Matrix; - } +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { -/***/ }, -/* 18 */ -/***/ function(module, exports) { - - 'use strict'; - - /** - * @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'); - } - }; - - /** - * @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'); - } - }; - - /** - * @private - * Check that the provided vector is an array with the right length - * @param {Matrix} matrix - * @param {Array|Matrix} vector - * @returns {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'); - } - return vector; - }; - - /** - * @private - * Check that the provided vector is an array with the right length - * @param {Matrix} matrix - * @param {Array|Matrix} vector - * @returns {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'); - } - return vector; - }; - - 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; - }); - - 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 - }; - }; - - 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'); - } - }; - - 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; - }; - - -/***/ }, -/* 19 */ -/***/ function(module, exports, __webpack_require__) { +"use strict"; - 'use strict'; - var BaseView = __webpack_require__(20); +module.exports = __webpack_require__(71); +module.exports.Matrix = __webpack_require__(0); +module.exports.Matrix.algebra = __webpack_require__(22); - class MatrixTransposeView extends BaseView { - constructor(matrix) { - super(matrix, matrix.columns, matrix.rows); - } - set(rowIndex, columnIndex, value) { - this.matrix.set(columnIndex, rowIndex, value); - return this; - } +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { - get(rowIndex, columnIndex) { - return this.matrix.get(columnIndex, rowIndex); - } - } +"use strict"; - module.exports = MatrixTransposeView; +exports.distance = __webpack_require__(72); +exports.similarity = __webpack_require__(108); -/***/ }, +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const newArray = __webpack_require__(162); + +const primeFinder = __webpack_require__(117); +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)); +} + + +/***/ }), /* 20 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var abstractMatrix = __webpack_require__(17); - var Matrix; - - class BaseView extends abstractMatrix() { - constructor(matrix, rows, columns) { - super(); - this.matrix = matrix; - this.rows = rows; - this.columns = columns; - } - - static get [Symbol.species]() { - if (!Matrix) { - Matrix = __webpack_require__(15); - } - return Matrix; - } - } - - module.exports = BaseView; - - -/***/ }, +/***/ (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]; + } + } + + // 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; + + +/***/ }), /* 21 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; +/***/ (function(module, exports, __webpack_require__) { - var BaseView = __webpack_require__(20); +"use strict"; - class MatrixRowView extends BaseView { - constructor(matrix, row) { - super(matrix, 1, matrix.columns); - this.row = row; - } +var numberIsNan = __webpack_require__(163); - set(rowIndex, columnIndex, value) { - this.matrix.set(this.row, columnIndex, value); - return this; - } - - get(rowIndex, columnIndex) { - return this.matrix.get(this.row, columnIndex); - } +function assertNum(x) { + if (typeof x !== 'number' || numberIsNan(x)) { + throw new TypeError('Expected a number'); } +} - module.exports = MatrixRowView; - - -/***/ }, -/* 22 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var BaseView = __webpack_require__(20); - var util = __webpack_require__(18); - - 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; - } - - set(rowIndex, columnIndex, value) { - this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex , value); - return this; - } +exports.asc = function (a, b) { + assertNum(a); + assertNum(b); + return a - b; +}; - get(rowIndex, columnIndex) { - return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); - } - } - - module.exports = MatrixSubView; +exports.desc = function (a, b) { + assertNum(a); + assertNum(b); + return b - a; +}; -/***/ }, +/***/ }), +/* 22 */ +/***/ (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 +}; + + +/***/ }), /* 23 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var BaseView = __webpack_require__(20); - var util = __webpack_require__(18); - - 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; - } - - 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]); - } - } - - module.exports = MatrixSelectionView; - - -/***/ }, +/***/ (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); +}; + + +/***/ }), /* 24 */ -/***/ function(module, exports, __webpack_require__) { +/***/ (function(module, exports) { - 'use strict'; +module.exports = function intersection(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii ; i++) { + ans += Math.min(a[i], b[i]); + } + return 1 - ans; +}; - var BaseView = __webpack_require__(20); - class MatrixColumnView extends BaseView { - constructor(matrix, column) { - super(matrix, matrix.rows, 1); - this.column = column; - } - - set(rowIndex, columnIndex, value) { - this.matrix.set(rowIndex, this.column, value); - return this; - } - - get(rowIndex, columnIndex) { - return this.matrix.get(rowIndex, this.column); - } - } - - module.exports = MatrixColumnView; - - -/***/ }, +/***/ }), /* 25 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; +/***/ (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); +}; + + +/***/ }), +/* 26 */ +/***/ (function(module, exports) { - var BaseView = __webpack_require__(20); +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; +}; - class MatrixFlipRowView extends BaseView { - constructor(matrix) { - super(matrix, matrix.rows, matrix.columns); - } - set(rowIndex, columnIndex, value) { - this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); - return this; - } +/***/ }), +/* 27 */ +/***/ (function(module, exports) { - get(rowIndex, columnIndex) { - return this.matrix.get(this.rows - rowIndex - 1, columnIndex); - } - } +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); +}; - module.exports = MatrixFlipRowView; +/***/ }), +/* 28 */ +/***/ (function(module, exports) { -/***/ }, -/* 26 */ -/***/ function(module, exports, __webpack_require__) { +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; +}; - 'use strict'; - var BaseView = __webpack_require__(20); +/***/ }), +/* 29 */ +/***/ (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)); +}; + + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { - class MatrixFlipColumnView extends BaseView { - constructor(matrix) { - super(matrix, matrix.rows, matrix.columns); - } +"use strict"; - 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); - } - } +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; +}; - module.exports = MatrixFlipColumnView; +/***/ }), +/* 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]; + } + 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); + } +}; + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Matrix = __webpack_require__(0); + +var Utils = __webpack_require__(34); +const ACTIVATION_FUNCTIONS = __webpack_require__(33); + +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; + + +/***/ }), +/* 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; + } + 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; + + +/***/ }), +/* 34 */ +/***/ (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 +}; + + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { -/***/ }, -/* 27 */ -/***/ function(module, exports, __webpack_require__) { +"use strict"; - 'use strict'; - var Matrix = __webpack_require__(15); +var Cluster = __webpack_require__(10); +var util = __webpack_require__(167); - var SingularValueDecomposition = __webpack_require__(28); - var EigenvalueDecomposition = __webpack_require__(30); - var LuDecomposition = __webpack_require__(31); - var QrDecomposition = __webpack_require__(32); - var CholeskyDecomposition = __webpack_require__(33); +function ClusterLeaf (index) { + Cluster.call(this); + this.index = index; + this.distance = 0; + this.children = []; +} - function inverse(matrix) { - matrix = Matrix.checkMatrix(matrix); - return solve(matrix, Matrix.eye(matrix.rows)); - } +util.inherits(ClusterLeaf, Cluster); - Matrix.inverse = Matrix.inv = inverse; - Matrix.prototype.inverse = Matrix.prototype.inv = function () { - return inverse(this); - }; +module.exports = ClusterLeaf; - 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); - } - Matrix.solve = solve; - Matrix.prototype.solve = function (other) { - return solve(this, other); - }; - - 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 - }; - - -/***/ }, -/* 28 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Matrix = __webpack_require__(15); - var util = __webpack_require__(29); - 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.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(); - 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] = -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; - } - } - } - - if (swapped) { - var tmp = V; - V = U; - U = tmp; - } - - this.m = m; - this.n = n; - this.s = s; - this.U = U; - this.V = V; - } +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const nearestVector = __webpack_require__(147); + +/** + * 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; + + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = abstractMatrix; + +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); + +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.'); + } + } + } + + 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; +} + + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var 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 = 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; + + +/***/ }), +/* 39 */ +/***/ (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; +} + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * 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. + */ + +const maybeToPrecision = __webpack_require__(6).maybeToPrecision; +const BaseRegression = __webpack_require__(4); +const Matrix = __webpack_require__(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'); + } + + 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]); + } + } + } + + var FT = F.transposeView(); + var A = FT.mmul(F); + var B = FT.mmul(Y.transposeView()); + + this.coefficients = A.solve(B).to1DArray(); + this.powers = powers; + this.M = M - 1; + if (opt.computeQuality) { + this.quality = this.modelQuality(x, y); + } + } + } + + _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; + } + + toJSON() { + var out = {name: 'polynomialRegression', + coefficients: this.coefficients, + powers: this.powers, + M: this.M + }; + + if (this.quality) { + out.quality = this.quality; + } + return out; + } + + toString(precision) { + return this._toFormula(precision, false); + } + + toLaTeX(precision) { + return this._toFormula(precision, true); + } + + _toFormula(precision, isLaTeX) { + var sup = '^'; + var closeSup = ''; + var times = ' * '; + if (isLaTeX) { + sup = '^{'; + closeSup = '}'; + times = ''; + } + + 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; + } + } + + 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); + } +} + +module.exports = PolynomialRegression; + + +/***/ }), +/* 41 */ +/***/ (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; +}; + + +/***/ }), +/* 42 */ +/***/ (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; + +/***/ }), +/* 43 */ +/***/ (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} + */ +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 +}; + + +/***/ }), +/* 44 */ +/***/ (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 + */ +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; + + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { - 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]; - } - } - - var U = this.U; - var V = this.rightSingularVectors; - - 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; - } - } - - 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; - - 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(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; - - -/***/ }, -/* 29 */ -/***/ function(module, exports) { - - 'use strict'; - - exports.hypotenuse = function hypotenuse(a, b) { - if (Math.abs(a) > Math.abs(b)) { - var r = b / a; - return Math.abs(a) * Math.sqrt(1 + r * r); - } - if (b !== 0) { - var 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; - }; - - -/***/ }, -/* 30 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const Matrix = __webpack_require__(15); - const util = __webpack_require__(29); - const hypotenuse = util.hypotenuse; - const getFilled2DArray = util.getFilled2DArray; - - 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 = Matrix.checkMatrix(matrix); - if (!matrix.isSquare()) { - throw new Error('Matrix is not a square matrix'); - } - - 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(); - } - - 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; - } +"use strict"; - 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]; - } - - for (i = n - 1; i > 0; i--) { - scale = 0; - h = 0; - for (k = 0; k < i; k++) { - scale = scale + Math.abs(d[k]); - } - - if (scale === 0) { - e[i] = d[i - 1]; - for (j = 0; j < i; j++) { - d[j] = V[i - 1][j]; - V[i][j] = 0; - V[j][i] = 0; - } - } else { - for (k = 0; k < i; k++) { - d[k] /= scale; - h += d[k] * d[k]; - } - - f = d[i - 1]; - g = Math.sqrt(h); - if (f > 0) { - g = -g; - } - - e[i] = scale * g; - h = h - f * g; - d[i - 1] = f - g; - for (j = 0; j < i; j++) { - e[j] = 0; - } - - for (j = 0; j < i; j++) { - f = d[j]; - V[j][i] = f; - g = e[j] + V[j][j] * f; - for (k = j + 1; k <= i - 1; k++) { - g += V[k][j] * d[k]; - e[k] += V[k][j] * f; - } - e[j] = g; - } - - f = 0; - for (j = 0; j < i; j++) { - e[j] /= h; - f += e[j] * d[j]; - } - - hh = f / (h + h); - for (j = 0; j < i; j++) { - e[j] -= hh * d[j]; - } - - for (j = 0; j < i; j++) { - f = d[j]; - g = e[j]; - for (k = j; k <= i - 1; k++) { - V[k][j] -= (f * e[k] + g * d[k]); - } - d[j] = V[i - 1][j]; - V[i][j] = 0; - } - } - d[i] = h; - } - - for (i = 0; i < n - 1; i++) { - V[n - 1][i] = V[i][i]; - V[i][i] = 1; - h = d[i + 1]; - if (h !== 0) { - for (k = 0; k <= i; k++) { - d[k] = V[k][i + 1] / h; - } - - for (j = 0; j <= i; j++) { - g = 0; - for (k = 0; k <= i; k++) { - g += V[k][i + 1] * V[k][j]; - } - for (k = 0; k <= i; k++) { - V[k][j] -= g * d[k]; - } - } - } - - for (k = 0; k <= i; k++) { - V[k][i + 1] = 0; - } - } - - for (j = 0; j < n; j++) { - d[j] = V[n - 1][j]; - V[n - 1][j] = 0; - } - - V[n - 1][n - 1] = 1; - e[0] = 0; - } - function tql2(n, e, d, V) { - - var g, h, i, j, k, l, m, p, r, - dl1, c, c2, c3, el1, s, s2, - iter; - - for (i = 1; i < n; i++) { - e[i - 1] = e[i]; - } - - e[n - 1] = 0; - - var f = 0, - 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; - - g = d[l]; - p = (d[l + 1] - g) / (2 * e[l]); - r = hypotenuse(p, 1); - if (p < 0) { - r = -r; - } - - d[l] = e[l] / (p + r); - d[l + 1] = e[l] * (p + r); - dl1 = d[l + 1]; - h = g - d[l]; - for (i = l + 2; i < n; i++) { - d[i] -= h; - } - - f = f + h; - - p = d[m]; - c = 1; - c2 = c; - c3 = c; - el1 = e[l + 1]; - s = 0; - s2 = 0; - for (i = m - 1; i >= l; i--) { - c3 = c2; - c2 = c; - s2 = s; - g = c * e[i]; - h = c * p; - r = hypotenuse(p, e[i]); - e[i + 1] = s * r; - s = e[i] / r; - c = p / r; - p = c * d[i] - s * g; - d[i + 1] = h + s * (c * g + s * d[i]); - - for (k = 0; k < n; k++) { - h = V[k][i + 1]; - V[k][i + 1] = s * V[k][i] + c * h; - V[k][i] = c * V[k][i] - s * h; - } - } - - p = -s * s2 * c3 * el1 * e[l] / dl1; - e[l] = s * p; - d[l] = c * p; - - } - while (Math.abs(e[l]) > eps * tst1); - } - d[l] = d[l] + f; - e[l] = 0; - } - - for (i = 0; i < n - 1; i++) { - k = i; - p = d[i]; - for (j = i + 1; j < n; j++) { - if (d[j] < p) { - k = j; - p = d[j]; - } - } - - if (k !== i) { - d[k] = d[i]; - d[i] = p; - for (j = 0; j < n; j++) { - p = V[j][i]; - V[j][i] = V[j][k]; - V[j][k] = p; - } - } - } - } - function orthes(n, H, ort, V) { - - var low = 0, - 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]); - } - - if (scale !== 0) { - h = 0; - for (i = high; i >= m; i--) { - ort[i] = H[i][m - 1] / scale; - h += ort[i] * ort[i]; - } - - g = Math.sqrt(h); - if (ort[m] > 0) { - g = -g; - } - - h = h - ort[m] * g; - ort[m] = ort[m] - g; - - for (j = m; j < n; j++) { - f = 0; - for (i = high; i >= m; i--) { - f += ort[i] * H[i][j]; - } - - f = f / h; - for (i = m; i <= high; i++) { - H[i][j] -= f * ort[i]; - } - } - - for (i = 0; i <= high; i++) { - f = 0; - for (j = high; j >= m; j--) { - f += ort[j] * H[i][j]; - } - - f = f / h; - for (j = m; j <= high; j++) { - H[i][j] -= f * ort[j]; - } - } - - ort[m] = scale * ort[m]; - H[m][m - 1] = scale * g; - } - } - - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - V[i][j] = (i === j ? 1 : 0); - } - } - - for (m = high - 1; m >= low + 1; m--) { - if (H[m][m - 1] !== 0) { - for (i = m + 1; i <= high; i++) { - ort[i] = H[i][m - 1]; - } - - for (j = m; j <= high; j++) { - g = 0; - for (i = m; i <= high; i++) { - g += ort[i] * V[i][j]; - } - - g = (g / ort[m]) / H[m][m - 1]; - for (i = m; i <= high; i++) { - V[i][j] += g * ort[i]; - } - } - } - } - } +/** + * 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})); - 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]); - } - } - - while (n >= low) { - l = n; - while (l > low) { - s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); - if (s === 0) { - s = norm; - } - if (Math.abs(H[l][l - 1]) < eps * s) { - break; - } - l--; - } - - if (l === n) { - H[n][n] = H[n][n] + exshift; - d[n] = H[n][n]; - e[n] = 0; - n--; - iter = 0; - } else if (l === n - 1) { - w = H[n][n - 1] * H[n - 1][n]; - p = (H[n - 1][n - 1] - H[n][n]) / 2; - q = p * p + w; - z = Math.sqrt(Math.abs(q)); - H[n][n] = H[n][n] + exshift; - H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; - x = H[n][n]; - - if (q >= 0) { - z = (p >= 0) ? (p + z) : (p - z); - d[n - 1] = x + z; - d[n] = d[n - 1]; - if (z !== 0) { - d[n] = x - w / z; - } - e[n - 1] = 0; - e[n] = 0; - x = H[n][n - 1]; - s = Math.abs(x) + Math.abs(z); - p = x / s; - q = z / s; - r = Math.sqrt(p * p + q * q); - p = p / r; - q = q / r; - - for (j = n - 1; j < nn; j++) { - z = H[n - 1][j]; - H[n - 1][j] = q * z + p * H[n][j]; - H[n][j] = q * H[n][j] - p * z; - } - - for (i = 0; i <= n; i++) { - z = H[i][n - 1]; - H[i][n - 1] = q * z + p * H[i][n]; - H[i][n] = q * H[i][n] - p * z; - } - - for (i = low; i <= high; i++) { - z = V[i][n - 1]; - V[i][n - 1] = q * z + p * V[i][n]; - V[i][n] = q * V[i][n] - p * z; - } - } else { - d[n - 1] = x + p; - d[n] = x + p; - e[n - 1] = z; - e[n] = -z; - } - - n = n - 2; - iter = 0; - } else { - x = H[n][n]; - y = 0; - w = 0; - if (l < n) { - y = H[n - 1][n - 1]; - w = H[n][n - 1] * H[n - 1][n]; - } - - if (iter === 10) { - exshift += x; - for (i = low; i <= n; i++) { - H[i][i] -= x; - } - s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); - x = y = 0.75 * s; - w = -0.4375 * s * s; - } - - if (iter === 30) { - s = (y - x) / 2; - s = s * s + w; - if (s > 0) { - s = Math.sqrt(s); - if (y < x) { - s = -s; - } - s = x - w / ((y - x) / 2 + s); - for (i = low; i <= n; i++) { - H[i][i] -= s; - } - exshift += s; - x = y = w = 0.964; - } - } - - iter = iter + 1; - - m = n - 2; - while (m >= l) { - z = H[m][m]; - r = x - z; - s = y - z; - p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; - q = H[m + 1][m + 1] - z - r - s; - r = H[m + 2][m + 1]; - s = Math.abs(p) + Math.abs(q) + Math.abs(r); - p = p / s; - q = q / s; - r = r / s; - if (m === l) { - break; - } - if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { - break; - } - m--; - } - - for (i = m + 2; i <= n; i++) { - H[i][i - 2] = 0; - if (i > m + 2) { - H[i][i - 3] = 0; - } - } - - for (k = m; k <= n - 1; k++) { - notlast = (k !== n - 1); - if (k !== m) { - p = H[k][k - 1]; - q = H[k + 1][k - 1]; - r = (notlast ? H[k + 2][k - 1] : 0); - x = Math.abs(p) + Math.abs(q) + Math.abs(r); - if (x !== 0) { - p = p / x; - q = q / x; - r = r / x; - } - } - - if (x === 0) { - break; - } - - s = Math.sqrt(p * p + q * q + r * r); - if (p < 0) { - s = -s; - } - - if (s !== 0) { - if (k !== m) { - H[k][k - 1] = -s * x; - } else if (l !== m) { - H[k][k - 1] = -H[k][k - 1]; - } - - p = p + s; - x = p / s; - y = q / s; - z = r / s; - q = q / p; - r = r / p; - - for (j = k; j < nn; j++) { - p = H[k][j] + q * H[k + 1][j]; - if (notlast) { - p = p + r * H[k + 2][j]; - H[k + 2][j] = H[k + 2][j] - p * z; - } - - H[k][j] = H[k][j] - p * x; - H[k + 1][j] = H[k + 1][j] - p * y; - } - - for (i = 0; i <= Math.min(n, k + 3); i++) { - p = x * H[i][k] + y * H[i][k + 1]; - if (notlast) { - p = p + z * H[i][k + 2]; - H[i][k + 2] = H[i][k + 2] - p * r; - } - - H[i][k] = H[i][k] - p; - H[i][k + 1] = H[i][k + 1] - p * q; - } - - for (i = low; i <= high; i++) { - p = x * V[i][k] + y * V[i][k + 1]; - if (notlast) { - p = p + z * V[i][k + 2]; - V[i][k + 2] = V[i][k + 2] - p * r; - } - - V[i][k] = V[i][k] - p; - V[i][k + 1] = V[i][k + 1] - p * q; - } - } - } - } - } - - if (norm === 0) { - return; - } - - for (n = nn - 1; n >= 0; n--) { - p = d[n]; - q = e[n]; - - if (q === 0) { - l = n; - H[n][n] = 1; - for (i = n - 1; i >= 0; i--) { - w = H[i][i] - p; - r = 0; - for (j = l; j <= n; j++) { - r = r + H[i][j] * H[j][n]; - } - - if (e[i] < 0) { - z = w; - s = r; - } else { - l = i; - if (e[i] === 0) { - H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm)); - } else { - x = H[i][i + 1]; - y = H[i + 1][i]; - q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; - t = (x * s - z * r) / q; - H[i][n] = t; - H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z); - } - - t = Math.abs(H[i][n]); - if ((eps * t) * t > 1) { - for (j = i; j <= n; j++) { - H[j][n] = H[j][n] / t; - } - } - } - } - } else if (q < 0) { - l = n - 1; - - if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { - H[n - 1][n - 1] = q / H[n][n - 1]; - H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; - } else { - cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); - H[n - 1][n - 1] = cdivres[0]; - H[n - 1][n] = cdivres[1]; - } - - H[n][n - 1] = 0; - H[n][n] = 1; - for (i = n - 2; i >= 0; i--) { - ra = 0; - sa = 0; - for (j = l; j <= n; j++) { - ra = ra + H[i][j] * H[j][n - 1]; - sa = sa + H[i][j] * H[j][n]; - } - - w = H[i][i] - p; - - if (e[i] < 0) { - z = w; - r = ra; - s = sa; - } else { - l = i; - if (e[i] === 0) { - cdivres = cdiv(-ra, -sa, w, q); - H[i][n - 1] = cdivres[0]; - H[i][n] = cdivres[1]; - } else { - x = H[i][i + 1]; - y = H[i + 1][i]; - vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; - vi = (d[i] - p) * 2 * q; - if (vr === 0 && vi === 0) { - vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); - } - cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); - H[i][n - 1] = cdivres[0]; - H[i][n] = cdivres[1]; - if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { - H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; - H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; - } else { - cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); - H[i + 1][n - 1] = cdivres[0]; - H[i + 1][n] = cdivres[1]; - } - } - - t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); - if ((eps * t) * t > 1) { - for (j = i; j <= n; j++) { - H[j][n - 1] = H[j][n - 1] / t; - H[j][n] = H[j][n] / t; - } - } - } - } - } - } - - 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; - } - } - } + // 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]); + } + } - 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]; - } - } + // 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]; + } + } - module.exports = EigenvalueDecomposition; + return result; +} +module.exports = distanceMatrix; -/***/ }, -/* 31 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Matrix = __webpack_require__(15); - - // https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs - function LuDecomposition(matrix) { - if (!(this instanceof LuDecomposition)) { - return new LuDecomposition(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(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(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.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, - X = value.subMatrixRow(this.pivotVector, 0, count - 1), - columns = lu.columns, - 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; - - -/***/ }, -/* 32 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Matrix = __webpack_require__(15); - var hypotenuse = __webpack_require__(29).hypotenuse; - - //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); - - 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 = 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; - } +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const Matrix = __webpack_require__(0); + +const Layer = __webpack_require__(32); +const OutputLayer = __webpack_require__(116); +const Utils = __webpack_require__(34); +const ACTIVATION_FUNCTIONS = __webpack_require__(33); + +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; + + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { - QrDecomposition.prototype = { - solve: function (value) { - value = Matrix.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, - X = value.clone(), - n = qr.columns, - 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 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]; - } - - s = -s / qr[k][k]; - - for (i = k; i < rows; i++) { - X[i][j] += s * qr[i][k]; - } - } - } - } - return X; - } - }; - - module.exports = QrDecomposition; - - -/***/ }, -/* 33 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Matrix = __webpack_require__(15); - - // 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; - } +exports.agnes = __webpack_require__(118); +exports.diana = __webpack_require__(119); +//exports.birch = require('./birch'); +//exports.cure = require('./cure'); +//exports.chameleon = require('./chameleon'); - 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; - - -/***/ }, -/* 34 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var extend = __webpack_require__(35); - - 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'); - } +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const utils = __webpack_require__(36); +const init = __webpack_require__(131); +const KMeansResult = __webpack_require__(130); +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; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * 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'); - } +"use strict"; - module.exports = padArray; +module.exports = __webpack_require__(133); -/***/ }, -/* 35 */ -/***/ function(module, exports) { +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { - 'use strict'; +"use strict"; - var hasOwn = Object.prototype.hasOwnProperty; - var toStr = Object.prototype.toString; - var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } +module.exports = exports = __webpack_require__(39).NaiveBayes; +exports.separateClasses = __webpack_require__(39).separateClasses; - return toStr.call(arr) === '[object Array]'; - }; - var isPlainObject = function isPlainObject(obj) { - if (!obj || toStr.call(obj) !== '[object Object]') { - return false; - } +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +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); + + 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]; + } + } + + } + + //} + } + 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; +} + +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; + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +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 +}; + +/** + * 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; + } + + options = Object.assign({}, defaultOptions, options); + + this.center = false; + this.scale = false; + this.means = null; + this.stdevs = null; + + if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset + this._computeFromCovarianceMatrix(dataset); + return; + } + + 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 + }); + + this.U = svd.rightSingularVectors; + + const singularValues = svd.diagonal; + const eigenvalues = new Array(singularValues.length); + for (var i = 0; i < singularValues.length; i++) { + eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1); + } + this.S = eigenvalues; + } + } + + /** + * Load a PCA model from JSON + * @param {Object} model + * @return {PCA} + */ + 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); + } + + /** + * Returns the proportion of variance for each component + * @return {[number]} + */ + getExplainedVariance() { + var sum = 0; + for (var i = 0; i < this.S.length; i++) { + sum += this.S[i]; + } + return this.S.map(value => value / sum); + } + + /** + * Returns the cumulative proportion of variance + * @return {[number]} + */ + getCumulativeVariance() { + var explained = this.getExplainedVariance(); + for (var i = 1; i < explained.length; i++) { + explained[i] += explained[i - 1]; + } + return explained; + } + + /** + * Returns the Eigenvectors of the covariance matrix + * @returns {Matrix} + */ + getEigenvectors() { + return this.U; + } + + /** + * Returns the Eigenvalues (on the diagonal) + * @returns {[number]} + */ + getEigenvalues() { + return this.S; + } + + /** + * Returns the standard deviations of the principal components + * @returns {[number]} + */ + getStandardDeviations() { + return this.S.map(x => Math.sqrt(x)); + } + + /** + * 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, + }; + } + + _adjust(dataset, options) { + this.center = !!options.center; + this.scale = !!options.scale; + + dataset = new Matrix(dataset); + + if (this.center) { + const means = mean(dataset); + const stdevs = this.scale ? stdev(dataset, means, true) : null; + this.means = means; + dataset.subRowVector(means); + if (this.scale) { + for (var i = 0; i < stdevs.length; i++) { + if (stdevs[i] === 0) { + throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i); + } + } + this.stdevs = stdevs; + dataset.divRowVector(stdevs); + } + } + + return dataset; + } + + _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(); + } +} + +module.exports = PCA; + + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const measures = __webpack_require__(148); + +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; + + const predP = []; + + if (options.all) { + for (var i = 0; i < rows; i++) { + for (var j = 0; j < columns; j++) { + predP.push({ + pred: prediction[i][j], + targ: target[i][j] + }); + } + } + } else { + if (rows < 3 || rows !== columns) { + throw new Error('When "all" option is false, the prediction matrix must be square and have at least 3 columns'); + } + for (var i = 0; i < rows - 1; i++) { + for (var j = i + 1; j < columns; j++) { + predP.push({ + pred: prediction[i][j], + targ: target[i][j] + }); + } + } + } + + 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]; + + var nPos = 0; + var nNeg = 0; + + var currentPred = predP[0].pred; + var nTp = 0; + var nFp = 0; + for (var i = 0; i < predP.length; i++) { + if (predP[i].pred !== currentPred) { + cutoffs.push(currentPred); + fp.push(nFp); + tp.push(nTp); + currentPred = predP[i].pred; + } + if (predP[i].targ) { + nPos++; + nTp++; + } else { + nNeg++; + nFp++; + } + } + cutoffs.push(currentPred); + fp.push(nFp); + tp.push(nTp); + + const l = cutoffs.length; + const fn = this.fn = new Array(l); + const tn = this.tn = new Array(l); + const nPosPred = this.nPosPred = new Array(l); + const nNegPred = this.nNegPred = new Array(l); + + for (var i = 0; i < l; i++) { + fn[i] = nPos - tp[i]; + tn[i] = nNeg - fp[i]; + + nPosPred[i] = tp[i] + fp[i]; + nNegPred[i] = tn[i] + fn[i]; + } + + 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); + } + + /** + * 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; + } + + /** + * 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; + } + + getDistribution(options) { + options = options || {}; + var cutLength = this.cutoffs.length; + var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100; + var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100; + var interval = options.interval || Math.floor(((cutHigh - cutLow) / 20 * 10000000) - 1) / 10000000; // Trick to avoid the precision problem of float numbers + + var xLabels = []; + var interValues = []; + var intraValues = []; + var interCumPercent = []; + var intraCumPercent = []; + + var nTP = this.tp[cutLength - 1], currentTP = 0; + var nFP = this.fp[cutLength - 1], currentFP = 0; + + for (var i = cutLow, j = (cutLength - 1); i <= cutHigh; i += interval) { + while (this.cutoffs[j] < i) + j--; + + xLabels.push(i); + + var thisTP = nTP - currentTP - this.tp[j]; + var thisFP = nFP - currentFP - this.fp[j]; + + currentTP += thisTP; + currentFP += thisFP; + + interValues.push(thisFP); + intraValues.push(thisTP); + + interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100); + intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100); + } + + return { + xLabels: xLabels, + interValues: interValues, + intraValues: intraValues, + interCumPercent: interCumPercent, + intraCumPercent: intraCumPercent + }; + } +} + +Performance.names = { + acc: 'Accuracy', + err: 'Error rate', + fpr: 'False positive rate', + tpr: 'True positive rate', + fnr: 'False negative rate', + tnr: 'True negative rate', + ppv: 'Positive predictive value', + npv: 'Negative predictive value', + pcfall: 'Prediction-conditioned fallout', + pcmiss: 'Prediction-conditioned miss', + lift: 'Lift value', + rpp: 'Rate of positive predictions', + rnp: 'Rate of negative predictions', + threshold: 'Threshold' +}; + +module.exports = Performance; + + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { - 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; - } +module.exports = exports = __webpack_require__(150); +exports.Utils = __webpack_require__(12); +exports.OPLS = __webpack_require__(149); - // 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 = {}; - } - 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]; - - // 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); - - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - target[name] = copy; - } - } - } - } - } +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { - // Return the modified object - return target; - }; +"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); -/***/ }, -/* 36 */ -/***/ function(module, exports, __webpack_require__) { - 'use strict'; +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +//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); + +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)') + + + if (options.windowSize>data.length) + throw new RangeError('Window size is higher than the data length '+options.windowSize+">"+data.length); + if ((options.derivative < 0) || !(Number.isInteger(options.derivative))) + throw new RangeError('Derivative should be a positive integer'); + if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial))) + throw new RangeError('Polynomial should be a positive integer'); + if (options.polynomial >= 6) + console.warn('You should not use polynomial grade higher than 5 if you are' + + ' not sure that your data arises from such a model. Possible polynomial oscillation problems'); + + var windowSize = options.windowSize; + + var half = Math.floor(windowSize/2); + var np = data.length; + var ans = new Array(np); + var weights = fullWeights(windowSize,options.polynomial,options.derivative); + var hs = 0; + var constantH = true; + if( Object.prototype.toString.call( h ) === '[object Array]' ) { + constantH = false; + } + else{ + hs = Math.pow(h, options.derivative); + } + //console.log("Constant h: "+constantH); + //For the borders + for(var i=0;i=0 && i < h.length-1){ + hs+= (h[i+1]-h[i]); + count++; + } + } + return Math.pow(hs/count,derivative); +} + +function GramPoly(i,m,k,s){ + var Grampoly = 0; + if(k>0){ + Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) + + s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s); + } + else{ + if(k==0&&s==0){ + Grampoly=1; + } + else{ + Grampoly=0; + } + } + //console.log(Grampoly); + return Grampoly; +} + +function GenFact(a,b){ + var gf=1; + if(a>=b){ + for(var j=a-b+1;j<=a;j++){ + gf*=j; + } + } + return gf; +} + +function Weight(i,t,m,n,s){ + var sum=0; + for(var k=0;k<=n;k++){ + //console.log(k); + sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s) + } + return sum; +} + +/** + * + * @param m Number of points + * @param n Polynomial grade + * @param s Derivative + */ +function fullWeights(m,n,s){ + var weights = new Array(m); + var np = Math.floor(m/2); + for(var t=-np;t<=np;t++){ + weights[t+np] = new Array(m); + for(var j=-np;j<=np;j++){ + weights[t+np][j+np]=Weight(j,t,np,n,s); + } + } + return weights; +} + +/*function entropy(data,h,options){ + var trend = SavitzkyGolay(data,h,trendOptions); + var copy = new Array(data.length); + var sum = 0; + var max = 0; + for(var i=0;i} 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; + } + else { + C = [2, -1, -2, -1, 2]; + norm = 7; + } + } + else { + var J = Matrix.ones(options.windowSize, options.polynomial + 1); + var inic = -(options.windowSize - 1) / 2; + for (var i = 0; i < J.length; i++) { + for (var j = 0; j < J[i].length; j++) { + if ((inic + 1 !== 0) || (j !== 0)) + J[i][j] = Math.pow((inic + i), j); + } + } + var Jtranspose = J.transposeView(); + var Jinv = (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); + +var defaultOptions = { + fields: 3, + randomizer: Math.random, + distance: squareEuclidean, + iterations: 10, + learningRate: 0.1, + gridType: 'rect', + torus: true, + method: 'random' +}; + +function SOM(x, y, options, reload) { + + this.x = x; + this.y = y; + + options = options || {}; + this.options = {}; + 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) + }; + } + + 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'); + } + + this.times = { + findBMU: 0, + adjust: 0 + }; + + this.randomizer = this.options.randomizer; + + this.iterationCount = 0; + this.iterations = this.options.iterations; + + this.startLearningRate = this.learningRate = this.options.learningRate; + + this.mapRadius = Math.floor(Math.max(x, y) / 2); + + this.algorithmMethod = this.options.method; + + this._initNodes(); + + this.done = false; +} + +SOM.load = function loadModel(model, distance) { + if (model.name === 'SOM') { + var x = model.data.length, + y = model.data[0].length; + if (distance) { + model.options.distance = distance; + } else if (model.options.distance) { + model.options.distance = eval('(' + model.options.distance + ')'); + } + var som = new SOM(x, y, model.options, true); + som.nodes = new Array(x); + for (var i = 0; i < x; i++) { + som.nodes[i] = new Array(y); + for (var j = 0; j < y; j++) { + som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som); + } + } + return som; + } else { + throw new Error('expecting a SOM model'); + } +}; + +SOM.prototype.export = function exportModel(includeDistance) { + if (!this.done) { + throw new Error('model is not ready yet'); + } + var model = { + name: 'SOM' + }; + model.options = { + fields: this.options.fields, + gridType: this.options.gridType, + torus: this.options.torus + }; + model.data = new Array(this.x); + for (var i = 0; i < this.x; i++) { + model.data[i] = new Array(this.y); + for (var j = 0; j < this.y; j++) { + model.data[i][j] = this.nodes[i][j].weights; + } + } + if (includeDistance) { + model.options.distance = this.distance.toString(); + } + return model; +}; + +SOM.prototype._initNodes = function initNodes() { + var now = Date.now(), + i, j, k; + this.nodes = new Array(this.x); + for (i = 0; i < this.x; i++) { + this.nodes[i] = new Array(this.y); + for (j = 0; j < this.y; j++) { + var weights = new Array(this.numWeights); + for (k = 0; k < this.numWeights; k++) { + weights[k] = this.randomizer(); + } + this.nodes[i][j] = new this.nodeType(i, j, weights, this); + } + } + this.times.initNodes = Date.now() - now; +}; + +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; + + 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; +}; + +SOM.prototype.trainOne = function trainOne() { + if (this.done) { + + return false; + + } else if (this.numIterations-- > 0) { + + 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)); + } + } + + this.iterationCount++; + + return true; + + } else { + + this.done = true; + return false; + + } +}; + +SOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) { + var now = Date.now(), + x, y, dist, influence; + + var bmu = this._findBestMatchingUnit(trainingValue); + + var now2 = Date.now(); + this.times.findBMU += now2 - now; + + var radiusLimit = Math.floor(neighbourhoodRadius); + var xMin = bmu.x - radiusLimit, + xMax = bmu.x + radiusLimit, + yMin = bmu.y - radiusLimit, + yMax = bmu.y + radiusLimit; + + for (x = xMin; x <= xMax; x++) { + var theX = x; + if (x < 0) { + theX += this.x; + } else if (x >= this.x) { + theX -= this.x; + } + for (y = yMin; y <= yMax; y++) { + var theY = y; + if (y < 0) { + theY += this.y; + } else if (y >= this.y) { + theY -= this.y; + } + + dist = bmu[this.distanceMethod](this.nodes[theX][theY]); + + if (dist < neighbourhoodRadius) { + influence = Math.exp(-dist / (2 * neighbourhoodRadius)); + this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence); + } + + } + } + + this.times.adjust += (Date.now() - now2); + +}; + +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; +}; + +SOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) { + + var bmu, + lowest = Infinity, + dist; + + for (var i = 0; i < this.x; i++) { + for (var j = 0; j < this.y; j++) { + dist = this.distance(this.nodes[i][j].weights, candidate); + if (dist < lowest) { + lowest = dist; + bmu = this.nodes[i][j]; + } + } + } + + return bmu; + +}; + +SOM.prototype.predict = function predict(data, computePosition) { + if (typeof data === 'boolean') { + computePosition = data; + data = null; + } + if (!data) { + data = this.trainingSet; + } + if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset + var self = this; + return data.map(function (element) { + return self._predict(element, computePosition); + }); + } else { // predict a single element + return this._predict(data, computePosition); + } +}; + +SOM.prototype._predict = function _predict(element, computePosition) { + if (!Array.isArray(element)) { + element = this.extractor(element); + } + var bmu = this._findBestMatchingUnit(element); + var result = [bmu.x, bmu.y]; + if (computePosition) { + result[2] = bmu.getPosition(element); + } + return result; +}; + +// 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; +}; + +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; +}; + +function getConverters(fields) { + var l = fields.length, + normalizers = new Array(l), + denormalizers = new Array(l); + for (var i = 0; i < l; i++) { + normalizers[i] = getNormalizer(fields[i].range); + denormalizers[i] = getDenormalizer(fields[i].range); + } + return { + extractor: function extractor(value) { + var result = new Array(l); + for (var i = 0; i < l; i++) { + result[i] = normalizers[i](value[fields[i].name]); + } + return result; + }, + creator: function creator(value) { + var result = {}; + for (var i = 0; i < l; i++) { + result[fields[i].name] = denormalizers[i](value[i]); + } + return result; + } + }; +} + +function getNormalizer(minMax) { + return function normalizer(value) { + return (value - minMax[0]) / (minMax[1] - minMax[0]); + }; +} + +function getDenormalizer(minMax) { + return function denormalizer(value) { + return (minMax[0] + value * (minMax[1] - minMax[0])); + }; +} + +function squareEuclidean(a, b) { + var d = 0; + for (var i = 0, ii = a.length; i < ii; i++) { + d += (a[i] - b[i]) * (a[i] - b[i]); + } + return d; +} + +function getRandomValue(arr, randomizer) { + return arr[Math.floor(randomizer() * arr.length)]; +} + +function getMaxDistance(distance, numWeights) { + var zero = new Array(numWeights), + one = new Array(numWeights); + for (var i = 0; i < numWeights; i++) { + zero[i] = 0; + one[i] = 1; + } + return distance(zero, one); +} + +module.exports = SOM; + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + +const HashTable = __webpack_require__(19); + +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]); + } + } + } + } else { + this._init(rows, columns, new HashTable(options), options.threshold); + } + } + + _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; + } + + 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 copy; + } + + 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 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; + } + + 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 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%(); +}) +`; + +var operators = [ + // Arithmetic operators + ['+', 'add'], + ['-', 'sub', 'subtract'], + ['*', 'mul', 'multiply'], + ['/', 'div', 'divide'], + ['%', 'mod', 'modulus'], + // Bitwise operators + ['&', 'and'], + ['|', 'or'], + ['^', 'xor'], + ['<<', 'leftShift'], + ['>>', 'signPropagatingRightShift'], + ['>>>', 'rightShift', 'zeroFillRightShift'] +]; + +for (var operator of operators) { + for (var i = 1; i < operator.length; i++) { + SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]})); + SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]})); + SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]})); + + SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]})); + } +} + +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]); +}); - exports.SimpleLinearRegression = exports.SLR = __webpack_require__(37); - exports.NonLinearRegression = exports.NLR = { - PolynomialRegression: __webpack_require__(40), - PotentialRegression: __webpack_require__(41), - ExpRegression: __webpack_require__(43), - PowerRegression: __webpack_require__(42) - }; - exports.KernelRidgeRegression = exports.KRR = __webpack_require__(44); - //exports.MultipleLinearRegression = exports.MLR = require('./regression/multiple-linear-regression'); - //exports.MultivariateLinearRegression = exports.MVLR = require('./regression/multivariate-linear-regression'); - exports.PolinomialFitting2D = __webpack_require__(57); - exports.TheilSenRegression = __webpack_require__(58); +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]})); + } +} +function fillTemplateFunction(template, values) { + for (var i in values) { + template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]); + } + return template; +} -/***/ }, -/* 37 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var maybeToPrecision = __webpack_require__(38).maybeToPrecision; - const BaseRegression = __webpack_require__(39); - - - 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; - - var xSquared = 0; - var ySquared = 0; - var xY = 0; - - for (var i = 0; i < n; i++) { - xSum += x[i]; - ySum += y[i]; - xSquared += x[i] * x[i]; - ySquared += y[i] * y[i]; - xY += x[i] * y[i]; - } - - var numerator = (n * xY - xSum * ySum); - - - 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); - } - } - - } - - toJSON() { - var out = { - name: 'simpleLinearRegression', - slope: this.slope, - intercept: this.intercept - }; - if (this.quality) { - out.quality = this.quality; - } - - return out; - } - - _predict(input) { - return this.slope * input + this.intercept; - } - - computeX(input) { - return (input - this.intercept) / this.slope; - } - - toString(precision) { - var result = 'y = '; - if (this.slope) { - var xFactor = maybeToPrecision(this.slope, precision); - result += (xFactor == 1 ? '' : xFactor) + 'x'; - if (this.intercept) { - var absIntercept = Math.abs(this.intercept); - var operator = absIntercept === this.intercept ? '+' : '-'; - result += ' ' + operator + ' ' + maybeToPrecision(absIntercept, precision); - } - } else { - result += 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); - } - } - module.exports = SimpleLinearRegression; +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const Kernel = __webpack_require__(8); +const stat = __webpack_require__(2).array; + +var defaultOptions = { + C: 1, + tol: 1e-4, + maxPasses: 10, + maxIterations: 10000, + kernel: 'linear', + alphaTol: 1e-6, + random: Math.random, + whitening: true +}; + +/** + * Simplified version of the Sequential Minimal Optimization algorithm for training + * support vector machines + * @param {{Object}} options - SVM options + * @param {Number} [options.C=1] - regularization parameter + * @param {Number} [options.tol=1e-4] - numerical tolerance + * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors + * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing + * @param {Number} [options.maxIterations=10000] - max number of iterations + * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels} + * @param {Function} [options.random=Math.random] - custom random number generator + * @constructor + */ +function SVM(options) { + this.options = Object.assign({}, defaultOptions, options); + + this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions); + this.b = 0; +} + +/** + * Train the SVM model + * @param {Array >} features - training data features + * @param {Array } labels - training data labels in the domain {1,-1} + */ +SVM.prototype.train = function (features, labels) { + if (features.length !== labels.length) { + throw new Error('Features and labels should have the same length'); + } + if (features.length < 2) { + throw new Error('Cannot train with less than 2 observations'); + } + this._trained = false; + this._loaded = false; + this.N = labels.length; + this.D = features[0].length; + if (this.options.whitening) { + this.X = new Array(this.N); + for (var i = 0; i < this.N; i++) { + this.X[i] = new Array(this.D); + } + this.minMax = new Array(this.D); + // Apply normalization and keep normalization parameters + for (var j = 0; j < this.D; j++) { + var d = new Array(this.N); + for (i = 0; i < this.N; i++) { + d[i] = features[i][j]; + } + this.minMax[j] = stat.minMax(d); + for (i = 0; i < this.N; i++) { + this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); + } + } + } else { + this.X = features; + } + this.Y = labels; + this.b = 0; + this.W = undefined; + + var kernel = this.kernel.compute(this.X); + var m = labels.length; + var alpha = new Array(m).fill(0); + this.alphas = alpha; + for (var a = 0; a < m; a++) + alpha[a] = 0; + + var b1 = 0, + b2 = 0, + iter = 0, + passes = 0, + Ei = 0, + Ej = 0, + ai = 0, + aj = 0, + L = 0, + H = 0, + eta = 0; + + while (passes < this.options.maxPasses && iter < this.options.maxIterations) { + var numChange = 0; + for (i = 0; i < m; i++) { + Ei = this._marginOnePrecomputed(i, kernel) - labels[i]; + if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) { + j = i; + while (j === i) j = Math.floor(this.options.random() * m); + Ej = this._marginOnePrecomputed(j, kernel) - labels[j]; + ai = alpha[i]; + aj = alpha[j]; + if (labels[i] === labels[j]) { + L = Math.max(0, ai + aj - this.options.C); + H = Math.min(this.options.C, ai + aj); + } else { + L = Math.max(0, aj - ai); + H = Math.min(this.options.C, this.options.C + aj + ai); + } + if (Math.abs(L - H) < 1e-4) continue; + + eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j]; + if (eta >= 0) continue; + var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta; + if (newaj > H) + newaj = H; + else if (newaj < L) + newaj = L; + if (Math.abs(aj - newaj) < 10e-4) continue; + alpha[j] = newaj; + alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj); + b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j]; + b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j]; + this.b = (b1 + b2) / 2; + if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1; + if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2; + numChange += 1; + } + } + iter++; + if (numChange === 0) + passes += 1; + else + passes = 0; + } + if (iter === this.options.maxIterations) { + throw new Error('max iterations reached'); + } + + this.iterations = iter; + + // Compute the weights (useful for fast decision on new test instances when linear SVM) + if (this.options.kernel === 'linear') { + this.W = new Array(this.D); + 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]; + } + } + + // 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; + + + // 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; +}; + +/** + * 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); + } +}; + +/** + * 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; +}; + + +/** + * 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); + } +}; + +/** + * 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; + } + 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(); + } + 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); + } + return whitened; +}; + +module.exports = SVM; + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -/***/ }, -/* 38 */ -/***/ function(module, exports) { - 'use strict'; +Object.defineProperty(exports, "__esModule", { + value: true +}); - exports.maybeToPrecision = function maybeToPrecision(value, digits) { - if (digits) return value.toPrecision(digits); - else return value.toString(); - }; +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 multiply_uint32(n, m) { + n >>>= 0; + m >>>= 0; + var nlo = n & 0xffff; + var nhi = n - nlo; + return (nhi * m >>> 0) + nlo * m >>> 0; +} + +var XSadd = (function () { + function XSadd() { + var seed = arguments.length <= 0 || arguments[0] === undefined ? Date.now() : arguments[0]; + + _classCallCheck(this, XSadd); + + 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 */ +/***/ (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; + }; + + + /* + 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; + } + 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); + }; + + + /* + 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); + }; + + + /* + 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); + }; + + + /* + Find the n largest elements in a dataset. + */ + + 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(); + }; + + + /* + 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; + }; + + _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; + }; + + _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); + }; + + Heap = (function() { + Heap.push = heappush; + + Heap.pop = heappop; + + Heap.replace = heapreplace; + + Heap.pushpop = heappushpop; + + Heap.heapify = heapify; + + Heap.updateItem = updateItem; + + Heap.nlargest = nlargest; + + Heap.nsmallest = nsmallest; + + function Heap(cmp) { + this.cmp = cmp != null ? cmp : defaultCmp; + this.nodes = []; + } + + Heap.prototype.push = function(x) { + return heappush(this.nodes, x, this.cmp); + }; + + Heap.prototype.pop = function() { + return heappop(this.nodes, this.cmp); + }; + + Heap.prototype.peek = function() { + return this.nodes[0]; + }; + + Heap.prototype.contains = function(x) { + return this.nodes.indexOf(x) !== -1; + }; + + Heap.prototype.replace = function(x) { + return heapreplace(this.nodes, x, this.cmp); + }; + + Heap.prototype.pushpop = function(x) { + return heappushpop(this.nodes, x, this.cmp); + }; + + Heap.prototype.heapify = function() { + return heapify(this.nodes, this.cmp); + }; + + Heap.prototype.updateItem = function(x) { + return updateItem(this.nodes, x, this.cmp); + }; + + Heap.prototype.clear = function() { + return this.nodes = []; + }; + + Heap.prototype.empty = function() { + return this.nodes.length === 0; + }; + + Heap.prototype.size = function() { + return this.nodes.length; + }; + + Heap.prototype.clone = function() { + var heap; + heap = new Heap(); + heap.nodes = this.nodes.slice(0); + return heap; + }; - module.exports = BaseRegression; + Heap.prototype.toArray = function() { + return this.nodes.slice(0); + }; + Heap.prototype.insert = Heap.prototype.push; -/***/ }, -/* 40 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - /** - * 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. - */ - - const maybeToPrecision = __webpack_require__(38).maybeToPrecision; - const BaseRegression = __webpack_require__(39); - const Matrix = __webpack_require__(14); - - - 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'); - } - - 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]); - } - } - } - - var FT = F.transposeView(); - var A = FT.mmul(F); - var B = FT.mmul(Y.transposeView()); - - this.coefficients = A.solve(B).to1DArray(); - this.powers = powers; - this.M = M - 1; - if (opt.computeQuality) { - this.quality = this.modelQuality(x, y); - } - } - } - - _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; - } - - toJSON() { - var out = {name: 'polynomialRegression', - coefficients: this.coefficients, - powers: this.powers, - M: this.M - }; - - if (this.quality) { - out.quality = this.quality; - } - return out; - } - - toString(precision) { - return this._toFormula(precision, false); - } - - toLaTeX(precision) { - return this._toFormula(precision, true); - } - - _toFormula(precision, isLaTeX) { - var sup = '^'; - var closeSup = ''; - var times = '*'; - if (isLaTeX) { - sup = '^{'; - closeSup = '}'; - times = ''; - } - - 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; - } - } - if (this.coefficients[k] > 0) - str = '+' + str; - } - fn = str + fn; - } - if (fn.charAt(0) === '+') { - fn = fn.slice(1); - } - - return 'y = ' + fn; - } - - static load(json) { - if (json.name !== 'polynomialRegression') { - throw new TypeError('not a polynomial regression model'); - } - return new PolynomialRegression(true, json); - } - } + Heap.prototype.top = Heap.prototype.peek; - module.exports = PolynomialRegression; + Heap.prototype.front = Heap.prototype.peek; + Heap.prototype.has = Heap.prototype.contains; -/***/ }, -/* 41 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - /* - * Function that calculate the potential fit in the form f(x) = A*x^M - * with a given M and return de A coefficient. - * - * @param {Vector} X - Vector of the x positions of the points. - * @param {Vector} Y - Vector of the x positions of the points. - * @param {Number, BigNumber} M - The exponent of the potential fit. - * @return {Number|BigNumber} A - The A coefficient of the potential fit. - * Created by acastillo on 5/12/16. - */ - - const maybeToPrecision = __webpack_require__(38).maybeToPrecision; - const PolynomialRegression = __webpack_require__(40); - const PowerRegression = __webpack_require__(42); - const BaseRegression = __webpack_require__(39); - - class PotentialRegression extends BaseRegression { - /** - * @constructor - * @param x: Independent variable - * @param y: Dependent variable - * @param options - */ - constructor(x, y, M, options) { - super(); - let opt = options || {}; - if (x === true) { // reloading model - this.A = y.A; - 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'); - } - - var linear = new PolynomialRegression(x, y, [M], {computeCoefficient: true}); - this.A = linear.coefficients[0]; - this.M = M; - if (opt.computeQuality) { - this.quality = this.modelQuality(x, y); - } - } - } - - _predict(x) { - return this.A * Math.pow(x, this.M); - } - - toJSON() { - var out = {name: 'potentialRegression', A: this.A, M: this.M}; - if (this.quality) { - out.quality = this.quality; - } - return out; - } - - toString(precision) { - return 'y = ' + maybeToPrecision(this.A, precision) + '*x^' + this.M; - } - - toLaTeX(precision) { - - if (this.M >= 0) - return 'y = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}'; - else - return 'y = \\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + (-this.M) + '}}'; - } - - static load(json) { - if (json.name !== 'potentialRegression') { - throw new TypeError('not a potential regression model'); - } - return new PowerRegression(true, json); - } - } + Heap.prototype.copy = Heap.prototype.clone; - module.exports = PotentialRegression; + return Heap; + })(); -/***/ }, -/* 42 */ -/***/ 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__(38).maybeToPrecision; - const SimpleLinearRegression = __webpack_require__(37); - const BaseRegression = __webpack_require__(39); - - 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 'y = ' + maybeToPrecision(this.A, precision) + '*x^' + maybeToPrecision(this.B, precision); - } - - toLaTeX(precision) { - if (this.B >= 0) - return 'y = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}'; - else - return 'y = \\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); - } - } + (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 = PowerRegression; +}).call(this); -/***/ }, -/* 43 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - /* - * 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__(38).maybeToPrecision; - const SimpleLinearRegression = __webpack_require__(37); - const BaseRegression = __webpack_require__(39); - - class ExpRegression 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.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]); - } - - 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); - } - } - } - - _predict(newInputs) { - return this.C * Math.exp(newInputs * this.A); - } - - toJSON() { - var out = {name: 'expRegression', A: this.A, C: this.C}; - if (this.quality) { - out.quality = this.quality; - } - return out; - } - - toString(precision) { - return 'y = ' + maybeToPrecision(this.C, precision) + '*exp(' + maybeToPrecision(this.A, precision) + '*x)'; - } - - toLaTeX(precision) { - if (this.A >= 0) - return 'y = ' + maybeToPrecision(this.C, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}'; - else - return 'y = \\frac{' + maybeToPrecision(this.C, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}'; - - } - - static load(json) { - if (json.name !== 'expRegression') { - throw new TypeError('not a exp regression model'); - } - return new ExpRegression(true, json); - } - } +/***/ }), +/* 65 */ +/***/ (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); + + 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 pointsArr; +} + + +/** + * Function that given an array as follows: + * [x1, y1, .. , x2, y2, ..] + * + * Returns an array as follows: + * [[x1, x2, ..], [y1, y2, ..], [ .. ]] + * + * And receives the number of dimensions of each coordinate. + * @param array + * @param dimensions + * @returns {Array} - Matrix of coordinates + */ +function coordArrayToCoordMatrix(array, dimensions) { + if(array.length % dimensions !== 0) { + throw new RangeError('Dimensions number must be accordance with the size of the array.'); + } + + var coordinatesArray = new Array(dimensions); + var points = array.length / dimensions; + for (var i = 0; i < coordinatesArray.length; i++) { + coordinatesArray[i] = new Array(points); + } + + for(i = 0; i < array.length; i += dimensions) { + for(var j = 0; j < dimensions; ++j) { + var currentPoint = Math.floor(i / dimensions); + coordinatesArray[j][currentPoint] = array[i + j]; + } + } + + return coordinatesArray; +} + +/** + * Function that receives a coordinate matrix as follows: + * [[x1, x2, ..], [y1, y2, ..], [ .. ]] + * + * Returns an array of coordinates as follows: + * [x1, y1, .. , x2, y2, ..] + * + * @param coordMatrix + * @returns {Array} + */ +function coordMatrixToCoordArray(coordMatrix) { + var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length); + var k = 0; + for(var i = 0; i < coordMatrix[0].length; ++i) { + for(var j = 0; j < coordMatrix.length; ++j) { + coodinatesArray[k] = coordMatrix[j][i]; + ++k; + } + } + + return coodinatesArray; +} + +/** + * Tranpose a matrix, this method is for coordMatrixToPoints and + * pointsToCoordMatrix, that because only transposing the matrix + * you can change your representation. + * + * @param matrix + * @returns {Array} + */ +function transpose(matrix) { + var resultMatrix = new Array(matrix[0].length); + for(var i = 0; i < resultMatrix.length; ++i) { + resultMatrix[i] = new Array(matrix.length); + } + + for (i = 0; i < matrix.length; ++i) { + for(var j = 0; j < matrix[0].length; ++j) { + resultMatrix[j][i] = matrix[i][j]; + } + } + + return resultMatrix; +} + +/** + * Function that transform an array of points into a coordinates array + * as follows: + * [x1, y1, .. , x2, y2, ..] + * + * @param points + * @returns {Array} + */ +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; +} + +/** + * Apply the dot product between the smaller vector and a subsets of the + * largest one. + * + * @param firstVector + * @param secondVector + * @returns {Array} each dot product of size of the difference between the + * larger and the smallest one. + */ +function applyDotProduct(firstVector, secondVector) { + var largestVector, smallestVector; + if(firstVector.length <= secondVector.length) { + smallestVector = firstVector; + largestVector = secondVector; + } 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; + } + + return dotProductApplied; +} +/** + * To scale the input array between the specified min and max values. The operation is performed inplace + * if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling + * will multiply the input array by min/min(input) or max/max(input) + * @param input + * @param options + * @returns {*} + */ +function scale(input, options){ + var 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; + } + } + } + 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 +}; + + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * + * Function that returns a Number array of equally spaced numberOfPoints + * containing a representation of intensities of the spectra arguments x + * and y. + * + * The options parameter contains an object in the following form: + * from: starting point + * to: last point + * numberOfPoints: number of points between from and to + * variant: "slot" or "smooth" - smooth is the default option + * + * The slot variant consist that each point in the new array is calculated + * averaging the existing points between the slot that belongs to the current + * value. The smooth variant is the same but takes the integral of the range + * of the slot and divide by the step size between two points in the new array. + * + * @param x - sorted increasing x values + * @param y + * @param options + * @returns {Array} new array with the equally spaced data. + * + */ +function getEquallySpacedData(x, y, options) { + if (x.length>1 && x[0]>x[1]) { + x=x.slice().reverse(); + y=y.slice().reverse(); + } + + 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"); + } + + var reverse = from > to; + if(reverse) { + var temp = from; + from = to; + to = temp; + } + + 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; +} + +/** + * function that retrieves the getEquallySpacedData with the variant "smooth" + * + * @param x + * @param y + * @param from - Initial point + * @param to - Final point + * @param numberOfPoints + * @returns {Array} - Array of y's equally spaced with the variant "smooth" + */ +function getEquallySpacedSmooth(x, y, from, to, numberOfPoints) { + var xLength = x.length; + + var step = (to - from) / (numberOfPoints - 1); + var halfStep = step / 2; + + var start = from - halfStep; + var output = new Array(numberOfPoints); + + var initialOriginalStep = x[1] - x[0]; + var lastOriginalStep = x[x.length - 1] - x[x.length - 2]; + + // Init main variables + var min = start; + var max = start + step; + + var previousX = Number.MIN_VALUE; + var previousY = 0; + var nextX = x[0] - initialOriginalStep; + var nextY = 0; + + var currentValue = 0; + var slope = 0; + var intercept = 0; + var sumAtMin = 0; + var sumAtMax = 0; + + var i = 0; // index of input + var j = 0; // index of output + + function getSlope(x0, y0, x1, y1) { + return (y1 - y0) / (x1 - x0); + } + + 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; + + output[j] = (sumAtMax - sumAtMin) / step; + j++; + + if (j === numberOfPoints) + break main; + + min = max; + max += step; + sumAtMin = sumAtMax; + } + + if(previousX <= min && min <= nextX) { + add = integral(0, min - previousX, slope, previousY); + sumAtMin = currentValue + add; + } + + currentValue += integral(previousX, nextX, slope, intercept); + + previousX = nextX; + previousY = nextY; + + 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; + } + + return output; +} + +/** + * function that retrieves the getEquallySpacedData with the variant "slot" + * + * @param x + * @param y + * @param from - Initial point + * @param to - Final point + * @param numberOfPoints + * @returns {Array} - Array of y's equally spaced with the variant "slot" + */ +function getEquallySpacedSlot(x, y, from, to, numberOfPoints) { + var xLength = x.length; + + var step = (to - from) / (numberOfPoints - 1); + var halfStep = step / 2; + var lastStep = x[x.length - 1] - x[x.length - 2]; + + var start = from - halfStep; + var output = new Array(numberOfPoints); + + // Init main variables + var min = start; + var max = start + step; + + var previousX = -Number.MAX_VALUE; + var previousY = 0; + var nextX = x[0]; + var nextY = y[0]; + var frontOutsideSpectra = 0; + var backOutsideSpectra = true; + + var currentValue = 0; + + // for slot algorithm + var currentPoints = 0; + + var i = 1; // index of input + var j = 0; // index of output + + main: while(true) { + if (previousX>=nextX) throw (new Error('x must be an increasing serie')); + while (previousX - max > 0) { + // no overlap with original point, just consume current value + if(backOutsideSpectra) { + currentPoints++; + backOutsideSpectra = false; + } + + output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints; + j++; + + if (j === numberOfPoints) + break main; + + min = max; + max += step; + currentValue = 0; + currentPoints = 0; + } + + if(previousX > min) { + currentValue += previousY; + currentPoints++; + } + + if(previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) + currentPoints--; + + previousX = nextX; + previousY = nextY; + + if (i < xLength) { + nextX = x[i]; + nextY = y[i]; + i++; + } else { + nextX += lastStep; + nextY = 0; + frontOutsideSpectra++; + } + } + + 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.getEquallySpacedData = getEquallySpacedData; +exports.integral = integral; + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; - module.exports = ExpRegression; +exports.SNV = SNV; +var Stat = __webpack_require__(2).array; -/***/ }, -/* 44 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const Matrix = __webpack_require__(14); - const Kernel = __webpack_require__(45); - - const BaseRegression = __webpack_require__(39); - - const defaultOptions = { - lambda: 0.1, - kernelType: 'gaussian', - kernelOptions: {}, - computeCoefficient: false - }; - - // Implements the Kernel ridge regression algorithm. - // http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf - class KernelRidgeRegression extends BaseRegression { - constructor(inputs, outputs, options) { - super(); - if (inputs === true) { // reloading model - this.alpha = outputs.alpha; - this.inputs = outputs.inputs; - this.kernelType = outputs.kernelType; - this.kernelOptions = outputs.kernelOptions; - this.kernel = new Kernel(outputs.kernelType, outputs.kernelOptions); - - if (outputs.quality) { - this.quality = outputs.quality; - } - } else { - options = Object.assign({}, defaultOptions, options); - - const kernelFunction = new Kernel(options.kernelType, options.kernelOptions); - const K = kernelFunction.compute(inputs); - const n = inputs.length; - K.add(Matrix.eye(n, n).mul(options.lambda)); - - this.alpha = K.solve(outputs); - this.inputs = inputs; - this.kernelType = options.kernelType; - this.kernelOptions = options.kernelOptions; - this.kernel = kernelFunction; - - if (options.computeQuality) { - this.quality = this.modelQuality(inputs, outputs); - } - } - } - - _predict(newInputs) { - return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0]; - } - - toJSON() { - var out = { - name: 'kernelRidgeRegression', - alpha: this.alpha, - inputs: this.inputs, - kernelType: this.kernelType, - kernelOptions: this.kernelOptions - }; - if (this.quality) { - out.quality = this.quality; - } - return out; - } - - static load(json) { - if (json.name !== 'kernelRidgeRegression') { - throw new TypeError('not a KRR model'); - } - return new KernelRidgeRegression(true, json); - } - } +/** + * 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; +} - module.exports = KernelRidgeRegression; +/***/ }), +/* 68 */ +/***/ (function(module, exports) { -/***/ }, -/* 45 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const Matrix = __webpack_require__(14); - - const GaussianKernel = __webpack_require__(46); - const PolynomialKernel = __webpack_require__(48); - const ANOVAKernel = __webpack_require__(49); - const CauchyKernel = __webpack_require__(50); - const ExponentialKernel = __webpack_require__(51); - const HistogramKernel = __webpack_require__(52); - const LaplacianKernel = __webpack_require__(53); - const MultiquadraticKernel = __webpack_require__(54); - const RationalKernel = __webpack_require__(55); - const SigmoidKernel = __webpack_require__(56); - - const kernelType = { - gaussian: GaussianKernel, - rbf: GaussianKernel, - polynomial: PolynomialKernel, - poly: PolynomialKernel, - anova: ANOVAKernel, - cauchy: CauchyKernel, - exponential: ExponentialKernel, - histogram: HistogramKernel, - min: HistogramKernel, - laplacian: LaplacianKernel, - multiquadratic: MultiquadraticKernel, - rational: RationalKernel, - sigmoid: SigmoidKernel, - mlp: SigmoidKernel - }; - - class Kernel { - constructor(type, options) { - this.kernelType = type; - if (type === 'linear') return; - - if (typeof type === 'string') { - type = type.toLowerCase(); - - var KernelConstructor = kernelType[type]; - if (KernelConstructor) { - this.kernelFunction = new KernelConstructor(options); - } else { - throw new Error('unsupported kernel type: ' + type); - } - } else if (typeof type === 'object' && typeof type.compute === 'function') { - this.kernelFunction = type; - } else { - throw new TypeError('first argument must be a valid kernel type or instance'); - } - } - - compute(inputs, landmarks) { - if (landmarks === undefined) { - landmarks = inputs; - } - - if (this.kernelType === 'linear') { - var matrix = new Matrix(inputs); - return matrix.mmul(new Matrix(landmarks).transpose()); - } - - 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; - } - } +// auxiliary file to create the 256 look at table elements - module.exports = Kernel; +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; +} +module.exports = ans; -/***/ }, -/* 46 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const defaultOptions = { + mode: 'index' +}; + +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; + + // 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; + } + + // 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 { + if (i === p[0]) { + return 0; + } else { + p[j] = p[i]; + z = p[i] - 1; + p[i] = 0; + x = j - 1; + y = i - 1; + } + } + } + return 1; + } + + 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 { + throw new Error('Invalid mode'); + } +}; + + +/***/ }), +/* 70 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * 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'); + } + if (labels.length !== matrix.length) { + throw new Error('Confusion matrix and labels should have the same length'); + } + this.labels = labels; + this.matrix = matrix; + + } + + /** + * 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]; + } + } + + return correct / (correct + incorrect); + } + + /** + * 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]; + } + } + return predicted; + } +} + +module.exports = ConfusionMatrix; + + +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Created by acastillo on 8/5/15. + */ +var Matrix = __webpack_require__(0); +var math = __webpack_require__(22); + +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 + + 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 = { + + 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 + + var iteration = 0; // iteration counter + //func_calls = 0; // running count of function evaluations + + 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); + + + if (t.length != y_dat.length) { + console.log('lm.m error: the length of t must equal the length of y_dat'); + + 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; + } + } + + 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 ]; + + 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 + + if ( tensor_parameter && prnt == 3 ) prnt = 2; + + + 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 + + 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; + } + + // 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 + + // --- 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; + + /*if nargout > 2 // standard error of parameters + covar = inv(JtWJ); + sigma_p = sqrt(diag(covar)); + end + + 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 + + if nargout > 4 // parameter correlation matrix + corr = covar ./ [sigma_p*sigma_p']; + end + + if nargout > 5 // coefficient of multiple determination + R_sq = corrcoef([y_dat y_hat]); + R_sq = R_sq(1,2).^2; + end + + if nargout > 6 // convergence history + cvg_hst = cvg_hst(1:iteration,:); + end*/ + + // endfunction # ---------------------------------------------------------- LM + + return { p:p, X2:X2}; + }, + + 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 + + // 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. + + 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); + + 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 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]; + } + + } // central difference, additional func call + } + + p[j] = ps[j]; // restore p(j) + + } + //console.log("lm_FD_J: "+ JSON.stringify(J)); + return J; + + }, + + // 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)); + + //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 + }, + + 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. + + + var Npnt = y_dat.length; // number of data points + var Npar = p.length; // number of parameters + + dp = dp || 0.001; + + + //var JtWJ = new Matrix.zeros(Npar); + //var JtWdy = new Matrix.zeros(Npar,1); + + 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); + + //console.log(weight_sq); + + var JtWJ = math.multiply(Jt, math.dotMultiply(J,math.multiply(weight_sq, Matrix.ones(1,Npar)))); + + //JtWdy = J' * ( weight_sq .* delta_y ); + var JtWdy = math.multiply(Jt, math.dotMultiply(weight_sq,delta_y)); + + + return {JtWJ:JtWJ,JtWdy:JtWdy,Chi_sq:Chi_sq,y_hat:y_hat,J:J}; + // endfunction # ------------------------------------------------------ LM_MATX + } + + + +}; + +module.exports = LM; + +/***/ }), +/* 72 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +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); + + +/***/ }), +/* 73 */ +/***/ (function(module, exports) { - 'use strict'; +module.exports = function additiveSymmetric(a, b) { + var i = 0, + ii = a.length, + d = 0; + for (; i < ii; i++) { + d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]); + } + return 2 * d; +}; - const squaredEuclidean = __webpack_require__(47).squared; - const defaultOptions = { - sigma: 1 - }; +/***/ }), +/* 74 */ +/***/ (function(module, exports) { + +module.exports = function avg(a, b) { + var ii = a.length, + max = 0, + ans = 0, + aux = 0; + for (var i = 0; i < ii ; i++) { + aux = Math.abs(a[i] - b[i]); + ans += aux; + if (max < aux) { + max = aux; + } + } + return (max + ans) / 2; +}; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports) { - class GaussianKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - this.divisor = 2 * options.sigma * options.sigma; - } +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]); + } + return - Math.log(ans); +}; - compute(x, y) { - const distance = squaredEuclidean(x, y); - return Math.exp(-distance / this.divisor); - } - } - module.exports = GaussianKernel; +/***/ }), +/* 76 */ +/***/ (function(module, exports) { +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]); + } + return ans; +}; -/***/ }, -/* 47 */ -/***/ function(module, exports) { - 'use strict'; +/***/ }), +/* 77 */ +/***/ (function(module, exports) { + +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; + } + } + return max; +}; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports) { - function squaredEuclidean(p, q) { - var d = 0; - for (var i = 0; i < p.length; i++) { - d += (p[i] - q[i]) * (p[i] - q[i]); - } - return d; - } +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; +}; - function euclidean(p, q) { - return Math.sqrt(squaredEuclidean(p, q)); - } - module.exports = euclidean; - euclidean.squared = squaredEuclidean; +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -/***/ }, -/* 48 */ -/***/ function(module, exports) { - - 'use strict'; - - const defaultOptions = { - degree: 1, - constant: 1, - scale: 1 - }; - - class PolynomialKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - - this.degree = options.degree; - this.constant = options.constant; - this.scale = options.scale; - } - - compute(x, y) { - var sum = 0; - for (var i = 0; i < x.length; i++) { - sum += x[i] * y[i]; - } - return Math.pow(this.scale * sum + this.constant, this.degree); - } - } - module.exports = PolynomialKernel; +const czekanowskiSimilarity = __webpack_require__(30); +module.exports = function czekanowskiDistance(a, b) { + return 1 - czekanowskiSimilarity(a, b); +}; -/***/ }, -/* 49 */ -/***/ function(module, exports) { - - '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; - } - - 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; - } - } - module.exports = ANOVAKernel; +/***/ }), +/* 80 */ +/***/ (function(module, exports) { +module.exports = function divergence(a, b) { + var i = 0, + ii = a.length, + d = 0; + for (; i < ii; i++) { + d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])); + } + return 2 * d; +}; -/***/ }, -/* 50 */ -/***/ function(module, exports, __webpack_require__) { - 'use strict'; +/***/ }), +/* 81 */ +/***/ (function(module, exports) { - const squaredEuclidean = __webpack_require__(47).squared; +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; +}; - const defaultOptions = { - sigma: 1 - }; - class CauchyKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - } +/***/ }), +/* 82 */ +/***/ (function(module, exports) { - compute(x, y) { - return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma)); - } - } +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; +}; - module.exports = CauchyKernel; +/***/ }), +/* 83 */ +/***/ (function(module, exports) { -/***/ }, -/* 51 */ -/***/ function(module, exports, __webpack_require__) { +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; +}; - 'use strict'; - const euclidean = __webpack_require__(47); +/***/ }), +/* 84 */ +/***/ (function(module, exports) { - const defaultOptions = { - sigma: 1 - }; +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]); + } + return 2 * Math.sqrt(1 - ans); +}; - class ExponentialKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - this.divisor = 2 * options.sigma * options.sigma; - } - compute(x, y) { - const distance = euclidean(x, y); - return Math.exp(-distance / this.divisor); - } - } +/***/ }), +/* 85 */ +/***/ (function(module, exports) { - module.exports = ExponentialKernel; +module.exports = function innerProduct(a, b) { + var ii = a.length, + ans = 0; + for (var i = 0; i < ii ; i++) { + ans += a[i] * b[i]; + } + return ans; +}; -/***/ }, -/* 52 */ -/***/ function(module, exports) { - - '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; - } - } - - module.exports = HistogramIntersectionKernel; - - -/***/ }, -/* 53 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const euclidean = __webpack_require__(47); - - const defaultOptions = { - sigma: 1 - }; - - class LaplacianKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.sigma = options.sigma; - } - - compute(x, y) { - const distance = euclidean(x, y); - return Math.exp(-distance / this.sigma); - } - } - - module.exports = LaplacianKernel; - - -/***/ }, -/* 54 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const squaredEuclidean = __webpack_require__(47).squared; - - const defaultOptions = { - constant: 1 - }; - - class MultiquadraticKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.constant = options.constant; - } - - compute(x, y) { - return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant); - } - } - - module.exports = MultiquadraticKernel; - - -/***/ }, -/* 55 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const squaredEuclidean = __webpack_require__(47).squared; - - const defaultOptions = { - constant: 1 - }; - - 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)); - } - } - - module.exports = RationalQuadraticKernel; - - -/***/ }, -/* 56 */ -/***/ function(module, exports) { - - 'use strict'; - - const defaultOptions = { - alpha: 0.01, - constant: -Math.E - }; - - class SigmoidKernel { - constructor(options) { - options = Object.assign({}, defaultOptions, options); - this.alpha = options.alpha; - this.constant = options.constant; - } - - compute(x, y) { - var sum = 0; - for (var i = 0; i < x.length; i++) { - sum += x[i] * y[i]; - } - return Math.tanh(this.alpha * sum + this.constant); - } - } - - module.exports = SigmoidKernel; - - -/***/ }, -/* 57 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const Matrix = __webpack_require__(14); - const SVD = Matrix.DC.SingularValueDecomposition; - const BaseRegression = __webpack_require__(39); - - const defaultOptions = { - order: 2 - }; - // Implements the Kernel ridge regression algorithm. - // http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf - class PolynomialFitRegression2D extends BaseRegression { - /** - * Constructor for the 2D polynomial fitting - * - * @param inputs - * @param outputs - * @param options - * @constructor - */ - constructor(inputs, outputs, options) { - super(); - if (inputs === true) { // reloading model - this.coefficients = Matrix.columnVector(outputs.coefficients); - this.order = outputs.order; - if (outputs.r) { - this.r = outputs.r; - this.r2 = outputs.r2; - } - if (outputs.chi2) { - this.chi2 = outputs.chi2; - } - } else { - options = Object.assign({}, defaultOptions, options); - this.order = options.order; - this.coefficients = []; - this.X = inputs; - this.y = outputs; - - this.train(this.X, this.y, options); - - if (options.computeQuality) { - this.quality = this.modelQuality(inputs, outputs); - } - } - } - - /** - * Function that fits the model given the data(X) and predictions(y). - * The third argument is an object with the following options: - * * order: order of the polynomial to fit. - * - * @param X - A matrix with n rows and 2 columns. - * @param y - A vector of the prediction values. - * @param options - */ - train(X, y, options) { - if (!Matrix.isMatrix(X)) X = new Matrix(X); - if (!Matrix.isMatrix(y)) y = Matrix.columnVector(y); - - if (y.rows !== X.rows)//Perhaps y is transpose - y = y.transpose(); - - if (X.columns !== 2) - throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2'); - if (X.rows !== y.rows) - throw new RangeError('X and y must have the same rows'); - - var examples = X.rows; - var coefficients = ((this.order + 2) * (this.order + 1)) / 2; - this.coefficients = new Array(coefficients); - - var x1 = X.getColumnVector(0); - var x2 = X.getColumnVector(1); - - var scaleX1 = 1.0 / x1.clone().apply(abs).max(); - var scaleX2 = 1.0 / x2.clone().apply(abs).max(); - var scaleY = 1.0 / y.clone().apply(abs).max(); - - x1.mulColumn(0, scaleX1); - x2.mulColumn(0, scaleX2); - y.mulColumn(0, scaleY); - - var A = new Matrix(examples, coefficients); - var col = 0; - - for (var i = 0; i <= this.order; ++i) { - var limit = this.order - i; - for (var j = 0; j <= limit; ++j) { - var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j)); - A.setColumn(col, result); - col++; - } - } - - var svd = new SVD(A.transpose(), { - computeLeftSingularVectors: true, - computeRightSingularVectors: true, - autoTranspose: false - }); - - var qqs = Matrix.rowVector(svd.diagonal); - qqs = qqs.apply(function (i, j) { - if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j]; - else this[i][j] = 0; - }); - - var qqs1 = Matrix.zeros(examples, coefficients); - for (i = 0; i < coefficients; ++i) { - qqs1[i][i] = qqs[0][i]; - } - - qqs = qqs1; - - var U = svd.rightSingularVectors; - var V = svd.leftSingularVectors; - - this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y); - - col = 0; - - for (i = 0; i <= coefficients; ++i) { - limit = this.order - i; - for (j = 0; j <= limit; ++j) { - this.coefficients[col][0] = (this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j)) / scaleY; - col++; - } - } - } - - _predict(newInputs) { - var x1 = newInputs[0]; - var x2 = newInputs[1]; - - var y = 0; - var column = 0; - - for (var i = 0; i <= this.order; i++) { - for (var j = 0; j <= this.order - i; j++) { - y += Math.pow(x1, i) * (Math.pow(x2, j)) * this.coefficients[column][0]; - column++; - } - } - - return y; - } - - toJSON() { - var out = { - name: 'polyfit2D', - order: this.order, - coefficients: this.coefficients - }; - if (this.quality) { - out.quality = this.quality; - } - return out; - } - - static load(json) { - if (json.name !== 'polyfit2D') { - throw new TypeError('not a polyfit2D model'); - } - return new PolynomialFitRegression2D(true, json); - } - - } - - module.exports = PolynomialFitRegression2D; - - - /** - * Function that given a column vector return this: vector^power - * - * @param x - Column vector. - * @param power - Pow number. - * @returns {Suite|Matrix} - */ - function powColVector(x, power) { - var result = x.clone(); - for (var i = 0; i < x.rows; ++i) { - result[i][0] = Math.pow(result[i][0], power); - } - return result; - } - - /** - * Function to use in the apply method to get the absolute value - * of each element of the matrix - * - * @param i - current row. - * @param j - current column. - */ - function abs(i, j) { - this[i][j] = Math.abs(this[i][j]); - } - - -/***/ }, -/* 58 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const BaseRegression = __webpack_require__(39); - const maybeToPrecision = __webpack_require__(38).maybeToPrecision; - const median = __webpack_require__(4).median; - - /** - * Theil–Sen estimator - * - * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator - * @class - */ - class TheilSenRegression extends BaseRegression { - - /** - * - * @param x - * @param y - * @param 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 = 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 { - // 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 out; - } - - _predict(input) { - return this.slope * input + this.intercept; - } - - computeX(input) { - return (input - this.intercept) / this.slope; - } - - toString(precision) { - var result = 'y = '; - 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 result; - } - - 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); - } - } - - module.exports = TheilSenRegression; - - -/***/ }, -/* 59 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.distance = __webpack_require__(60); - exports.similarity = __webpack_require__(105); - -/***/ }, -/* 60 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - - exports.additiveSymmetric = __webpack_require__(61); - exports.avg = __webpack_require__(62); - exports.bhattacharyya = __webpack_require__(63); - exports.canberra = __webpack_require__(64); - exports.chebyshev = __webpack_require__(65); - exports.clark = __webpack_require__(66); - exports.czekanowski = __webpack_require__(67); - exports.dice = __webpack_require__(69); - exports.divergence = __webpack_require__(70); - exports.euclidean = __webpack_require__(47); - exports.fidelity = __webpack_require__(71); - exports.gower = __webpack_require__(72); - exports.harmonicMean = __webpack_require__(73); - exports.hellinger = __webpack_require__(74); - exports.innerProduct = __webpack_require__(75); - exports.intersection = __webpack_require__(76); - exports.jaccard = __webpack_require__(77); - exports.jeffreys = __webpack_require__(78); - exports.jensenDifference = __webpack_require__(79); - exports.jensenShannon = __webpack_require__(80); - exports.kdivergence = __webpack_require__(81); - exports.kulczynski = __webpack_require__(82); - exports.kullbackLeibler = __webpack_require__(83); - exports.kumarHassebrook = __webpack_require__(84); - exports.kumarJohnson = __webpack_require__(85); - exports.lorentzian = __webpack_require__(86); - exports.manhattan = __webpack_require__(87); - exports.matusita = __webpack_require__(88); - exports.minkowski = __webpack_require__(89); - exports.motyka = __webpack_require__(90); - exports.neyman = __webpack_require__(91); - exports.pearson = __webpack_require__(92); - exports.probabilisticSymmetric = __webpack_require__(93); - exports.ruzicka = __webpack_require__(94); - exports.soergel = __webpack_require__(95); - exports.sorensen = __webpack_require__(96); - exports.squared = __webpack_require__(97); - exports.squaredChord = __webpack_require__(98); - exports.squaredEuclidean = __webpack_require__(47).squared; - exports.taneja = __webpack_require__(99); - exports.tanimoto = __webpack_require__(100); - exports.topsoe = __webpack_require__(102); - exports.tree = __webpack_require__(103); - exports.waveHedges = __webpack_require__(104); - - -/***/ }, -/* 61 */ -/***/ 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; - }; - - -/***/ }, -/* 62 */ -/***/ function(module, exports) { - - module.exports = function avg(a, b) { - var ii = a.length, - max = 0, - ans = 0, - aux = 0; - for (var i = 0; i < ii ; i++) { - aux = Math.abs(a[i] - b[i]); - ans += aux; - if (max < aux) { - max = aux; - } - } - return (max + ans) / 2; - }; - - -/***/ }, -/* 63 */ -/***/ 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]); - } - return - Math.log(ans); - }; - - -/***/ }, -/* 64 */ -/***/ function(module, exports) { - - 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]); - } - return ans; - }; - - -/***/ }, -/* 65 */ -/***/ function(module, exports) { - - 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; - } - } - return max; - }; - - -/***/ }, -/* 66 */ -/***/ 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; - }; - - -/***/ }, -/* 67 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const czekanowskiSimilarity = __webpack_require__(68); - - module.exports = function czekanowskiDistance(a, b) { - return 1 - czekanowskiSimilarity(a, b); - }; - - -/***/ }, -/* 68 */ -/***/ function(module, exports) { - - '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; - }; - - -/***/ }, -/* 69 */ -/***/ 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); - }; - - -/***/ }, -/* 70 */ -/***/ function(module, exports) { - - module.exports = function divergence(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])); - } - return 2 * d; - }; - - -/***/ }, -/* 71 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 72 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 73 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 74 */ -/***/ function(module, exports) { - - 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]); - } - return 2 * Math.sqrt(1 - ans); - }; - - -/***/ }, -/* 75 */ -/***/ 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]; - } - return ans; - }; - - -/***/ }, -/* 76 */ -/***/ 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; - }; - - -/***/ }, -/* 77 */ -/***/ 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); - }; - - -/***/ }, -/* 78 */ -/***/ function(module, exports) { - - 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]); - } - return ans; - }; - - -/***/ }, -/* 79 */ -/***/ function(module, exports) { - - 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); - } - return ans; - }; - - -/***/ }, -/* 80 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 81 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 82 */ -/***/ 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; - }; - - -/***/ }, -/* 83 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 84 */ -/***/ function(module, exports) { - - 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); - }; - - -/***/ }, -/* 85 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, +/***/ }), /* 86 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 87 */ -/***/ function(module, exports) { - - 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]); - } - return d; - }; - - -/***/ }, -/* 88 */ -/***/ 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]); - } - return Math.sqrt(2 - 2 * ans); - }; - - -/***/ }, -/* 89 */ -/***/ function(module, exports) { - - 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)); - }; - - -/***/ }, -/* 90 */ -/***/ 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); - }; - - -/***/ }, -/* 91 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 92 */ -/***/ function(module, exports) { - - module.exports = function pearson(a, b) { - var i = 0, - ii = a.length, - d = 0; - for (; i < ii; i++) { - d += ((a[i] - b[i]) * (a[i] - b[i])) / b[i]; - } - return d; - }; - - -/***/ }, -/* 93 */ -/***/ 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]); - } - return 2 * d; - }; - - -/***/ }, -/* 94 */ -/***/ function(module, exports) { - - 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]); - } - return up / down; - }; - - -/***/ }, -/* 95 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 96 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 97 */ -/***/ function(module, exports) { - - 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]); - } - return d; - }; - - -/***/ }, -/* 98 */ -/***/ 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; - }; - - -/***/ }, -/* 99 */ -/***/ 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; - }; - - -/***/ }, -/* 100 */ -/***/ function(module, exports, __webpack_require__) { - - var tanimotoS = __webpack_require__(101); - - 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); - } - }; - - -/***/ }, -/* 101 */ -/***/ 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); - } - }; - - -/***/ }, -/* 102 */ -/***/ function(module, exports) { - - 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; - }; - - -/***/ }, -/* 103 */ -/***/ function(module, exports) { - - "use strict"; - - /** - * Function that creates the tree - * @param {Array } X - chemical shifts of the signal - * @param {Array } Y - intensity of the signal - * @param {number} from - the low limit of x - * @param {number} to - the top limit of x - * @param {number} minWindow - smallest range to accept in x - * @param {number} threshold - smallest range to accept in y - * @returns {{sum: number, center: number, left: {json}, right: {json}}} - * left and right have the same structure than the parent, or have a - * undefined value if are leafs - */ - function createTree (X, Y, from, to, minWindow, threshold) { - minWindow = minWindow || 0.16; - threshold = threshold || 0.01; - if ((to - from) < minWindow) - return undefined; - var sum = 0; - for (var i = 0; X[i] < to; i++) { - if (X[i] > from) - sum += Y[i]; - } - if (sum < threshold) { - return undefined; - } - var center = 0; - for (var j = 0; X[j] < to; j++) { - if (X[i] > from) - center += X[j] * Y[j]; - } - center = center / sum; - if (((center - from) < 10e-6) || ((to - center) < 10e-6)) return undefined; - if ((center - from) < (minWindow /4)) { - return createTree(X, Y, center, to, minWindow, threshold); - } - else { - if ((to - center) < (minWindow / 4)) { - return createTree(X, Y, from, center, minWindow, threshold); - } - else { - return { - 'sum': sum, - 'center': center, - 'left': createTree(X, Y, from, center, minWindow, threshold), - 'right': createTree(X, Y, center, to, minWindow, threshold) - }; - } - } - } - - /** - * Similarity between two nodes - * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node - * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node - * @param {number} alpha - weights the relative importance of intensity vs. shift match - * @param {number} beta - weights the relative importance of node matching and children matching - * @param {number} gamma - controls the attenuation of the effect of chemical shift differences - * @returns {number} similarity measure between tree nodes - */ - function S(a, b, alpha, beta, gamma) { - if (a === undefined || b === undefined) { - return 0; - } - else { - var C = (alpha*Math.min(a.sum, b.sum)/Math.max(a.sum, b.sum)+ (1-alpha)*Math.exp(-gamma*Math.abs(a.center - b.center))); - } - return beta*C + (1-beta)*(S(a.left, b.left, alpha, beta, gamma)+S(a.right, b.right, alpha, beta, gamma)); - } - - /** - * @type {number} alpha - weights the relative importance of intensity vs. shift match - * @type {number} beta - weights the relative importance of node matching and children matching - * @type {number} gamma - controls the attenuation of the effect of chemical shift differences - * @type {number} minWindow - smallest range to accept in x - * @type {number} threshold - smallest range to accept in y - */ - var defaultOptions = { - minWindow: 0.16, - threshold : 0.01, - alpha: 0.1, - beta: 0.33, - gamma: 0.001 - }; - - /** - * Builds a tree based in the spectra and compares this trees - * @param {{x: Array, y: Array}} A - first spectra to be compared - * @param {{x: Array, y: Array}} B - second spectra to be compared - * @param {number} from - the low limit of x - * @param {number} to - the top limit of x - * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options - * @returns {number} similarity measure between the spectra - */ - function tree(A, B, from, to, options) { - options = options || {}; - for (var o in defaultOptions) - if (!options.hasOwnProperty(o)) { - options[o] = defaultOptions[o]; - } - var Atree, Btree; - if (A.sum) - Atree = A; - else - Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold); - if (B.sum) - Btree = B; - else - Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold); - return S(Atree, Btree, options.alpha, options.beta, options.gamma); - } - - module.exports = { - calc: tree, - createTree: createTree - }; - -/***/ }, -/* 104 */ -/***/ 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; - }; - - -/***/ }, -/* 105 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - - exports.cosine = __webpack_require__(106); - exports.czekanowski = __webpack_require__(68); - exports.dice = __webpack_require__(107); - exports.intersection = __webpack_require__(108); - exports.jaccard = __webpack_require__(109); - exports.kulczynski = __webpack_require__(110); - exports.motyka = __webpack_require__(111); - exports.pearson = __webpack_require__(112); - exports.squaredChord = __webpack_require__(113); - exports.tanimoto = __webpack_require__(101); - - -/***/ }, -/* 106 */ -/***/ 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)); - }; - - -/***/ }, -/* 107 */ -/***/ function(module, exports, __webpack_require__) { - - var diceD = __webpack_require__(69); - - module.exports = function dice(a, b) { - return 1 - diceD(a,b); - }; - - -/***/ }, -/* 108 */ -/***/ function(module, exports, __webpack_require__) { - - var intersectionD = __webpack_require__(76); - - module.exports = function intersection(a, b) { - return 1 - intersectionD(a,b); - }; - - -/***/ }, -/* 109 */ -/***/ function(module, exports, __webpack_require__) { - - var jaccardD = __webpack_require__(77); - - module.exports = function jaccard(a, b) { - return 1 - jaccardD(a, b); - }; - - -/***/ }, -/* 110 */ -/***/ function(module, exports, __webpack_require__) { - - var kulczynskiD = __webpack_require__(82); - - module.exports = function kulczynski(a, b) { - return 1 / kulczynskiD(a, b); - }; - - -/***/ }, -/* 111 */ -/***/ function(module, exports, __webpack_require__) { - - var motykaD = __webpack_require__(90); - - module.exports = function motyka(a, b) { - return 1 - motykaD(a,b); - }; - - -/***/ }, -/* 112 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var stat=__webpack_require__(3).array; - var cosine=__webpack_require__(106); - - module.exports = function pearson(a, b) { - var avgA=stat.mean(a); - var avgB=stat.mean(b); - - var newA=new Array(a.length); - var newB=new Array(b.length); - for (var i=0; i} 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; - } - else { - C = [2, -1, -2, -1, 2]; - norm = 7; - } - } - else { - var J = Matrix.ones(options.windowSize, options.polynomial + 1); - var inic = -(options.windowSize - 1) / 2; - for (var i = 0; i < J.length; i++) { - for (var j = 0; j < J[i].length; j++) { - if ((inic + 1 !== 0) || (j !== 0)) - J[i][j] = Math.pow((inic + i), j); - } - } - var Jtranspose = J.transposeView(); - var Jinv = (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; - - -/***/ }, -/* 115 */ -/***/ function(module, exports) { - - 'use strict'; - - var hasOwn = Object.prototype.hasOwnProperty; - var toStr = Object.prototype.toString; - - var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } - - return toStr.call(arr) === '[object Array]'; - }; - - 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 = {}; - } - - 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]; - - // 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); - - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - target[name] = copy; - } - } - } - } - } - - // Return the modified object - return target; - }; - - - -/***/ }, -/* 116 */ -/***/ function(module, exports, __webpack_require__) { - - //Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007 - var extend = __webpack_require__(115); - var stat = __webpack_require__(117); - - 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)') - - - if (options.windowSize>data.length) - throw new RangeError('Window size is higher than the data length '+options.windowSize+">"+data.length); - if ((options.derivative < 0) || !(Number.isInteger(options.derivative))) - throw new RangeError('Derivative should be a positive integer'); - if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial))) - throw new RangeError('Polynomial should be a positive integer'); - if (options.polynomial >= 6) - console.warn('You should not use polynomial grade higher than 5 if you are' + - ' not sure that your data arises from such a model. Possible polynomial oscillation problems'); - - var windowSize = options.windowSize; - - var half = Math.floor(windowSize/2); - var np = data.length; - var ans = new Array(np); - var weights = fullWeights(windowSize,options.polynomial,options.derivative); - var hs = 0; - var constantH = true; - if( Object.prototype.toString.call( h ) === '[object Array]' ) { - constantH = false; - } - else{ - hs = Math.pow(h, options.derivative); - } - //console.log("Constant h: "+constantH); - //For the borders - for(var i=0;i=0 && i < h.length-1){ - hs+= (h[i+1]-h[i]); - count++; - } - } - return Math.pow(hs/count,derivative); - } - - function GramPoly(i,m,k,s){ - var Grampoly = 0; - if(k>0){ - Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) + - s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s); - } - else{ - if(k==0&&s==0){ - Grampoly=1; - } - else{ - Grampoly=0; - } - } - //console.log(Grampoly); - return Grampoly; - } - - function GenFact(a,b){ - var gf=1; - if(a>=b){ - for(var j=a-b+1;j<=a;j++){ - gf*=j; - } - } - return gf; - } - - function Weight(i,t,m,n,s){ - var sum=0; - for(var k=0;k<=n;k++){ - //console.log(k); - sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s) - } - return sum; - } - - /** - * - * @param m Number of points - * @param n Polynomial grade - * @param s Derivative - */ - function fullWeights(m,n,s){ - var weights = new Array(m); - var np = Math.floor(m/2); - for(var t=-np;t<=np;t++){ - weights[t+np] = new Array(m); - for(var j=-np;j<=np;j++){ - weights[t+np][j+np]=Weight(j,t,np,n,s); - } - } - return weights; - } - - /*function entropy(data,h,options){ - var trend = SavitzkyGolay(data,h,trendOptions); - var copy = new Array(data.length); - var sum = 0; - var max = 0; - for(var i=0;i 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; - }; - - -/***/ }, -/* 119 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - var arrayStat = __webpack_require__(118); - - // https://github.com/accord-net/framework/blob/development/Sources/Accord.Statistics/Tools.cs - - function entropy(matrix, eps) { - if (typeof(eps) === 'undefined') { - eps = 0; - } - var sum = 0, - l1 = matrix.length, - l2 = matrix[0].length; - for (var i = 0; i < l1; i++) { - for (var j = 0; j < l2; j++) { - sum += matrix[i][j] * Math.log(matrix[i][j] + eps); - } - } - return -sum; - } - - function mean(matrix, dimension) { - if (typeof(dimension) === 'undefined') { - dimension = 0; - } - var rows = matrix.length, - cols = matrix[0].length, - theMean, N, i, j; - - if (dimension === -1) { - theMean = [0]; - N = rows * cols; - for (i = 0; i < rows; i++) { - for (j = 0; j < cols; j++) { - theMean[0] += matrix[i][j]; - } - } - theMean[0] /= N; - } else if (dimension === 0) { - theMean = new Array(cols); - N = rows; - for (j = 0; j < cols; j++) { - theMean[j] = 0; - for (i = 0; i < rows; i++) { - theMean[j] += matrix[i][j]; - } - theMean[j] /= N; - } - } else if (dimension === 1) { - theMean = new Array(rows); - N = cols; - for (j = 0; j < rows; j++) { - theMean[j] = 0; - for (i = 0; i < cols; i++) { - theMean[j] += matrix[j][i]; - } - theMean[j] /= N; - } - } else { - throw new Error('Invalid dimension'); - } - return theMean; - } - - function standardDeviation(matrix, means, unbiased) { - var vari = variance(matrix, means, unbiased), l = vari.length; - for (var i = 0; i < l; i++) { - vari[i] = Math.sqrt(vari[i]); - } - return vari; - } - - function variance(matrix, means, unbiased) { - if (typeof(unbiased) === 'undefined') { - unbiased = true; - } - means = means || mean(matrix); - var rows = matrix.length; - if (rows === 0) return []; - var cols = matrix[0].length; - var vari = new Array(cols); - - for (var j = 0; j < cols; j++) { - var sum1 = 0, sum2 = 0, x = 0; - for (var i = 0; i < rows; i++) { - x = matrix[i][j] - means[j]; - sum1 += x; - sum2 += x * x; - } - if (unbiased) { - vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1); - } else { - vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows; - } - } - return vari; - } - - function median(matrix) { - var rows = matrix.length, cols = matrix[0].length; - var medians = new Array(cols); - - for (var i = 0; i < cols; i++) { - var data = new Array(rows); - for (var j = 0; j < rows; j++) { - data[j] = matrix[j][i]; - } - data.sort(); - var N = data.length; - if (N % 2 === 0) { - medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5; - } else { - medians[i] = data[Math.floor(N / 2)]; - } - } - return medians; - } - - function mode(matrix) { - var rows = matrix.length, - cols = matrix[0].length, - modes = new Array(cols), - i, j; - for (i = 0; i < cols; i++) { - var itemCount = new Array(rows); - for (var k = 0; k < rows; k++) { - itemCount[k] = 0; - } - var itemArray = new Array(rows); - var count = 0; - - for (j = 0; j < rows; j++) { - var index = itemArray.indexOf(matrix[j][i]); - if (index >= 0) { - itemCount[index]++; - } else { - itemArray[count] = matrix[j][i]; - itemCount[count] = 1; - count++; - } - } - - var maxValue = 0, maxIndex = 0; - for (j = 0; j < count; j++) { - if (itemCount[j] > maxValue) { - maxValue = itemCount[j]; - maxIndex = j; - } - } - - modes[i] = itemArray[maxIndex]; - } - return modes; - } - - function skewness(matrix, unbiased) { - if (typeof(unbiased) === 'undefined') unbiased = true; - var means = mean(matrix); - var n = matrix.length, l = means.length; - var skew = new Array(l); - - for (var j = 0; j < l; j++) { - var s2 = 0, s3 = 0; - for (var i = 0; i < n; i++) { - var dev = matrix[i][j] - means[j]; - s2 += dev * dev; - s3 += dev * dev * dev; - } - - var m2 = s2 / n; - var m3 = s3 / n; - var g = m3 / Math.pow(m2, 3 / 2); - - if (unbiased) { - var a = Math.sqrt(n * (n - 1)); - var b = n - 2; - skew[j] = (a / b) * g; - } else { - skew[j] = g; - } - } - return skew; - } - - function kurtosis(matrix, unbiased) { - if (typeof(unbiased) === 'undefined') unbiased = true; - var means = mean(matrix); - var n = matrix.length, m = matrix[0].length; - var kurt = new Array(m); - - for (var j = 0; j < m; j++) { - var s2 = 0, s4 = 0; - for (var i = 0; i < n; i++) { - var dev = matrix[i][j] - means[j]; - s2 += dev * dev; - s4 += dev * dev * dev * dev; - } - var m2 = s2 / n; - var m4 = s4 / n; - - if (unbiased) { - var v = s2 / (n - 1); - var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3)); - var b = s4 / (v * v); - var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3)); - kurt[j] = a * b - 3 * c; - } else { - kurt[j] = m4 / (m2 * m2) - 3; - } - } - return kurt; - } - - function standardError(matrix) { - var samples = matrix.length; - var standardDeviations = standardDeviation(matrix), l = standardDeviations.length; - var standardErrors = new Array(l); - var sqrtN = Math.sqrt(samples); - - for (var i = 0; i < l; i++) { - standardErrors[i] = standardDeviations[i] / sqrtN; - } - return standardErrors; - } - - function covariance(matrix, dimension) { - return scatter(matrix, undefined, dimension); - } - - function scatter(matrix, divisor, dimension) { - if (typeof(dimension) === 'undefined') { - dimension = 0; - } - if (typeof(divisor) === 'undefined') { - if (dimension === 0) { - divisor = matrix.length - 1; - } else if (dimension === 1) { - divisor = matrix[0].length - 1; - } - } - var means = mean(matrix, dimension), - rows = matrix.length; - if (rows === 0) { - return [[]]; - } - var cols = matrix[0].length, - cov, i, j, s, k; - - if (dimension === 0) { - cov = new Array(cols); - for (i = 0; i < cols; i++) { - cov[i] = new Array(cols); - } - for (i = 0; i < cols; i++) { - for (j = i; j < cols; j++) { - s = 0; - for (k = 0; k < rows; k++) { - s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); - } - s /= divisor; - cov[i][j] = s; - cov[j][i] = s; - } - } - } else if (dimension === 1) { - cov = new Array(rows); - for (i = 0; i < rows; i++) { - cov[i] = new Array(rows); - } - for (i = 0; i < rows; i++) { - for (j = i; j < rows; j++) { - s = 0; - for (k = 0; k < cols; k++) { - s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); - } - s /= divisor; - cov[i][j] = s; - cov[j][i] = s; - } - } - } else { - throw new Error('Invalid dimension'); - } - - return cov; - } - - function correlation(matrix) { - var means = mean(matrix), - standardDeviations = standardDeviation(matrix, true, means), - scores = zScores(matrix, means, standardDeviations), - rows = matrix.length, - cols = matrix[0].length, - i, j; - - var cor = new Array(cols); - for (i = 0; i < cols; i++) { - cor[i] = new Array(cols); - } - for (i = 0; i < cols; i++) { - for (j = i; j < cols; j++) { - var c = 0; - for (var k = 0, l = scores.length; k < l; k++) { - c += scores[k][j] * scores[k][i]; - } - c /= rows - 1; - cor[i][j] = c; - cor[j][i] = c; - } - } - return cor; - } - - function zScores(matrix, means, standardDeviations) { - means = means || mean(matrix); - if (typeof(standardDeviations) === 'undefined') standardDeviations = standardDeviation(matrix, true, means); - return standardize(center(matrix, means, false), standardDeviations, true); - } - - function center(matrix, means, inPlace) { - means = means || mean(matrix); - var result = matrix, - l = matrix.length, - i, j, jj; - - if (!inPlace) { - result = new Array(l); - for (i = 0; i < l; i++) { - result[i] = new Array(matrix[i].length); - } - } - - for (i = 0; i < l; i++) { - var row = result[i]; - for (j = 0, jj = row.length; j < jj; j++) { - row[j] = matrix[i][j] - means[j]; - } - } - return result; - } - - function standardize(matrix, standardDeviations, inPlace) { - if (typeof(standardDeviations) === 'undefined') standardDeviations = standardDeviation(matrix); - var result = matrix, - l = matrix.length, - i, j, jj; - - if (!inPlace) { - result = new Array(l); - for (i = 0; i < l; i++) { - result[i] = new Array(matrix[i].length); - } - } - - for (i = 0; i < l; i++) { - var resultRow = result[i]; - var sourceRow = matrix[i]; - for (j = 0, jj = resultRow.length; j < jj; j++) { - if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) { - resultRow[j] = sourceRow[j] / standardDeviations[j]; - } - } - } - return result; - } - - function weightedVariance(matrix, weights) { - var means = mean(matrix); - var rows = matrix.length; - if (rows === 0) return []; - var cols = matrix[0].length; - var vari = new Array(cols); - - for (var j = 0; j < cols; j++) { - var sum = 0; - var a = 0, b = 0; - - for (var i = 0; i < rows; i++) { - var z = matrix[i][j] - means[j]; - var w = weights[i]; +/***/ (function(module, exports) { - sum += w * (z * z); - b += w; - a += w * w; - } +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]); + } + return ans; +}; - vari[j] = sum * (b / (b * b - a)); - } - return vari; - } +/***/ }), +/* 87 */ +/***/ (function(module, exports) { - function weightedMean(matrix, weights, dimension) { - if (typeof(dimension) === 'undefined') { - dimension = 0; - } - var rows = matrix.length; - if (rows === 0) return []; - var cols = matrix[0].length, - means, i, ii, j, w, row; - - if (dimension === 0) { - means = new Array(cols); - for (i = 0; i < cols; i++) { - means[i] = 0; - } - for (i = 0; i < rows; i++) { - row = matrix[i]; - w = weights[i]; - for (j = 0; j < cols; j++) { - means[j] += row[j] * w; - } - } - } else if (dimension === 1) { - means = new Array(rows); - for (i = 0; i < rows; i++) { - means[i] = 0; - } - for (j = 0; j < rows; j++) { - row = matrix[j]; - w = weights[j]; - for (i = 0; i < cols; i++) { - means[j] += row[i] * w; - } - } - } else { - throw new Error('Invalid dimension'); - } - - var weightSum = arrayStat.sum(weights); - if (weightSum !== 0) { - for (i = 0, ii = means.length; i < ii; i++) { - means[i] /= weightSum; - } - } - return means; - } +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); + } + return ans; +}; - function weightedCovariance(matrix, weights, means, dimension) { - dimension = dimension || 0; - means = means || weightedMean(matrix, weights, dimension); - var s1 = 0, s2 = 0; - for (var i = 0, ii = weights.length; i < ii; i++) { - s1 += weights[i]; - s2 += weights[i] * weights[i]; - } - var factor = s1 / (s1 * s1 - s2); - return weightedScatter(matrix, weights, means, factor, dimension); - } - function weightedScatter(matrix, weights, means, factor, dimension) { - dimension = dimension || 0; - means = means || weightedMean(matrix, weights, dimension); - if (typeof(factor) === 'undefined') { - factor = 1; - } - var rows = matrix.length; - if (rows === 0) { - return [[]]; - } - var cols = matrix[0].length, - cov, i, j, k, s; - - if (dimension === 0) { - cov = new Array(cols); - for (i = 0; i < cols; i++) { - cov[i] = new Array(cols); - } - for (i = 0; i < cols; i++) { - for (j = i; j < cols; j++) { - s = 0; - for (k = 0; k < rows; k++) { - s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); - } - cov[i][j] = s * factor; - cov[j][i] = s * factor; - } - } - } else if (dimension === 1) { - cov = new Array(rows); - for (i = 0; i < rows; i++) { - cov[i] = new Array(rows); - } - for (i = 0; i < rows; i++) { - for (j = i; j < rows; j++) { - s = 0; - for (k = 0; k < cols; k++) { - s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); - } - cov[i][j] = s * factor; - cov[j][i] = s * factor; - } - } - } else { - throw new Error('Invalid dimension'); - } - - return cov; - } +/***/ }), +/* 88 */ +/***/ (function(module, exports) { - module.exports = { - entropy: entropy, - mean: mean, - standardDeviation: standardDeviation, - variance: variance, - median: median, - mode: mode, - skewness: skewness, - kurtosis: kurtosis, - standardError: standardError, - covariance: covariance, - scatter: scatter, - correlation: correlation, - zScores: zScores, - center: center, - standardize: standardize, - weightedVariance: weightedVariance, - weightedMean: weightedMean, - weightedCovariance: weightedCovariance, - weightedScatter: weightedScatter - }; - - -/***/ }, -/* 120 */ -/***/ function(module, exports, __webpack_require__) { - - const HashTable = __webpack_require__(11); - - 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]); - } - } - } - } else { - this._init(rows, columns, new HashTable(options), options.threshold); - } - } - - _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; - } - - 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 copy; - } - - 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 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; - } - - 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 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; - } - } +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; +}; - 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%(); - }) - `; - - var operators = [ - // Arithmetic operators - ['+', 'add'], - ['-', 'sub', 'subtract'], - ['*', 'mul', 'multiply'], - ['/', 'div', 'divide'], - ['%', 'mod', 'modulus'], - // Bitwise operators - ['&', 'and'], - ['|', 'or'], - ['^', 'xor'], - ['<<', 'leftShift'], - ['>>', 'signPropagatingRightShift'], - ['>>>', 'rightShift', 'zeroFillRightShift'] - ]; - - for (var operator of operators) { - for (var i = 1; i < operator.length; i++) { - SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {name: operator[i], op: operator[0]})); - SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {name: operator[i] + 'S', op: operator[0]})); - SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {name: operator[i] + 'M', op: operator[0]})); - - SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {name: operator[i]})); - } - } - 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) { - 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]})); - } - } +/***/ }), +/* 89 */ +/***/ (function(module, exports) { - function fillTemplateFunction(template, values) { - for (var i in values) { - template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]); - } - return template; - } +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; +}; -/***/ }, -/* 121 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var LM = __webpack_require__(122); - var math = LM.Matrix.algebra; - var Matrix = __webpack_require__(14); - - /** - * 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]; - } - } - - } - - //} - } - 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; - } +/***/ }), +/* 101 */ +/***/ (function(module, exports) { - function sizeException(nbPoints) { - return new RangeError("Not enough points to perform the optimization: "+nbPoints +"< 3"); - } +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; +}; - 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; -/***/ }, -/* 122 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 102 */ +/***/ (function(module, exports) { - 'use strict'; +module.exports = function sorensen(a, b) { + var ii = a.length, + up = 0, + down = 0; + for (var i = 0; i < ii ; i++) { + up += Math.abs(a[i] - b[i]); + down += a[i] + b[i]; + } + return up / down; +}; - module.exports = __webpack_require__(123); - module.exports.Matrix = __webpack_require__(14); - module.exports.Matrix.algebra = __webpack_require__(124); +/***/ }), +/* 103 */ +/***/ (function(module, exports) { -/***/ }, -/* 123 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * Created by acastillo on 8/5/15. - */ - var Matrix = __webpack_require__(14); - var math = __webpack_require__(124); - - 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 - - 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 = { - - 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 - - var iteration = 0; // iteration counter - //func_calls = 0; // running count of function evaluations - - 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); - - - if (t.length != y_dat.length) { - console.log('lm.m error: the length of t must equal the length of y_dat'); - - 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; - } - } - - 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 ]; - - 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 - - if ( tensor_parameter && prnt == 3 ) prnt = 2; - - - 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 - - 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; - } - - // 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 - - // --- 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; - - /*if nargout > 2 // standard error of parameters - covar = inv(JtWJ); - sigma_p = sqrt(diag(covar)); - end - - 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 - - if nargout > 4 // parameter correlation matrix - corr = covar ./ [sigma_p*sigma_p']; - end - - if nargout > 5 // coefficient of multiple determination - R_sq = corrcoef([y_dat y_hat]); - R_sq = R_sq(1,2).^2; - end - - if nargout > 6 // convergence history - cvg_hst = cvg_hst(1:iteration,:); - end*/ - - // endfunction # ---------------------------------------------------------- LM - - return { p:p, X2:X2}; - }, - - 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 - - // 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. - - 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); - - 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 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]; - } - - } // central difference, additional func call - } - - p[j] = ps[j]; // restore p(j) - - } - //console.log("lm_FD_J: "+ JSON.stringify(J)); - return J; - - }, - - // 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)); - - //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 - }, - - 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. - - - var Npnt = y_dat.length; // number of data points - var Npar = p.length; // number of parameters - - dp = dp || 0.001; - - - //var JtWJ = new Matrix.zeros(Npar); - //var JtWdy = new Matrix.zeros(Npar,1); - - 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); - - //console.log(weight_sq); - - var JtWJ = math.multiply(Jt, math.dotMultiply(J,math.multiply(weight_sq, Matrix.ones(1,Npar)))); - - //JtWdy = J' * ( weight_sq .* delta_y ); - var JtWdy = math.multiply(Jt, math.dotMultiply(weight_sq,delta_y)); - - - return {JtWJ:JtWJ,JtWdy:JtWdy,Chi_sq:Chi_sq,y_hat:y_hat,J:J}; - // endfunction # ------------------------------------------------------ LM_MATX - } - - - - }; - - module.exports = LM; - -/***/ }, -/* 124 */ -/***/ function(module, exports, __webpack_require__) { +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]); + } + return d; +}; - /** - * Created by acastillo on 8/24/15. - */ - /** - * Non in-place function definitions, compatible with mathjs code * - */ - 'use strict'; +/***/ }), +/* 104 */ +/***/ (function(module, exports) { - var Matrix = __webpack_require__(14); +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; +}; - function matrix(A,B){ - return new Matrix(A,B); - } - function ones(rows, cols){ - return Matrix.ones(rows,cols); - } +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { + +var tanimotoS = __webpack_require__(31); + +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); + } +}; + + +/***/ }), +/* 106 */ +/***/ (function(module, exports) { - function eye(rows, cols){ - return Matrix.eye(rows, cols); - } +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; +}; - function zeros(rows, cols){ - return Matrix.zeros(rows, cols); - } - function random(rows, cols){ - return Matrix.rand(rows,cols); - } +/***/ }), +/* 107 */ +/***/ (function(module, exports) { - function transpose(A){ - if(typeof A == 'number') - return A; - var result = A.clone(); - return result.transpose(); - } +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; +}; - 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); +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { - } +"use strict"; - 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); +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 result = A.clone(); - if(typeof B === 'number') - result.mul(B); - else - result = result.mmul(B); +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { - if(result.rows==1&&result.columns==1) - return result[0][0]; - else - return result; +var diceD = __webpack_require__(23); - } +module.exports = function dice(a, b) { + return 1 - diceD(a,b); +}; - function dotMultiply(A, B){ - var result = A.clone(); - return result.mul(B); - } - function dotDivide(A, B){ - var result = A.clone(); - return result.div(B); - } +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { - 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; - } +var intersectionD = __webpack_require__(24); - 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; - } +module.exports = function intersection(a, b) { + return 1 - intersectionD(a,b); +}; - 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; - } +/***/ }), +/* 111 */ +/***/ (function(module, exports, __webpack_require__) { - 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; - } +var jaccardD = __webpack_require__(25); - 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; - } +module.exports = function jaccard(a, b) { + return 1 - jaccardD(a, b); +}; - 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); - } +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { - function inv(A){ - if(typeof A ==="number") - return 1/A; - return A.inverse(); - } +var kulczynskiD = __webpack_require__(26); - 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 - }; - - -/***/ }, -/* 125 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const Matrix = __webpack_require__(14); - const EVD = Matrix.DC.EVD; - const SVD = Matrix.DC.SVD; - const Stat = __webpack_require__(3).matrix; - const mean = Stat.mean; - const stdev = Stat.standardDeviation; - - const defaultOptions = { - isCovarianceMatrix: false, - center: true, - scale: false - }; - - /** - * Creates new PCA (Principal Component Analysis) from the dataset - * @param {Matrix} dataset - dataset or covariance matrix - * @param {Object} options - * @param {boolean} [options.isCovarianceMatrix=false] - true if the dataset is a covariance matrix - * @param {boolean} [options.center=true] - should the data be centered (subtract the mean) - * @param {boolean} [options.scale=false] - should the data be scaled (divide by the standard deviation) - * */ - 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; - } - - options = Object.assign({}, defaultOptions, options); - - this.center = false; - this.scale = false; - this.means = null; - this.stdevs = null; - - if (options.isCovarianceMatrix) { // user provided a covariance matrix instead of dataset - this._computeFromCovarianceMatrix(dataset); - return; - } - - 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 - }); - - this.U = svd.rightSingularVectors; - - const singularValues = svd.diagonal; - const eigenvalues = new Array(singularValues.length); - for (var i = 0; i < singularValues.length; i++) { - eigenvalues[i] = singularValues[i] * singularValues[i] / (dataset.length - 1); - } - this.S = eigenvalues; - } - } - - /** - * Load a PCA model from JSON - * @param {Object} model - * @return {PCA} - */ - 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); - } - - /** - * Returns the proportion of variance for each component - * @return {[number]} - */ - getExplainedVariance() { - var sum = 0; - for (var i = 0; i < this.S.length; i++) { - sum += this.S[i]; - } - return this.S.map(value => value / sum); - } - - /** - * Returns the cumulative proportion of variance - * @return {[number]} - */ - getCumulativeVariance() { - var explained = this.getExplainedVariance(); - for (var i = 1; i < explained.length; i++) { - explained[i] += explained[i - 1]; - } - return explained; - } - - /** - * Returns the Eigenvectors of the covariance matrix - * @returns {Matrix} - */ - getEigenvectors() { - return this.U; - } - - /** - * Returns the Eigenvalues (on the diagonal) - * @returns {[number]} - */ - getEigenvalues() { - return this.S; - } - - /** - * Returns the standard deviations of the principal components - * @returns {[number]} - */ - getStandardDeviations() { - return this.S.map(x => Math.sqrt(x)); - } - - /** - * 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, - }; - } - - _adjust(dataset, options) { - this.center = !!options.center; - this.scale = !!options.scale; - - dataset = new Matrix(dataset); - - if (this.center) { - const means = mean(dataset); - const stdevs = this.scale ? stdev(dataset, means, true) : null; - this.means = means; - dataset.subRowVector(means); - if (this.scale) { - for (var i = 0; i < stdevs.length; i++) { - if (stdevs[i] === 0) { - throw new RangeError('Cannot scale the dataset (standard deviation is zero at index ' + i); - } - } - this.stdevs = stdevs; - dataset.divRowVector(stdevs); - } - } - - return dataset; - } - - _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(); - } - } +module.exports = function kulczynski(a, b) { + return 1 / kulczynskiD(a, b); +}; - module.exports = PCA; +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { -/***/ }, -/* 126 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const measures = __webpack_require__(127); - - 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; - - const predP = []; - - if (options.all) { - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { - predP.push({ - pred: prediction[i][j], - targ: target[i][j] - }); - } - } - } else { - if (rows < 3 || rows !== columns) { - throw new Error('When "all" option is false, the prediction matrix must be square and have at least 3 columns'); - } - for (var i = 0; i < rows - 1; i++) { - for (var j = i + 1; j < columns; j++) { - predP.push({ - pred: prediction[i][j], - targ: target[i][j] - }); - } - } - } - - 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]; - - var nPos = 0; - var nNeg = 0; - - var currentPred = predP[0].pred; - var nTp = 0; - var nFp = 0; - for (var i = 0; i < predP.length; i++) { - if (predP[i].pred !== currentPred) { - cutoffs.push(currentPred); - fp.push(nFp); - tp.push(nTp); - currentPred = predP[i].pred; - } - if (predP[i].targ) { - nPos++; - nTp++; - } else { - nNeg++; - nFp++; - } - } - cutoffs.push(currentPred); - fp.push(nFp); - tp.push(nTp); - - const l = cutoffs.length; - const fn = this.fn = new Array(l); - const tn = this.tn = new Array(l); - const nPosPred = this.nPosPred = new Array(l); - const nNegPred = this.nNegPred = new Array(l); - - for (var i = 0; i < l; i++) { - fn[i] = nPos - tp[i]; - tn[i] = nNeg - fp[i]; - - nPosPred[i] = tp[i] + fp[i]; - nNegPred[i] = tn[i] + fn[i]; - } - - 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); - } - - /** - * 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; - } - - /** - * 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; - } - - getDistribution(options) { - options = options || {}; - var cutLength = this.cutoffs.length; - var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100; - var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100; - var interval = options.interval || Math.floor(((cutHigh - cutLow) / 20 * 10000000) - 1) / 10000000; // Trick to avoid the precision problem of float numbers - - var xLabels = []; - var interValues = []; - var intraValues = []; - var interCumPercent = []; - var intraCumPercent = []; - - var nTP = this.tp[cutLength - 1], currentTP = 0; - var nFP = this.fp[cutLength - 1], currentFP = 0; - - for (var i = cutLow, j = (cutLength - 1); i <= cutHigh; i += interval) { - while (this.cutoffs[j] < i) - j--; - - xLabels.push(i); - - var thisTP = nTP - currentTP - this.tp[j]; - var thisFP = nFP - currentFP - this.fp[j]; - - currentTP += thisTP; - currentFP += thisFP; - - interValues.push(thisFP); - intraValues.push(thisTP); - - interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100); - intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100); - } - - return { - xLabels: xLabels, - interValues: interValues, - intraValues: intraValues, - interCumPercent: interCumPercent, - intraCumPercent: intraCumPercent - }; - } - } +var motykaD = __webpack_require__(27); - Performance.names = { - acc: 'Accuracy', - err: 'Error rate', - fpr: 'False positive rate', - tpr: 'True positive rate', - fnr: 'False negative rate', - tnr: 'True negative rate', - ppv: 'Positive predictive value', - npv: 'Negative predictive value', - pcfall: 'Prediction-conditioned fallout', - pcmiss: 'Prediction-conditioned miss', - lift: 'Lift value', - rpp: 'Rate of positive predictions', - rnp: 'Rate of negative predictions', - threshold: 'Threshold' - }; - - module.exports = Performance; - - -/***/ }, -/* 127 */ -/***/ function(module, exports) { - - '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); - } - 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)); - } - return result; - }; - - // 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; - }; - - // 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; - }; - - // 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; - }; - - // 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; - }; - - // 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; - }; - - // 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; - }; - - // Prediction conditioned fallout - exports.pcfall = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1; - } - return result; - }; - - // Prediction conditioned miss - exports.pcmiss = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1; - } - return result; - }; - - // Lift value - exports.lift = pred => { - const l = pred.cutoffs.length; - const result = new Array(l); - 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; - }; - - // 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; - }; - - // 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; - }; - - -/***/ }, -/* 128 */ -/***/ function(module, exports) { +module.exports = function motyka(a, b) { + return 1 - motykaD(a,b); +}; - "use strict"; - Object.defineProperty(exports, "__esModule", { - value: true - }); +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { - 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; }; })(); +"use strict"; - 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; +var stat=__webpack_require__(2).array; +var cosine=__webpack_require__(29); - function multiply_uint32(n, m) { - n >>>= 0; - m >>>= 0; - var nlo = n & 0xffff; - var nhi = n - nlo; - return (nhi * m >>> 0) + nlo * m >>> 0; - } +module.exports = function pearson(a, b) { + var avgA=stat.mean(a); + var avgB=stat.mean(b); - var XSadd = (function () { - function XSadd() { - var seed = arguments.length <= 0 || arguments[0] === undefined ? Date.now() : arguments[0]; - - _classCallCheck(this, XSadd); - - 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 newA=new Array(a.length); + var newB=new Array(b.length); + for (var i=0; i>> 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"]; + return cosine(newA, newB); +}; -/***/ }, -/* 129 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const ConfusionMatrix = __webpack_require__(130); - - const CV = {}; - const combinations = __webpack_require__(131); - - /** - * 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'); - } - } +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { - function initMatrix(rows, columns) { - return new Array(rows).fill(0).map(() => new Array(columns).fill(0)); - } +var squaredChordD = __webpack_require__(28); - function getDistinct(arr) { - var s = new Set(); - for (let i = 0; i < arr.length; i++) { - s.add(arr[i]); - } - return Array.from(s); - } +module.exports = function squaredChord(a, b) { + return 1 - squaredChordD(a, b); +}; - 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; +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -/***/ }, -/* 130 */ -/***/ function(module, exports) { - - 'use strict'; - - /** - * 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'); - } - if (labels.length !== matrix.length) { - throw new Error('Confusion matrix and labels should have the same length'); - } - this.labels = labels; - this.matrix = matrix; - - } - - /** - * 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]; - } - } - - return correct / (correct + incorrect); - } - - /** - * 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]; - } - } - return predicted; - } - } - module.exports = ConfusionMatrix; +var Layer = __webpack_require__(32); +class OutputLayer extends Layer { + constructor(options) { + super(options); -/***/ }, -/* 131 */ -/***/ function(module, exports) { - - 'use strict'; - const defaultOptions = { - mode: 'index' - }; - - 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; - - // 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; - } - - // 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 { - if (i === p[0]) { - return 0; - } else { - p[j] = p[i]; - z = p[i] - 1; - p[i] = 0; - x = j - 1; - y = i - 1; - } - } - } - return 1; - } - - 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 { - throw new Error('Invalid mode'); - } - }; - - -/***/ }, -/* 132 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - const Kernel = __webpack_require__(45); - const stat = __webpack_require__(3).array; - - var defaultOptions = { - C: 1, - tol: 1e-4, - maxPasses: 10, - maxIterations: 10000, - kernel: 'linear', - alphaTol: 1e-6, - random: Math.random, - whitening: true - }; - - /** - * Simplified version of the Sequential Minimal Optimization algorithm for training - * support vector machines - * @param {{Object}} options - SVM options - * @param {Number} [options.C=1] - regularization parameter - * @param {Number} [options.tol=1e-4] - numerical tolerance - * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors - * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing - * @param {Number} [options.maxIterations=10000] - max number of iterations - * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels} - * @param {Function} [options.random=Math.random] - custom random number generator - * @constructor - */ - function SVM(options) { - this.options = Object.assign({}, defaultOptions, options); - - this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions); - this.b = 0; - } + this.activationFunction = function (i, j) { + this[i][j] = Math.exp(this[i][j]); + }; + } - /** - * Train the SVM model - * @param {Array >} features - training data features - * @param {Array } labels - training data labels in the domain {1,-1} - */ - SVM.prototype.train = function (features, labels) { - if (features.length !== labels.length) { - throw new Error('Features and labels should have the same length'); - } - if (features.length < 2) { - throw new Error('Cannot train with less than 2 observations'); - } - this._trained = false; - this._loaded = false; - this.N = labels.length; - this.D = features[0].length; - if (this.options.whitening) { - this.X = new Array(this.N); - for (var i = 0; i < this.N; i++) { - this.X[i] = new Array(this.D); - } - this.minMax = new Array(this.D); - // Apply normalization and keep normalization parameters - for (var j = 0; j < this.D; j++) { - var d = new Array(this.N); - for (i = 0; i < this.N; i++) { - d[i] = features[i][j]; - } - this.minMax[j] = stat.minMax(d); - for (i = 0; i < this.N; i++) { - this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min); - } - } - } else { - this.X = features; - } - this.Y = labels; - this.b = 0; - this.W = undefined; - - var kernel = this.kernel.compute(this.X); - var m = labels.length; - var alpha = new Array(m).fill(0); - this.alphas = alpha; - for (var a = 0; a < m; a++) - alpha[a] = 0; - - var b1 = 0, - b2 = 0, - iter = 0, - passes = 0, - Ei = 0, - Ej = 0, - ai = 0, - aj = 0, - L = 0, - H = 0, - eta = 0; - - while (passes < this.options.maxPasses && iter < this.options.maxIterations) { - var numChange = 0; - for (i = 0; i < m; i++) { - Ei = this._marginOnePrecomputed(i, kernel) - labels[i]; - if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) { - j = i; - while (j === i) j = Math.floor(this.options.random() * m); - Ej = this._marginOnePrecomputed(j, kernel) - labels[j]; - ai = alpha[i]; - aj = alpha[j]; - if (labels[i] === labels[j]) { - L = Math.max(0, ai + aj - this.options.C); - H = Math.min(this.options.C, ai + aj); - } else { - L = Math.max(0, aj - ai); - H = Math.min(this.options.C, this.options.C + aj + ai); - } - if (Math.abs(L - H) < 1e-4) continue; - - eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j]; - if (eta >= 0) continue; - var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta; - if (newaj > H) - newaj = H; - else if (newaj < L) - newaj = L; - if (Math.abs(aj - newaj) < 10e-4) continue; - alpha[j] = newaj; - alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj); - b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j]; - b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j]; - this.b = (b1 + b2) / 2; - if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1; - if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2; - numChange += 1; - } - } - iter++; - if (numChange === 0) - passes += 1; - else - passes = 0; - } - if (iter === this.options.maxIterations) { - throw new Error('max iterations reached'); - } - - this.iterations = iter; - - // Compute the weights (useful for fast decision on new test instances when linear SVM) - if (this.options.kernel === 'linear') { - this.W = new Array(this.D); - 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]; - } - } - - // 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; - - - // 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; - }; - - /** - * 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); - } - }; - - /** - * 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; - }; - - - /** - * 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); - } - }; - - /** - * 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; - } - 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(); - } - 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); - } - return whitened; - }; - - module.exports = SVM; - - -/***/ }, -/* 133 */ -/***/ function(module, exports, __webpack_require__) { + static load(model) { + if (model.model !== 'Layer') { + throw new RangeError('the current model is not a Layer model'); + } - 'use strict'; + return new OutputLayer(model); + } +} - module.exports = __webpack_require__(134); +module.exports = OutputLayer; -/***/ }, -/* 134 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - module.exports = KNN; - - var KDTree = __webpack_require__(135).kdTree; - var Distances = __webpack_require__(59); - - /** - * 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; - } - } - /** - * 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++; - } - } - - // copy dataset - var points = new Array(trainingSet.length); - for(i = 0; i < points.length; ++i) { - points[i] = trainingSet[i].slice(); - } - - this.features = trainingSet[0].length; - for(i = 0; i < trainingLabels.length; ++i) { - points[i].push(trainingLabels[i]); - } - - 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; - }; - - /** - * 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]); - } - - return predictions; - }; - - /** - * 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; - - for(var i = 0; i < pointsPerClass.length; ++i) { - pointsPerClass[i] = 0; - } - - for(i = 0; i < nearestPoints.length; ++i) { - var currentClass = nearestPoints[i][0][lastElement]; - var currentPoints = ++pointsPerClass[currentClass]; - if(currentPoints > maxPoints) { - predictedClass = currentClass; - maxPoints = currentPoints; - } - } - - return predictedClass; - }; - - /** - * 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); - }; - - /** - * function that exports the current KNN classifier. - */ - KNN.prototype.export = function () { - return { - modelName: "KNN", - kdtree: this.kdtree, - k: this.k, - classes: this.classes - }; - }; - -/***/ }, -/* 135 */ -/***/ function(module, exports) { - - 'use strict'; - - /** - * k-d Tree JavaScript - V 1.01 - * - * https://github.com/ubilabs/kd-tree-javascript - * - * @author Mircea Pricop , 2012 - * @author Martin Kleppe , 2012 - * @author Ubilabs http://ubilabs.net, 2012 - * @license MIT License - */ - - - function Node(obj, dimension, parent) { - this.obj = obj; - this.left = null; - this.right = null; - this.parent = parent; - this.dimension = dimension; - } +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { + +const binarySearch = __webpack_require__(15); +const sortAsc = __webpack_require__(21).asc; + +const largestPrime = 0x7fffffff; + +const primeNumbers = [ + //chunk #0 + largestPrime, // 2^31-1 + + //chunk #1 + 5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759, + 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939, + 210719881, 421439783, 842879579, 1685759167, + + //chunk #2 + 433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107, + 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699, + 1854585413, + + //chunk #3 + 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341, + 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963, + 2004663929, + + //chunk #4 + 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963, + 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463, + + //chunk #5 + 31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953, + 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013, + 587742049, 1175484103, + + //chunk #6 + 599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729, + 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683, + + //chunk #7 + 311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867, + 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673, + 1344393353, + + //chunk #8 + 3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, + 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, + 359339171, 718678369, 1437356741, + + //chunk #9 + 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337, + 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741, + 759155483, 1518310967, + + //chunk #10 + 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611, + 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929, + 1600153859, + + //chunk #11 + 13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683, + 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407, + 276172823, 552345671, 1104691373, + + //chunk #12 + 19, 41, 83, 167, 337, 677, + 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, + 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, + 359339171, 718678369, 1437356741, + + //chunk #13 + 53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269, + 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781, + 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943 +]; + +primeNumbers.sort(sortAsc); + +function nextPrime(value) { + let index = binarySearch(primeNumbers, value, sortAsc); + if (index < 0) { + index = ~index; + } + return primeNumbers[index]; +} + +exports.nextPrime = nextPrime; +exports.largestPrime = largestPrime; + + +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var euclidean = __webpack_require__(1); +var ClusterLeaf = __webpack_require__(35); +var Cluster = __webpack_require__(10); + +/** + * @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 m = -1; + 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*cluster1.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); +} + +function compareNumbers(a, b) { + return a - b; +} + +function median(values, alreadySorted) { + if (alreadySorted === undefined) alreadySorted = false; + if (!alreadySorted) { + values = [].concat(values).sort(compareNumbers); + } + var l = values.length; + var half = Math.floor(l / 2); + if (l % 2 === 0) { + return (values[half - 1] + values[half]) * 0.5; + } else { + return values[half]; + } +} + +var defaultOptions = { + disFunc: euclidean, + kind: 'single', + isDistanceMatrix:false + +}; + +/** + * 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 = 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]); + } + } + } + + + // allows to use a string or a given function + if (typeof options.kind === "string") { + switch (options.kind) { + case 'single': + options.kind = simpleLink; + break; + case 'complete': + options.kind = completeLink; + break; + case 'average': + options.kind = averageLink; + break; + case 'centroid': + options.kind = centroidLink; + break; + case 'ward': + options.kind = wardLink; + break; + default: + throw new RangeError('Unknown kind of similarity'); + } + } + else if (typeof options.kind !== "function") + throw new TypeError('Undefined kind of similarity'); + + var list = new Array(len); + for (var i = 0; i < distance.length; i++) + list[i] = new ClusterLeaf(i); + var min = 10e5, + d = {}, + dis = 0; + + while (list.length > 1) { + // calculates the minimum distance + d = {}; + min = 10e5; + for (var j = 0; j < list.length; j++){ + for (var k = j + 1; k < list.length; k++) { + var fdistance, sdistance; + if (list[j] instanceof ClusterLeaf) + fdistance = [list[j].index]; + else { + fdistance = new Array(list[j].index.length); + for (var e = 0; e < fdistance.length; e++) + fdistance[e] = list[j].index[e].index; + } + if (list[k] instanceof ClusterLeaf) + sdistance = [list[k].index]; + else { + sdistance = new Array(list[k].index.length); + for (var f = 0; f < sdistance.length; f++) + sdistance[f] = list[k].index[f].index; + } + dis = options.kind(fdistance, sdistance, distance).toFixed(4); + if (dis in d) { + d[dis].push([list[j], list[k]]); + } + else { + d[dis] = [[list[j], list[k]]]; + } + min = Math.min(dis, min); + } + } + // cluster dots + var dmin = d[min.toFixed(4)]; + var clustered = new Array(dmin.length); + var aux, + count = 0; + while (dmin.length > 0) { + aux = dmin.shift(); + for (var q = 0; q < dmin.length; q++) { + var int = dmin[q].filter(function(n) { + //noinspection JSReferencingMutableVariableFromClosure + return aux.indexOf(n) !== -1 + }); + if (int.length > 0) { + var diff = dmin[q].filter(function(n) { + //noinspection JSReferencingMutableVariableFromClosure + return aux.indexOf(n) === -1 + }); + aux = aux.concat(diff); + dmin.splice(q-- ,1); + } + } + clustered[count++] = aux; + } + clustered.length = count; + + for (var ii = 0; ii < clustered.length; ii++) { + var obj = new Cluster(); + obj.children = clustered[ii].concat(); + obj.distance = min; + obj.index = new Array(len); + var indCount = 0; + for (var jj = 0; jj < clustered[ii].length; jj++) { + if (clustered[ii][jj] instanceof ClusterLeaf) + obj.index[indCount++] = clustered[ii][jj]; + else { + indCount += clustered[ii][jj].index.length; + obj.index = clustered[ii][jj].index.concat(obj.index); + } + list.splice((list.indexOf(clustered[ii][jj])), 1); + } + obj.index.length = indCount; + list.push(obj); + } + } + return list[0]; +} + +module.exports = agnes; + + +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var euclidean = __webpack_require__(1); +var ClusterLeaf = __webpack_require__(35); +var Cluster = __webpack_require__(10); + +/** + * @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; +} + +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ +function completeLink(cluster1, cluster2, disFun) { + var m = -1; + for (var i = 0; i < cluster1.length; i++) + for (var j = i; j < cluster2.length; j++) { + var d = disFun(cluster1[i], cluster2[j]); + m = Math.max(d,m); + } + return m; +} + +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ +function averageLink(cluster1, cluster2, disFun) { + var m = 0; + for (var i = 0; i < cluster1.length; i++) + for (var j = 0; j < cluster2.length; j++) + m += disFun(cluster1[i], cluster2[j]); + return m / (cluster1.length * cluster2.length); +} + +/** + * @private + * @param {Array >} cluster1 + * @param {Array >} cluster2 + * @param {function} disFun + * @returns {number} + */ +function centroidLink(cluster1, cluster2, disFun) { + var x1 = 0, + y1 = 0, + x2 = 0, + y2 = 0; + for (var i = 0; i < cluster1.length; i++) { + x1 += cluster1[i][0]; + y1 += cluster1[i][1]; + } + for (var j = 0; j < cluster2.length; j++) { + x2 += cluster2[j][0]; + y2 += cluster2[j][1]; + } + x1 /= cluster1.length; + y1 /= cluster1.length; + x2 /= cluster2.length; + y2 /= cluster2.length; + return disFun([x1,y1], [x2,y2]); +} + +/** + * @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); +} + +/** + * @private + * Returns the most distant point and his distance + * @param {Array >} splitting - Clusters to split + * @param {Array >} data - Original data + * @param {function} disFun - Distance function + * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant + */ +function diff(splitting, data, disFun) { + var ans = { + d:0, + p:0 + }; + + var Ci = new Array(splitting[0].length); + 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 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; + } + } + return ans; +} + +var defaultOptions = { + dist: euclidean, + kind: 'single' +}; + +/** + * @private + * Intra-cluster distance + * @param {Array} index + * @param {Array} data + * @param {function} disFun + * @returns {number} + */ +function intrDist(index, data, disFun) { + var dist = 0, + count = 0; + for (var i = 0; i < index.length; i++) + for (var j = i; j < index.length; j++) { + dist += disFun(data[index[i].index], data[index[j].index]); + count++ + } + return dist / count; +} + +/** + * 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'); + } + } + else if (typeof options.kind !== "function") + throw new TypeError('Undefined kind of similarity'); + var tree = new Cluster(); + tree.children = new Array(data.length); + tree.index = new Array(data.length); + for (var ind = 0; ind < data.length; ind++) { + tree.children[ind] = new ClusterLeaf(ind); + tree.index[ind] = new ClusterLeaf(ind); + } + + tree.distance = intrDist(tree.index, data, options.dist); + var m, M, clId, + dist, rebel; + var list = [tree]; + while (list.length > 0) { + M = 0; + clId = 0; + for (var i = 0; i < list.length; i++) { + m = 0; + for (var j = 0; j < list[i].length; j++) { + for (var l = (j + 1); l < list[i].length; l++) { + m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m); + } + } + if (m > M) { + M = m; + clId = i; + } + } + 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; +} + +module.exports = diana; + + +/***/ }), +/* 120 */ +/***/ (function(module, exports, __webpack_require__) { - function kdTree(points, metric, dimensions) { - - var self = this; - - function buildTree(points, depth, parent) { - var dim = depth % dimensions.length, - median, - node; - - if (points.length === 0) { - return null; - } - if (points.length === 1) { - return new Node(points[0], dim, parent); - } - - points.sort(function (a, b) { - return a[dimensions[dim]] - b[dimensions[dim]]; - }); - - 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); - - 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); - } - } - - restoreParent(self.root); - } - - // 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; - } - - var dimension = dimensions[node.dimension]; - if (point[dimension] < node.obj[dimension]) { - return innerSearch(node.left, node); - } else { - return innerSearch(node.right, node); - } - } - - var insertPosition = innerSearch(this.root, null), - newNode, - dimension; - - if (insertPosition === null) { - this.root = new Node(point, 0, null); - return; - } - - newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition); - dimension = dimensions[insertPosition.dimension]; - - if (point[dimension] < insertPosition.obj[dimension]) { - insertPosition.left = newNode; - } else { - insertPosition.right = newNode; - } - }; - - this.remove = function (point) { - var node; - - function nodeSearch(node) { - if (node === null) { - return null; - } - - if (node.obj === point) { - return node; - } - - var dimension = dimensions[node.dimension]; - - if (point[dimension] < node.obj[dimension]) { - return nodeSearch(node.left, node); - } else { - return nodeSearch(node.right, node); - } - } - - function removeNode(node) { - var nextNode, - nextObj, - pDimension; - - function findMin(node, dim) { - var dimension, - own, - left, - right, - min; - - if (node === null) { - return null; - } - - dimension = dimensions[dim]; - - if (node.dimension === dim) { - if (node.left !== null) { - return findMin(node.left, dim); - } - return node; - } - - own = node.obj[dimension]; - left = findMin(node.left, dim); - right = findMin(node.right, dim); - min = node; - - 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; - } - - pDimension = dimensions[node.parent.dimension]; - - 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; - } - - } - - node = nodeSearch(self.root); - - if (node === null) { return; } - - removeNode(node); - }; - - this.nearest = function (point, maxNodes, maxDistance) { - var i, - result, - bestNodes; - - bestNodes = new BinaryHeap( - function (e) { return -e[1]; } - ); - - function nearestSearch(node) { - var bestChild, - dimension = dimensions[node.dimension], - ownDistance = metric(point, node.obj), - linearPoint = {}, - linearDistance, - otherChild, - i; - - function saveNode(node, distance) { - bestNodes.push([node, distance]); - if (bestNodes.size() > maxNodes) { - bestNodes.pop(); - } - } - - for (i = 0; i < dimensions.length; i += 1) { - if (i === node.dimension) { - linearPoint[dimensions[i]] = point[dimensions[i]]; - } else { - linearPoint[dimensions[i]] = node.obj[dimensions[i]]; - } - } - - linearDistance = metric(linearPoint, node.obj); - - if (node.right === null && node.left === null) { - if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { - saveNode(node, ownDistance); - } - 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; - } - } - - 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 { - otherChild = node.left; - } - if (otherChild !== null) { - nearestSearch(otherChild); - } - } - } - - if (maxDistance) { - for (i = 0; i < maxNodes; i += 1) { - bestNodes.push([null, maxDistance]); - } - } - - if(self.root) - nearestSearch(self.root); - - 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; - }; - - this.balanceFactor = function () { - function height(node) { - if (node === null) { - return 0; - } - return Math.max(height(node.left), height(node.right)) + 1; - } - - function count(node) { - if (node === null) { - return 0; - } - return count(node.left) + count(node.right) + 1; - } - - return height(self.root) / (Math.log(count(self.root)) / Math.log(2)); - }; - } +"use strict"; - // Binary heap implementation from: - // http://eloquentjavascript.net/appendix2.html - function BinaryHeap(scoreFunction){ - this.content = []; - this.scoreFunction = scoreFunction; - } +const squaredEuclidean = __webpack_require__(1).squared; - 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; - }, - - peek: function() { - return this.content[0]; - }, - - 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; - } - } - throw new Error("Node not found."); - }, - - 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; - } - } - }, - - sinkDown: function(n) { - // Look up the target element and its score. - var length = this.content.length, - element = this.content[n], - elemScore = this.scoreFunction(element); - - 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; - } - } - - // 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; - } - } - } - }; - - this.kdTree = kdTree; - - exports.kdTree = kdTree; - exports.BinaryHeap = BinaryHeap; - - -/***/ }, -/* 136 */ -/***/ function(module, exports, __webpack_require__) { +const defaultOptions = { + sigma: 1 +}; - 'use strict'; +class GaussianKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + this.divisor = 2 * options.sigma * options.sigma; + } - module.exports = exports = __webpack_require__(137).NaiveBayes; - exports.separateClasses = __webpack_require__(137).separateClasses; + compute(x, y) { + const distance = squaredEuclidean(x, y); + return Math.exp(-distance / this.divisor); + } +} +module.exports = GaussianKernel; -/***/ }, -/* 137 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Matrix = __webpack_require__(14); - var Stat = __webpack_require__(3); - - 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; - } +/***/ }), +/* 121 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * 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)) - } +"use strict"; - /** - * 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; - } +const defaultOptions = { + degree: 1, + constant: 1, + scale: 1 +}; -/***/ }, -/* 138 */ -/***/ function(module, exports, __webpack_require__) { +class PolynomialKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); - module.exports = exports = __webpack_require__(139); - exports.Utils = __webpack_require__(140); - exports.OPLS = __webpack_require__(141); + 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); + } +} -/***/ }, -/* 139 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Matrix = __webpack_require__(14); - var Utils = __webpack_require__(140); - - 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); - } - - var tolerance = options.tolerance; - if (tolerance === undefined) { - tolerance = 1e-5; - } - - var X = this.X; - var Y = this.Y; - - 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(); - - 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; - - 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)); - - 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); - } - - t = t1; - var num = transposeX.mmul(t); - var den = (t.transpose().mmul(t))[0][0]; - var p = num.div(den); - var pnorm = Utils.norm(p); - p.div(pnorm); - t.mul(pnorm); - w.mul(pnorm); - - num = u.transpose().mmul(t); - den = (t.transpose().mmul(t))[0][0]; - var b = (num.div(den))[0][0]; - 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); - - B[k][k] = b; - k++; - } - - k--; - T = T.subMatrix(0, T.rows - 1, 0, k); - P = P.subMatrix(0, P.rows - 1, 0, k); - U = U.subMatrix(0, U.rows - 1, 0, k); - Q = Q.subMatrix(0, Q.rows - 1, 0, k); - W = W.subMatrix(0, W.rows - 1, 0, k); - B = B.subMatrix(0, k, 0, k); - - // TODO: review of R2Y - //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0]; - - this.ssqYcal = sumOfSquaresY; - this.E = 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, - }; - } - - /** - * 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 = PolynomialKernel; - 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]; - } - 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; - } - } - return maxIndex; - } +/***/ }), +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -/***/ }, -/* 140 */ -/***/ function(module, exports, __webpack_require__) { - 'use strict'; +const defaultOptions = { + alpha: 0.01, + constant: -Math.E +}; - const Matrix = __webpack_require__(14); - const Stat = __webpack_require__(3); +class SigmoidKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.alpha = options.alpha; + this.constant = options.constant; + } - /** - * 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()); - } + compute(x, y) { + var sum = 0; + for (var i = 0; i < x.length; i++) { + sum += x[i] * y[i]; + } + return Math.tanh(this.alpha * sum + this.constant); + } +} - /** - * Function 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; - } +module.exports = SigmoidKernel; - /** - * 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 - }; +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -/***/ }, -/* 141 */ -/***/ function(module, exports, __webpack_require__) { - 'use strict'; +const defaultOptions = { + sigma: 1, + degree: 1 +}; - var Matrix = __webpack_require__(14); - var Utils = __webpack_require__(140); +class ANOVAKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + this.degree = options.degree; + } - module.exports = OPLS; + 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; + } +} - function OPLS(dataset, predictions, numberOSC) { - var X = new Matrix(dataset); - var y = new Matrix(predictions); +module.exports = ANOVAKernel; - X = Utils.featureNormalize(X).result; - y = Utils.featureNormalize(y).result; - var rows = X.rows; - var columns = X.columns; +/***/ }), +/* 124 */ +/***/ (function(module, exports, __webpack_require__) { - var sumOfSquaresX = X.clone().mul(X).sum(); - var w = X.transpose().mmul(y); - w.div(Utils.norm(w)); +"use strict"; - 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); +const squaredEuclidean = __webpack_require__(1).squared; - 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)); +const defaultOptions = { + sigma: 1 +}; - var tOsc = X.mmul(wOsc); +class CauchyKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + } - numerator = X.transpose().mmul(tOsc); - denominator = tOsc.transpose().mmul(tOsc)[0][0]; - var pOsc = numerator.div(denominator); + compute(x, y) { + return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma)); + } +} - X.sub(tOsc.mmul(pOsc.transpose())); - orthoW[i] = wOsc.getColumn(0); - orthoT[i] = tOsc.getColumn(0); - orthoP[i] = pOsc.getColumn(0); - } +module.exports = CauchyKernel; - this.Xosc = X; - var sumOfSquaresXosx = this.Xosc.clone().mul(this.Xosc).sum(); - this.R2X = 1 - sumOfSquaresXosx/sumOfSquaresX; +/***/ }), +/* 125 */ +/***/ (function(module, exports, __webpack_require__) { - this.W = orthoW; - this.T = orthoT; - this.P = orthoP; - this.numberOSC = numberOSC; - } +"use strict"; - 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); +const euclidean = __webpack_require__(1); - var t = X.mmul(currentW); - X.sub(t.mmul(currentP)); - } - var sumOfSquaresXosx = X.clone().mul(X).sum(); +const defaultOptions = { + sigma: 1 +}; - var R2X = 1 - sumOfSquaresXosx / sumOfSquaresX; +class ExponentialKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + this.divisor = 2 * options.sigma * options.sigma; + } - return { - datasetOsc: X, - R2Dataset: R2X - }; - }; + compute(x, y) { + const distance = euclidean(x, y); + return Math.exp(-distance / this.divisor); + } +} -/***/ }, -/* 142 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - const squaredDistance = __webpack_require__(143).squared; - - /** - * Calculates the sum of squared errors - * @param {Array >} data - the (x,y) points to cluster - * @param {Array >} centers - the K centers in format (x,y) - * @param {Array } clusterID - the cluster identifier for each data dot - * @returns {Number} the sum of squared errors - */ - function computeSSE(data, centers, clusterID) { - let sse = 0; - let nData = data.length; - let c = 0; - for (let i = 0; i < nData; i++) { - c = clusterID[i]; - sse += squaredDistance(data[i], centers[c]); - } - return sse; - } +module.exports = ExponentialKernel; - /** - * Updates the cluster identifier based in the new data - * @param {Array >} data - the (x,y) points to cluster - * @param {Array >} centers - the K centers in format (x,y) - * @returns {Array} the cluster identifier for each data dot - */ - function updateClusterID(data, centers) { - let nData = data.length; - let k = centers.length; - let aux = 0; - let clusterID = new Array(nData); - for (let i = 0; i < nData; i++) - clusterID[i] = 0; - let d = new Array(nData); - for (let i = 0; i < nData; i++) { - d[i] = new Array(k); - for (let j = 0; j < k; j++) { - aux = squaredDistance(data[i], centers[j]); - d[i][j] = new Array(2); - d[i][j][0] = aux; - d[i][j][1] = j; - } - let min = d[i][0][0]; - let id = 0; - for (let j = 0; j < k; j++) - if (d[i][j][0] < min) { - min = d[i][j][0]; - id = d[i][j][1]; - } - clusterID[i] = id; - } - return clusterID; - } - /** - * Update the center values based in the new configurations of the clusters - * @param {Array >} data - the (x,y) 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) - */ - function updateCenters(data, clusterID, K) { - let nDim = data[0].length; - let nData = data.length; - let centers = new Array(K); - for (let i = 0; i < K; i++) { - centers[i] = new Array(nDim); - for (let j = 0; j < nDim; j++) - centers[i][j] = 0; - } - - for (let k = 0; k < K; k++) { - let cluster = []; - for (let i = 0; i < nData; i++) - if (clusterID[i] === k) - cluster.push(data[i]); - for (let d = 0; d < nDim; d++) { - let x = []; - for (let i = 0; i < nData; i++) - if (clusterID[i] === k) - x.push(data[i][d]); - let sum = 0; - let l = x.length; - for (let i = 0; i < l; i++) - sum += x[i]; - centers[k][d] = sum / l; - } - } - return centers; - } +/***/ }), +/* 126 */ +/***/ (function(module, exports, __webpack_require__) { - const defaultOptions = { - maxIterations: 100, - tolerance: 1e-6, - withIterations: false - }; - - /** - * K-means algorithm - * @param {Array >} data - the (x,y) points to cluster - * @param {Array >} centers - the K centers in format (x,y) - * @param {Object} options - properties - * @param {Number} options.maxIterations - maximum of iterations allowed - * @param {Number} options.tolerance - the error tolerance - * @param {boolean} options.withIterations - store clusters and centroids for each iteration - * @returns {Object} the cluster identifier for each data dot and centroids - */ - function kmeans(data, centers, options) { - if (!options) options = defaultOptions; - let maxIterations = options.maxIterations || defaultOptions.maxIterations; - let tolerance = options.tolerance || defaultOptions.tolerance; - let withIterations = options.withIterations || defaultOptions.withIterations; - - let nData = data.length; - if (nData === 0) { - return []; - } - let K = centers.length; - let clusterID = new Array(nData); - for (let i = 0; i < nData; i++) - clusterID[i] = 0; - if (K >= nData) { - for (let i = 0; i < nData; i++) - clusterID[i] = i; - return clusterID; - } - let lastDistance; - lastDistance = 1e100; - let curDistance = 0; - let iterations = []; - for (let iter = 0; iter < maxIterations; iter++) { - clusterID = updateClusterID(data, centers); - centers = updateCenters(data, clusterID, K); - curDistance = computeSSE(data, centers, clusterID); - if (withIterations) { - iterations.push({ - 'clusters': clusterID, - 'centroids': centers - }); - } - - if ((lastDistance - curDistance < tolerance) || ((lastDistance - curDistance) / lastDistance < tolerance)) { - if (withIterations) { - return { - 'clusters': clusterID, - 'centroids': centers, - 'iterations': iterations - }; - } else { - return { - 'clusters': clusterID, - 'centroids': centers - }; - } - } - lastDistance = curDistance; - } - if (withIterations) { - return { - 'clusters': clusterID, - 'centroids': centers, - 'iterations': iterations - }; - } else { - return { - 'clusters': clusterID, - 'centroids': centers - }; - } - } +"use strict"; - module.exports = kmeans; +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]); -/***/ }, -/* 143 */ -/***/ function(module, exports) { + return sum; + } +} - 'use strict'; +module.exports = HistogramIntersectionKernel; - function squaredEuclidean(p, q) { - var d = 0; - for (var i = 0; i < p.length; i++) { - d += (p[i] - q[i]) * (p[i] - q[i]); - } - return d; - } - function euclidean(p, q) { - return Math.sqrt(squaredEuclidean(p, q)); - } +/***/ }), +/* 127 */ +/***/ (function(module, exports, __webpack_require__) { - module.exports = euclidean; - euclidean.squared = squaredEuclidean; +"use strict"; -/***/ }, -/* 144 */ -/***/ function(module, exports, __webpack_require__) { +const euclidean = __webpack_require__(1); - exports.agnes = __webpack_require__(145); - exports.diana = __webpack_require__(154); - //exports.birch = require('./birch'); - //exports.cure = require('./cure'); - //exports.chameleon = require('./chameleon'); +const defaultOptions = { + sigma: 1 +}; +class LaplacianKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.sigma = options.sigma; + } -/***/ }, -/* 145 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var euclidean = __webpack_require__(47); - var ClusterLeaf = __webpack_require__(146); - var Cluster = __webpack_require__(147); - - /** - * @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; - } + compute(x, y) { + const distance = euclidean(x, y); + return Math.exp(-distance / this.sigma); + } +} - /** - * @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; - } +module.exports = LaplacianKernel; - /** - * @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 m = -1; - 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*cluster1.length+j]=(disFun[cluster1[i]][ cluster2[j]]); - } - return median(dist); - } +/***/ }), +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * @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); - } +"use strict"; - function compareNumbers(a, b) { - return a - b; - } - function median(values, alreadySorted) { - if (alreadySorted === undefined) alreadySorted = false; - if (!alreadySorted) { - values = [].concat(values).sort(compareNumbers); - } - var l = values.length; - var half = Math.floor(l / 2); - if (l % 2 === 0) { - return (values[half - 1] + values[half]) * 0.5; - } else { - return values[half]; - } - } +const squaredEuclidean = __webpack_require__(1).squared; - var defaultOptions = { - disFunc: euclidean, - kind: 'single', - isDistanceMatrix:false - - }; - - /** - * 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 = 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]); - } - } - } - - - // allows to use a string or a given function - if (typeof options.kind === "string") { - switch (options.kind) { - case 'single': - options.kind = simpleLink; - break; - case 'complete': - options.kind = completeLink; - break; - case 'average': - options.kind = averageLink; - break; - case 'centroid': - options.kind = centroidLink; - break; - case 'ward': - options.kind = wardLink; - break; - default: - throw new RangeError('Unknown kind of similarity'); - } - } - else if (typeof options.kind !== "function") - throw new TypeError('Undefined kind of similarity'); - - var list = new Array(len); - for (var i = 0; i < distance.length; i++) - list[i] = new ClusterLeaf(i); - var min = 10e5, - d = {}, - dis = 0; - - while (list.length > 1) { - // calculates the minimum distance - d = {}; - min = 10e5; - for (var j = 0; j < list.length; j++){ - for (var k = j + 1; k < list.length; k++) { - var fdistance, sdistance; - if (list[j] instanceof ClusterLeaf) - fdistance = [list[j].index]; - else { - fdistance = new Array(list[j].index.length); - for (var e = 0; e < fdistance.length; e++) - fdistance[e] = list[j].index[e].index; - } - if (list[k] instanceof ClusterLeaf) - sdistance = [list[k].index]; - else { - sdistance = new Array(list[k].index.length); - for (var f = 0; f < sdistance.length; f++) - sdistance[f] = list[k].index[f].index; - } - dis = options.kind(fdistance, sdistance, distance).toFixed(4); - if (dis in d) { - d[dis].push([list[j], list[k]]); - } - else { - d[dis] = [[list[j], list[k]]]; - } - min = Math.min(dis, min); - } - } - // cluster dots - var dmin = d[min.toFixed(4)]; - var clustered = new Array(dmin.length); - var aux, - count = 0; - while (dmin.length > 0) { - aux = dmin.shift(); - for (var q = 0; q < dmin.length; q++) { - var int = dmin[q].filter(function(n) { - //noinspection JSReferencingMutableVariableFromClosure - return aux.indexOf(n) !== -1 - }); - if (int.length > 0) { - var diff = dmin[q].filter(function(n) { - //noinspection JSReferencingMutableVariableFromClosure - return aux.indexOf(n) === -1 - }); - aux = aux.concat(diff); - dmin.splice(q-- ,1); - } - } - clustered[count++] = aux; - } - clustered.length = count; - - for (var ii = 0; ii < clustered.length; ii++) { - var obj = new Cluster(); - obj.children = clustered[ii].concat(); - obj.distance = min; - obj.index = new Array(len); - var indCount = 0; - for (var jj = 0; jj < clustered[ii].length; jj++) { - if (clustered[ii][jj] instanceof ClusterLeaf) - obj.index[indCount++] = clustered[ii][jj]; - else { - indCount += clustered[ii][jj].index.length; - obj.index = clustered[ii][jj].index.concat(obj.index); - } - list.splice((list.indexOf(clustered[ii][jj])), 1); - } - obj.index.length = indCount; - list.push(obj); - } - } - return list[0]; - } +const defaultOptions = { + constant: 1 +}; - module.exports = agnes; +class MultiquadraticKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.constant = options.constant; + } + compute(x, y) { + return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant); + } +} -/***/ }, -/* 146 */ -/***/ function(module, exports, __webpack_require__) { +module.exports = MultiquadraticKernel; - 'use strict'; - var Cluster = __webpack_require__(147); - var util = __webpack_require__(150); +/***/ }), +/* 129 */ +/***/ (function(module, exports, __webpack_require__) { - function ClusterLeaf (index) { - Cluster.call(this); - this.index = index; - this.distance = 0; - this.children = []; - } +"use strict"; - util.inherits(ClusterLeaf, Cluster); - module.exports = ClusterLeaf; +const squaredEuclidean = __webpack_require__(1).squared; +const defaultOptions = { + constant: 1 +}; -/***/ }, -/* 147 */ -/***/ function(module, exports, __webpack_require__) { +class RationalQuadraticKernel { + constructor(options) { + options = Object.assign({}, defaultOptions, options); + this.constant = options.constant; + } - 'use strict'; + compute(x, y) { + const distance = squaredEuclidean(x, y); + return 1 - (distance / (distance + this.constant)); + } +} - const Heap = __webpack_require__(148); +module.exports = RationalQuadraticKernel; - 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); - } - 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)); - } - - var root = new Cluster(); - root.children = heap.toArray(); - root.distance = this.distance; - - return root; - }; - - module.exports = Cluster; - - -/***/ }, -/* 148 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 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; + } + + return new KMeansResult(this.clusters, enrichedCentroids, this.converged, this.iterations, this[distanceSymbol]); +}; + +module.exports = KMeansResult; + + +/***/ }), +/* 131 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const Picker = __webpack_require__(62).Picker; + +/** + * 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); + + for (var i = 0; i < K; ++i) { + ans[i] = rand.pick(); + } + return ans; +} + +/** + * 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); + + // chooses a random point as initial cluster + ans[0] = Math.floor(Math.random() * data.length); + + if (K > 1) { + // chooses the more distant point + var maxDist = {dist: -1, index: -1}; + for (var l = 0; l < data.length; ++l) { + if (distanceMatrix[ans[0]][l] > maxDist.dist) { + maxDist.dist = distanceMatrix[ans[0]][l]; + maxDist.index = l; + } + } + ans[1] = maxDist.index; + + if (K > 2) { + // chooses the set of points that maximises the min distance + for (var k = 2; k < K; ++k) { + var center = {dist: -1, index: -1}; + for (var m = 0; m < data.length; ++m) { + + // minimum distance to centers + var minDistCent = {dist: Number.MAX_VALUE, index: -1}; + for (var n = 0; n < k; ++n) { + if (distanceMatrix[n][m] < minDistCent.dist && ans.indexOf(m) === -1) { + minDistCent = { + dist: distanceMatrix[n][m], + index: m + }; + } + } + + if (minDistCent.dist !== Number.MAX_VALUE && minDistCent.dist > center.dist) { + center = Object.assign({}, minDistCent); + } + } + + ans[k] = center.index; + } + } + } + + return ans.map((index) => data[index]); +} + +exports.random = random; +exports.mostDistant = mostDistant; + + +/***/ }), +/* 132 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** +* k-d Tree JavaScript - V 1.01 +* +* https://github.com/ubilabs/kd-tree-javascript +* +* @author Mircea Pricop , 2012 +* @author Martin Kleppe , 2012 +* @author Ubilabs http://ubilabs.net, 2012 +* @license MIT License +*/ + + +function Node(obj, dimension, parent) { + this.obj = obj; + this.left = null; + this.right = null; + this.parent = parent; + this.dimension = dimension; +} + +function kdTree(points, metric, dimensions) { + + var self = this; + + function buildTree(points, depth, parent) { + var dim = depth % dimensions.length, + median, + node; + + if (points.length === 0) { + return null; + } + if (points.length === 1) { + return new Node(points[0], dim, parent); + } + + points.sort(function (a, b) { + return a[dimensions[dim]] - b[dimensions[dim]]; + }); + + 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); + + 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); + } + } + + restoreParent(self.root); + } + + // 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; + } + + var dimension = dimensions[node.dimension]; + if (point[dimension] < node.obj[dimension]) { + return innerSearch(node.left, node); + } else { + return innerSearch(node.right, node); + } + } + + var insertPosition = innerSearch(this.root, null), + newNode, + dimension; + + if (insertPosition === null) { + this.root = new Node(point, 0, null); + return; + } + + newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition); + dimension = dimensions[insertPosition.dimension]; + + if (point[dimension] < insertPosition.obj[dimension]) { + insertPosition.left = newNode; + } else { + insertPosition.right = newNode; + } + }; + + this.remove = function (point) { + var node; + + function nodeSearch(node) { + if (node === null) { + return null; + } + + if (node.obj === point) { + return node; + } + + var dimension = dimensions[node.dimension]; + + if (point[dimension] < node.obj[dimension]) { + return nodeSearch(node.left, node); + } else { + return nodeSearch(node.right, node); + } + } + + function removeNode(node) { + var nextNode, + nextObj, + pDimension; + + function findMin(node, dim) { + var dimension, + own, + left, + right, + min; + + if (node === null) { + return null; + } + + dimension = dimensions[dim]; + + if (node.dimension === dim) { + if (node.left !== null) { + return findMin(node.left, dim); + } + return node; + } + + own = node.obj[dimension]; + left = findMin(node.left, dim); + right = findMin(node.right, dim); + min = node; + + 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; + } + + pDimension = dimensions[node.parent.dimension]; + + 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; + } + + } + + node = nodeSearch(self.root); + + if (node === null) { return; } + + removeNode(node); + }; + + this.nearest = function (point, maxNodes, maxDistance) { + var i, + result, + bestNodes; + + bestNodes = new BinaryHeap( + function (e) { return -e[1]; } + ); + + function nearestSearch(node) { + var bestChild, + dimension = dimensions[node.dimension], + ownDistance = metric(point, node.obj), + linearPoint = {}, + linearDistance, + otherChild, + i; + + function saveNode(node, distance) { + bestNodes.push([node, distance]); + if (bestNodes.size() > maxNodes) { + bestNodes.pop(); + } + } + + for (i = 0; i < dimensions.length; i += 1) { + if (i === node.dimension) { + linearPoint[dimensions[i]] = point[dimensions[i]]; + } else { + linearPoint[dimensions[i]] = node.obj[dimensions[i]]; + } + } + + linearDistance = metric(linearPoint, node.obj); + + if (node.right === null && node.left === null) { + if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) { + saveNode(node, ownDistance); + } + 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; + } + } + + 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 { + otherChild = node.left; + } + if (otherChild !== null) { + nearestSearch(otherChild); + } + } + } + + if (maxDistance) { + for (i = 0; i < maxNodes; i += 1) { + bestNodes.push([null, maxDistance]); + } + } + + if(self.root) + nearestSearch(self.root); + + 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; + }; + + this.balanceFactor = function () { + function height(node) { + if (node === null) { + return 0; + } + return Math.max(height(node.left), height(node.right)) + 1; + } + + function count(node) { + if (node === null) { + return 0; + } + return count(node.left) + count(node.right) + 1; + } + + 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); + }, + + 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; + }, + + peek: function() { + return this.content[0]; + }, + + 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; + } + } + throw new Error("Node not found."); + }, + + 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; + } + } + }, + + sinkDown: function(n) { + // Look up the target element and its score. + var length = this.content.length, + element = this.content[n], + elemScore = this.scoreFunction(element); + + 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; + } + } + + // 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; + } + } + } +}; + +this.kdTree = kdTree; + +exports.kdTree = kdTree; +exports.BinaryHeap = BinaryHeap; + + +/***/ }), +/* 133 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = KNN; + +var KDTree = __webpack_require__(132).kdTree; +var Distances = __webpack_require__(18); + +/** + * 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; + } +} + +/** + * 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++; + } + } + + // copy dataset + var points = new Array(trainingSet.length); + for(i = 0; i < points.length; ++i) { + points[i] = trainingSet[i].slice(); + } + + this.features = trainingSet[0].length; + for(i = 0; i < trainingLabels.length; ++i) { + points[i].push(trainingLabels[i]); + } + + 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; +}; + +/** + * 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]); + } + + return predictions; +}; + +/** + * 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; + + for(var i = 0; i < pointsPerClass.length; ++i) { + pointsPerClass[i] = 0; + } + + for(i = 0; i < nearestPoints.length; ++i) { + var currentClass = nearestPoints[i][0][lastElement]; + var currentPoints = ++pointsPerClass[currentClass]; + if(currentPoints > maxPoints) { + predictedClass = currentClass; + maxPoints = currentPoints; + } + } + + return predictedClass; +}; + +/** + * 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); +}; + +/** + * 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__) { + +"use strict"; + + +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; + } + + 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; +} + +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"; + + +const Matrix = __webpack_require__(3).Matrix; +const util = __webpack_require__(11); +const hypotenuse = util.hypotenuse; +const getFilled2DArray = util.getFilled2DArray; + +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 = Matrix.checkMatrix(matrix); + if (!matrix.isSquare()) { + throw new Error('Matrix is not a square matrix'); + } + + 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(); + } + + 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; +} + +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]; + } + + for (i = n - 1; i > 0; i--) { + scale = 0; + h = 0; + for (k = 0; k < i; k++) { + scale = scale + Math.abs(d[k]); + } + + if (scale === 0) { + e[i] = d[i - 1]; + for (j = 0; j < i; j++) { + d[j] = V[i - 1][j]; + V[i][j] = 0; + V[j][i] = 0; + } + } else { + for (k = 0; k < i; k++) { + d[k] /= scale; + h += d[k] * d[k]; + } + + f = d[i - 1]; + g = Math.sqrt(h); + if (f > 0) { + g = -g; + } + + e[i] = scale * g; + h = h - f * g; + d[i - 1] = f - g; + for (j = 0; j < i; j++) { + e[j] = 0; + } + + for (j = 0; j < i; j++) { + f = d[j]; + V[j][i] = f; + g = e[j] + V[j][j] * f; + for (k = j + 1; k <= i - 1; k++) { + g += V[k][j] * d[k]; + e[k] += V[k][j] * f; + } + e[j] = g; + } + + f = 0; + for (j = 0; j < i; j++) { + e[j] /= h; + f += e[j] * d[j]; + } + + hh = f / (h + h); + for (j = 0; j < i; j++) { + e[j] -= hh * d[j]; + } + + for (j = 0; j < i; j++) { + f = d[j]; + g = e[j]; + for (k = j; k <= i - 1; k++) { + V[k][j] -= (f * e[k] + g * d[k]); + } + d[j] = V[i - 1][j]; + V[i][j] = 0; + } + } + d[i] = h; + } + + for (i = 0; i < n - 1; i++) { + V[n - 1][i] = V[i][i]; + V[i][i] = 1; + h = d[i + 1]; + if (h !== 0) { + for (k = 0; k <= i; k++) { + d[k] = V[k][i + 1] / h; + } + + for (j = 0; j <= i; j++) { + g = 0; + for (k = 0; k <= i; k++) { + g += V[k][i + 1] * V[k][j]; + } + for (k = 0; k <= i; k++) { + V[k][j] -= g * d[k]; + } + } + } + + for (k = 0; k <= i; k++) { + V[k][i + 1] = 0; + } + } + + for (j = 0; j < n; j++) { + d[j] = V[n - 1][j]; + V[n - 1][j] = 0; + } + + V[n - 1][n - 1] = 1; + e[0] = 0; +} + +function tql2(n, e, d, V) { + + var g, h, i, j, k, l, m, p, r, + dl1, c, c2, c3, el1, s, s2, + iter; + + for (i = 1; i < n; i++) { + e[i - 1] = e[i]; + } + + e[n - 1] = 0; + + var f = 0, + 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; + + g = d[l]; + p = (d[l + 1] - g) / (2 * e[l]); + r = hypotenuse(p, 1); + if (p < 0) { + r = -r; + } + + d[l] = e[l] / (p + r); + d[l + 1] = e[l] * (p + r); + dl1 = d[l + 1]; + h = g - d[l]; + for (i = l + 2; i < n; i++) { + d[i] -= h; + } + + f = f + h; + + p = d[m]; + c = 1; + c2 = c; + c3 = c; + el1 = e[l + 1]; + s = 0; + s2 = 0; + for (i = m - 1; i >= l; i--) { + c3 = c2; + c2 = c; + s2 = s; + g = c * e[i]; + h = c * p; + r = hypotenuse(p, e[i]); + e[i + 1] = s * r; + s = e[i] / r; + c = p / r; + p = c * d[i] - s * g; + d[i + 1] = h + s * (c * g + s * d[i]); + + for (k = 0; k < n; k++) { + h = V[k][i + 1]; + V[k][i + 1] = s * V[k][i] + c * h; + V[k][i] = c * V[k][i] - s * h; + } + } + + p = -s * s2 * c3 * el1 * e[l] / dl1; + e[l] = s * p; + d[l] = c * p; + + } + while (Math.abs(e[l]) > eps * tst1); + } + d[l] = d[l] + f; + e[l] = 0; + } + + for (i = 0; i < n - 1; i++) { + k = i; + p = d[i]; + for (j = i + 1; j < n; j++) { + if (d[j] < p) { + k = j; + p = d[j]; + } + } + + if (k !== i) { + d[k] = d[i]; + d[i] = p; + for (j = 0; j < n; j++) { + p = V[j][i]; + V[j][i] = V[j][k]; + V[j][k] = p; + } + } + } +} + +function orthes(n, H, ort, V) { + + var low = 0, + 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]); + } + + if (scale !== 0) { + h = 0; + for (i = high; i >= m; i--) { + ort[i] = H[i][m - 1] / scale; + h += ort[i] * ort[i]; + } + + g = Math.sqrt(h); + if (ort[m] > 0) { + g = -g; + } + + h = h - ort[m] * g; + ort[m] = ort[m] - g; + + for (j = m; j < n; j++) { + f = 0; + for (i = high; i >= m; i--) { + f += ort[i] * H[i][j]; + } + + f = f / h; + for (i = m; i <= high; i++) { + H[i][j] -= f * ort[i]; + } + } + + for (i = 0; i <= high; i++) { + f = 0; + for (j = high; j >= m; j--) { + f += ort[j] * H[i][j]; + } + + f = f / h; + for (j = m; j <= high; j++) { + H[i][j] -= f * ort[j]; + } + } + + ort[m] = scale * ort[m]; + H[m][m - 1] = scale * g; + } + } + + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + V[i][j] = (i === j ? 1 : 0); + } + } + + for (m = high - 1; m >= low + 1; m--) { + if (H[m][m - 1] !== 0) { + for (i = m + 1; i <= high; i++) { + ort[i] = H[i][m - 1]; + } + + for (j = m; j <= high; j++) { + g = 0; + for (i = m; i <= high; i++) { + g += ort[i] * V[i][j]; + } + + g = (g / ort[m]) / H[m][m - 1]; + for (i = m; i <= high; i++) { + V[i][j] += g * ort[i]; + } + } + } + } +} + +function hqr2(nn, e, d, V, H) { + var n = nn - 1, + 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]); + } + } + + while (n >= low) { + l = n; + while (l > low) { + s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); + if (s === 0) { + s = norm; + } + if (Math.abs(H[l][l - 1]) < eps * s) { + break; + } + l--; + } + + if (l === n) { + H[n][n] = H[n][n] + exshift; + d[n] = H[n][n]; + e[n] = 0; + n--; + iter = 0; + } else if (l === n - 1) { + w = H[n][n - 1] * H[n - 1][n]; + p = (H[n - 1][n - 1] - H[n][n]) / 2; + q = p * p + w; + z = Math.sqrt(Math.abs(q)); + H[n][n] = H[n][n] + exshift; + H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; + x = H[n][n]; + + if (q >= 0) { + z = (p >= 0) ? (p + z) : (p - z); + d[n - 1] = x + z; + d[n] = d[n - 1]; + if (z !== 0) { + d[n] = x - w / z; + } + e[n - 1] = 0; + e[n] = 0; + x = H[n][n - 1]; + s = Math.abs(x) + Math.abs(z); + p = x / s; + q = z / s; + r = Math.sqrt(p * p + q * q); + p = p / r; + q = q / r; + + for (j = n - 1; j < nn; j++) { + z = H[n - 1][j]; + H[n - 1][j] = q * z + p * H[n][j]; + H[n][j] = q * H[n][j] - p * z; + } + + for (i = 0; i <= n; i++) { + z = H[i][n - 1]; + H[i][n - 1] = q * z + p * H[i][n]; + H[i][n] = q * H[i][n] - p * z; + } + + for (i = low; i <= high; i++) { + z = V[i][n - 1]; + V[i][n - 1] = q * z + p * V[i][n]; + V[i][n] = q * V[i][n] - p * z; + } + } else { + d[n - 1] = x + p; + d[n] = x + p; + e[n - 1] = z; + e[n] = -z; + } + + n = n - 2; + iter = 0; + } else { + x = H[n][n]; + y = 0; + w = 0; + if (l < n) { + y = H[n - 1][n - 1]; + w = H[n][n - 1] * H[n - 1][n]; + } + + if (iter === 10) { + exshift += x; + for (i = low; i <= n; i++) { + H[i][i] -= x; + } + s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); + x = y = 0.75 * s; + w = -0.4375 * s * s; + } + + if (iter === 30) { + s = (y - x) / 2; + s = s * s + w; + if (s > 0) { + s = Math.sqrt(s); + if (y < x) { + s = -s; + } + s = x - w / ((y - x) / 2 + s); + for (i = low; i <= n; i++) { + H[i][i] -= s; + } + exshift += s; + x = y = w = 0.964; + } + } + + iter = iter + 1; + + m = n - 2; + while (m >= l) { + z = H[m][m]; + r = x - z; + s = y - z; + p = (r * s - w) / H[m + 1][m] + H[m][m + 1]; + q = H[m + 1][m + 1] - z - r - s; + r = H[m + 2][m + 1]; + s = Math.abs(p) + Math.abs(q) + Math.abs(r); + p = p / s; + q = q / s; + r = r / s; + if (m === l) { + break; + } + if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math.abs(H[m + 1][m + 1])))) { + break; + } + m--; + } + + for (i = m + 2; i <= n; i++) { + H[i][i - 2] = 0; + if (i > m + 2) { + H[i][i - 3] = 0; + } + } + + for (k = m; k <= n - 1; k++) { + notlast = (k !== n - 1); + if (k !== m) { + p = H[k][k - 1]; + q = H[k + 1][k - 1]; + r = (notlast ? H[k + 2][k - 1] : 0); + x = Math.abs(p) + Math.abs(q) + Math.abs(r); + if (x !== 0) { + p = p / x; + q = q / x; + r = r / x; + } + } + + if (x === 0) { + break; + } + + s = Math.sqrt(p * p + q * q + r * r); + if (p < 0) { + s = -s; + } + + if (s !== 0) { + if (k !== m) { + H[k][k - 1] = -s * x; + } else if (l !== m) { + H[k][k - 1] = -H[k][k - 1]; + } + + p = p + s; + x = p / s; + y = q / s; + z = r / s; + q = q / p; + r = r / p; + + for (j = k; j < nn; j++) { + p = H[k][j] + q * H[k + 1][j]; + if (notlast) { + p = p + r * H[k + 2][j]; + H[k + 2][j] = H[k + 2][j] - p * z; + } + + H[k][j] = H[k][j] - p * x; + H[k + 1][j] = H[k + 1][j] - p * y; + } + + for (i = 0; i <= Math.min(n, k + 3); i++) { + p = x * H[i][k] + y * H[i][k + 1]; + if (notlast) { + p = p + z * H[i][k + 2]; + H[i][k + 2] = H[i][k + 2] - p * r; + } + + H[i][k] = H[i][k] - p; + H[i][k + 1] = H[i][k + 1] - p * q; + } + + for (i = low; i <= high; i++) { + p = x * V[i][k] + y * V[i][k + 1]; + if (notlast) { + p = p + z * V[i][k + 2]; + V[i][k + 2] = V[i][k + 2] - p * r; + } + + V[i][k] = V[i][k] - p; + V[i][k + 1] = V[i][k + 1] - p * q; + } + } + } + } + } + + if (norm === 0) { + return; + } + + for (n = nn - 1; n >= 0; n--) { + p = d[n]; + q = e[n]; + + if (q === 0) { + l = n; + H[n][n] = 1; + for (i = n - 1; i >= 0; i--) { + w = H[i][i] - p; + r = 0; + for (j = l; j <= n; j++) { + r = r + H[i][j] * H[j][n]; + } + + if (e[i] < 0) { + z = w; + s = r; + } else { + l = i; + if (e[i] === 0) { + H[i][n] = (w !== 0) ? (-r / w) : (-r / (eps * norm)); + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; + t = (x * s - z * r) / q; + H[i][n] = t; + H[i + 1][n] = (Math.abs(x) > Math.abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z); + } + + t = Math.abs(H[i][n]); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n] = H[j][n] / t; + } + } + } + } + } else if (q < 0) { + l = n - 1; + + if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { + H[n - 1][n - 1] = q / H[n][n - 1]; + H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; + } else { + cdivres = cdiv(0, -H[n - 1][n], H[n - 1][n - 1] - p, q); + H[n - 1][n - 1] = cdivres[0]; + H[n - 1][n] = cdivres[1]; + } + + H[n][n - 1] = 0; + H[n][n] = 1; + for (i = n - 2; i >= 0; i--) { + ra = 0; + sa = 0; + for (j = l; j <= n; j++) { + ra = ra + H[i][j] * H[j][n - 1]; + sa = sa + H[i][j] * H[j][n]; + } + + w = H[i][i] - p; + + if (e[i] < 0) { + z = w; + r = ra; + s = sa; + } else { + l = i; + if (e[i] === 0) { + cdivres = cdiv(-ra, -sa, w, q); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + } else { + x = H[i][i + 1]; + y = H[i + 1][i]; + vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; + vi = (d[i] - p) * 2 * q; + if (vr === 0 && vi === 0) { + vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); + } + cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi); + H[i][n - 1] = cdivres[0]; + H[i][n] = cdivres[1]; + if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { + H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x; + H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x; + } else { + cdivres = cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q); + H[i + 1][n - 1] = cdivres[0]; + H[i + 1][n] = cdivres[1]; + } + } + + t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); + if ((eps * t) * t > 1) { + for (j = i; j <= n; j++) { + H[j][n - 1] = H[j][n - 1] / t; + H[j][n] = H[j][n] / t; + } + } + } + } + } + } + + 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]; + } +} + +module.exports = EigenvalueDecomposition; + + +/***/ }), +/* 136 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Matrix = __webpack_require__(3).Matrix; +var hypotenuse = __webpack_require__(11).hypotenuse; + +//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); + + 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 = 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 = Matrix.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 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]; + } + + s = -s / qr[k][k]; + + for (i = k; i < rows; i++) { + X[i][j] += s * qr[i][k]; + } + } + } + } + return X; + } +}; + +module.exports = QrDecomposition; + + +/***/ }), +/* 137 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +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); + } + value = 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.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]; + } + } + + var U = this.U; + var V = this.rightSingularVectors; + + 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; + } + } + + 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; + + 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(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; + + +/***/ }), +/* 138 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Matrix = __webpack_require__(3).Matrix; + +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); + +function inverse(matrix) { + matrix = Matrix.checkMatrix(matrix); + return solve(matrix, Matrix.eye(matrix.rows)); +} + +/** + * Returns the inverse + * @memberOf Matrix + * @static + * @param {Matrix} matrix + * @return {Matrix} matrix + * @alias inv + */ +Matrix.inverse = Matrix.inv = inverse; + +/** + * 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); +} + +Matrix.solve = solve; +Matrix.prototype.solve = function (other) { + return solve(this, other); +}; + +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 +}; + + +/***/ }), +/* 139 */ +/***/ (function(module, exports, __webpack_require__) { - module.exports = __webpack_require__(149); +"use strict"; -/***/ }, -/* 149 */ -/***/ function(module, exports, __webpack_require__) { - - var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Generated by CoffeeScript 1.8.0 - (function() { - var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; - - floor = Math.floor, min = Math.min; - - - /* - Default comparison function to be used - */ - - defaultCmp = function(x, y) { - if (x < y) { - return -1; - } - if (x > y) { - return 1; - } - return 0; - }; - - - /* - Insert item x in list a, and keep it sorted assuming a is sorted. - - If x is already in a, insert it to the right of the rightmost x. - - Optional args lo (default 0) and hi (default a.length) bound the slice - of a to be searched. - */ - - 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); - }; - - - /* - 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); - }; - - - /* - 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); - }; - - - /* - Find the n largest elements in a dataset. - */ - - 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(); - }; - - - /* - 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; - }; - - _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; - }; - - _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); - }; - - Heap = (function() { - Heap.push = heappush; - - Heap.pop = heappop; - - Heap.replace = heapreplace; - - Heap.pushpop = heappushpop; - - Heap.heapify = heapify; - - Heap.updateItem = updateItem; - - Heap.nlargest = nlargest; - - Heap.nsmallest = nsmallest; - - function Heap(cmp) { - this.cmp = cmp != null ? cmp : defaultCmp; - this.nodes = []; - } - - Heap.prototype.push = function(x) { - return heappush(this.nodes, x, this.cmp); - }; - - Heap.prototype.pop = function() { - return heappop(this.nodes, this.cmp); - }; - - Heap.prototype.peek = function() { - return this.nodes[0]; - }; - - Heap.prototype.contains = function(x) { - return this.nodes.indexOf(x) !== -1; - }; - - Heap.prototype.replace = function(x) { - return heapreplace(this.nodes, x, this.cmp); - }; - - Heap.prototype.pushpop = function(x) { - return heappushpop(this.nodes, x, this.cmp); - }; - - Heap.prototype.heapify = function() { - return heapify(this.nodes, this.cmp); - }; - - Heap.prototype.updateItem = function(x) { - return updateItem(this.nodes, x, this.cmp); - }; - - Heap.prototype.clear = function() { - return this.nodes = []; - }; - - Heap.prototype.empty = function() { - return this.nodes.length === 0; - }; - - Heap.prototype.size = function() { - return this.nodes.length; - }; - - Heap.prototype.clone = function() { - var heap; - heap = new Heap(); - heap.nodes = this.nodes.slice(0); - return heap; - }; +if (!Symbol.species) { + Symbol.species = Symbol.for('@@species'); +} - Heap.prototype.toArray = function() { - return this.nodes.slice(0); - }; - Heap.prototype.insert = Heap.prototype.push; +/***/ }), +/* 140 */ +/***/ (function(module, exports, __webpack_require__) { - Heap.prototype.top = Heap.prototype.peek; +"use strict"; - Heap.prototype.front = Heap.prototype.peek; - Heap.prototype.has = Heap.prototype.contains; +var BaseView = __webpack_require__(5); - Heap.prototype.copy = Heap.prototype.clone; +class MatrixColumnView extends BaseView { + constructor(matrix, column) { + super(matrix, matrix.rows, 1); + this.column = column; + } - return Heap; + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.column, value); + return this; + } - })(); + get(rowIndex) { + return this.matrix.get(rowIndex, this.column); + } +} - (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 = MatrixColumnView; - }).call(this); +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { -/***/ }, -/* 150 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var formatRegExp = /%[sdj%]/g; - exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; - - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - }; - - - var debugs = {}; - var debugEnviron; - exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; - }; - - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - exports.inspect = inspect; - - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } +"use strict"; - function stylizeNoColor(str, styleType) { - return str; - } +var BaseView = __webpack_require__(5); +class MatrixFlipColumnView extends BaseView { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); + } - function arrayToHash(array) { - var hash = {}; + set(rowIndex, columnIndex, value) { + this.matrix.set(rowIndex, this.columns - columnIndex - 1, value); + return this; + } - array.forEach(function(val, idx) { - hash[val] = true; - }); + get(rowIndex, columnIndex) { + return this.matrix.get(rowIndex, this.columns - columnIndex - 1); + } +} - return hash; - } +module.exports = MatrixFlipColumnView; - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } +var BaseView = __webpack_require__(5); - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } +class MatrixFlipRowView extends BaseView { + constructor(matrix) { + super(matrix, matrix.rows, matrix.columns); + } + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rows - rowIndex - 1, columnIndex, value); + return this; + } - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.rows - rowIndex - 1, columnIndex); + } +} +module.exports = MatrixFlipRowView; - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } +/***/ }), +/* 143 */ +/***/ (function(module, exports, __webpack_require__) { - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } +"use strict"; - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - exports.isArray = isArray; +var BaseView = __webpack_require__(5); - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; +class MatrixRowView extends BaseView { + constructor(matrix, row) { + super(matrix, 1, matrix.columns); + this.row = row; + } - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; + set(rowIndex, columnIndex, value) { + this.matrix.set(this.row, columnIndex, value); + return this; + } - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; + get(rowIndex, columnIndex) { + return this.matrix.get(this.row, columnIndex); + } +} - function isNumber(arg) { - return typeof arg === 'number'; - } - exports.isNumber = isNumber; +module.exports = MatrixRowView; - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - exports.isSymbol = isSymbol; +/***/ }), +/* 144 */ +/***/ (function(module, exports, __webpack_require__) { - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; +"use strict"; - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - exports.isRegExp = isRegExp; - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; +var BaseView = __webpack_require__(5); +var util = __webpack_require__(7); - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; +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; + } - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; + set(rowIndex, columnIndex, value) { + this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value); + return this; + } - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; + get(rowIndex, columnIndex) { + return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]); + } +} - exports.isBuffer = __webpack_require__(152); +module.exports = MatrixSelectionView; - function objectToString(o) { - return Object.prototype.toString.call(o); - } +/***/ }), +/* 145 */ +/***/ (function(module, exports, __webpack_require__) { - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } +"use strict"; - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; +var BaseView = __webpack_require__(5); +var util = __webpack_require__(7); - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } +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; + } + set(rowIndex, columnIndex, value) { + this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value); + return this; + } - // log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); - }; - - - /** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ - exports.inherits = __webpack_require__(153); - - exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - }; - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } + get(rowIndex, columnIndex) { + return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex); + } +} - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(151))) +module.exports = MatrixSubView; -/***/ }, -/* 151 */ -/***/ function(module, exports) { - // shim for using process in browser - var process = module.exports = {}; +/***/ }), +/* 146 */ +/***/ (function(module, exports, __webpack_require__) { - // cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. +"use strict"; - var cachedSetTimeout; - var cachedClearTimeout; - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - (function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } - } ()) - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } +var BaseView = __webpack_require__(5); +class MatrixTransposeView extends BaseView { + constructor(matrix) { + super(matrix, matrix.columns, matrix.rows); + } - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } + set(rowIndex, columnIndex, value) { + this.matrix.set(columnIndex, rowIndex, value); + return this; + } + get(rowIndex, columnIndex) { + return this.matrix.get(columnIndex, rowIndex); + } +} +module.exports = MatrixTransposeView; - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const squaredDistance = __webpack_require__(1).squared; + +const defaultOptions = { + distanceFunction: squaredDistance, + similarityFunction: false, + returnVector: false +}; + +/** + * 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; + + var vectorIndex = -1; + if (typeof similarityFunction === 'function') { + + // maximum similarity + var maxSim = Number.MIN_VALUE; + for (var j = 0; j < listVectors.length; j++) { + var sim = similarityFunction(vector, listVectors[j]); + if (sim > maxSim) { + maxSim = sim; + vectorIndex = j; + } + } + } else if (typeof distanceFunction === 'function') { + + // minimum distance + var minDist = Number.MAX_VALUE; + for (var i = 0; i < listVectors.length; i++) { + var dist = distanceFunction(vector, listVectors[i]); + if (dist < minDist) { + minDist = dist; + vectorIndex = i; + } + } + } else { + throw new Error('A similarity or distance function it\'s required'); + } + + if (returnVector) { + return listVectors[vectorIndex]; + } else { + return vectorIndex; + } +} + +module.exports = nearestVector; + + +/***/ }), +/* 148 */ +/***/ (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); + } + 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)); + } + return result; +}; + +// 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; +}; + +// 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; +}; + +// 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; +}; + +// 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; +}; + +// 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; +}; + +// 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; +}; + +// Prediction conditioned fallout +exports.pcfall = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + for (var i = 0; i < l; i++) { + result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1; + } + return result; +}; + +// Prediction conditioned miss +exports.pcmiss = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + for (var i = 0; i < l; i++) { + result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1; + } + return result; +}; + +// Lift value +exports.lift = pred => { + const l = pred.cutoffs.length; + const result = new Array(l); + 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; +}; + +// 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; +}; + +// 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; +}; + + +/***/ }), +/* 149 */ +/***/ (function(module, exports, __webpack_require__) { - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - -/***/ }, -/* 152 */ -/***/ function(module, exports) { +"use strict"; - module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; - } -/***/ }, -/* 153 */ -/***/ function(module, exports) { - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } +var Matrix = __webpack_require__(0); +var Utils = __webpack_require__(12); +module.exports = OPLS; -/***/ }, -/* 154 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var euclidean = __webpack_require__(47); - var ClusterLeaf = __webpack_require__(146); - var Cluster = __webpack_require__(147); - - /** - * @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; - } +function OPLS(dataset, predictions, numberOSC) { + var X = new Matrix(dataset); + var y = new Matrix(predictions); - /** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ - function completeLink(cluster1, cluster2, disFun) { - var m = -1; - for (var i = 0; i < cluster1.length; i++) - for (var j = i; j < cluster2.length; j++) { - var d = disFun(cluster1[i], cluster2[j]); - m = Math.max(d,m); - } - return m; - } + X = Utils.featureNormalize(X).result; + y = Utils.featureNormalize(y).result; - /** - * @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); - } + var rows = X.rows; + var columns = X.columns; - /** - * @private - * @param {Array >} cluster1 - * @param {Array >} cluster2 - * @param {function} disFun - * @returns {number} - */ - function centroidLink(cluster1, cluster2, disFun) { - var x1 = 0, - y1 = 0, - x2 = 0, - y2 = 0; - for (var i = 0; i < cluster1.length; i++) { - x1 += cluster1[i][0]; - y1 += cluster1[i][1]; - } - for (var j = 0; j < cluster2.length; j++) { - x2 += cluster2[j][0]; - y2 += cluster2[j][1]; - } - x1 /= cluster1.length; - y1 /= cluster1.length; - x2 /= cluster2.length; - y2 /= cluster2.length; - return disFun([x1,y1], [x2,y2]); - } + var sumOfSquaresX = X.clone().mul(X).sum(); + var w = X.transpose().mmul(y); + w.div(Utils.norm(w)); - /** - * @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); - } + 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); - /** - * @private - * Returns the most distant point and his distance - * @param {Array >} splitting - Clusters to split - * @param {Array >} data - Original data - * @param {function} disFun - Distance function - * @returns {{d: number, p: number}} - d: maximum difference between points, p: the point more distant - */ - function diff(splitting, data, disFun) { - var ans = { - d:0, - p:0 - }; - - var Ci = new Array(splitting[0].length); - 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 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; - } - } - return ans; - } + var numerator = X.transpose().mmul(t); + var denominator = t.transpose().mmul(t)[0][0]; + var p = numerator.div(denominator); - var defaultOptions = { - dist: euclidean, - kind: 'single' - }; - - /** - * @private - * Intra-cluster distance - * @param {Array} index - * @param {Array} data - * @param {function} disFun - * @returns {number} - */ - function intrDist(index, data, disFun) { - var dist = 0, - count = 0; - for (var i = 0; i < index.length; i++) - for (var j = i; j < index.length; j++) { - dist += disFun(data[index[i].index], data[index[j].index]); - count++ - } - return dist / count; - } + 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)); - /** - * 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'); - } - } - else if (typeof options.kind !== "function") - throw new TypeError('Undefined kind of similarity'); - var tree = new Cluster(); - tree.children = new Array(data.length); - tree.index = new Array(data.length); - for (var ind = 0; ind < data.length; ind++) { - tree.children[ind] = new ClusterLeaf(ind); - tree.index[ind] = new ClusterLeaf(ind); - } - - tree.distance = intrDist(tree.index, data, options.dist); - var m, M, clId, - dist, rebel; - var list = [tree]; - while (list.length > 0) { - M = 0; - clId = 0; - for (var i = 0; i < list.length; i++) { - m = 0; - for (var j = 0; j < list[i].length; j++) { - for (var l = (j + 1); l < list[i].length; l++) { - m = Math.max(options.dist(data[list[i].index[j].index], data[list[i].index[l].index]), m); - } - } - if (m > M) { - M = m; - clId = i; - } - } - 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; - } + var tOsc = X.mmul(wOsc); - module.exports = diana; + 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); + } -/***/ }, -/* 155 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var NodeSquare = __webpack_require__(156), - NodeHexagonal = __webpack_require__(157); - - var defaultOptions = { - fields: 3, - randomizer: Math.random, - distance: squareEuclidean, - iterations: 10, - learningRate: 0.1, - gridType: 'rect', - torus: true, - method: 'random' - }; - - function SOM(x, y, options, reload) { - - this.x = x; - this.y = y; - - options = options || {}; - this.options = {}; - 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) - }; - } - - 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'); - } - - this.times = { - findBMU: 0, - adjust: 0 - }; - - this.randomizer = this.options.randomizer; - - this.iterationCount = 0; - this.iterations = this.options.iterations; - - this.startLearningRate = this.learningRate = this.options.learningRate; - - this.mapRadius = Math.floor(Math.max(x, y) / 2); - - this.algorithmMethod = this.options.method; - - this._initNodes(); - - this.done = false; - } + this.Xosc = X; - SOM.load = function loadModel(model, distance) { - if (model.name === 'SOM') { - var x = model.data.length, - y = model.data[0].length; - if (distance) { - model.options.distance = distance; - } else if (model.options.distance) { - model.options.distance = eval('(' + model.options.distance + ')'); - } - var som = new SOM(x, y, model.options, true); - som.nodes = new Array(x); - for (var i = 0; i < x; i++) { - som.nodes[i] = new Array(y); - for (var j = 0; j < y; j++) { - som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som); - } - } - return som; - } else { - throw new Error('expecting a SOM model'); - } - }; - - SOM.prototype.export = function exportModel(includeDistance) { - if (!this.done) { - throw new Error('model is not ready yet'); - } - var model = { - name: 'SOM' - }; - model.options = { - fields: this.options.fields, - gridType: this.options.gridType, - torus: this.options.torus - }; - model.data = new Array(this.x); - for (var i = 0; i < this.x; i++) { - model.data[i] = new Array(this.y); - for (var j = 0; j < this.y; j++) { - model.data[i][j] = this.nodes[i][j].weights; - } - } - if (includeDistance) { - model.options.distance = this.distance.toString(); - } - return model; - }; - - SOM.prototype._initNodes = function initNodes() { - var now = Date.now(), - i, j, k; - this.nodes = new Array(this.x); - for (i = 0; i < this.x; i++) { - this.nodes[i] = new Array(this.y); - for (j = 0; j < this.y; j++) { - var weights = new Array(this.numWeights); - for (k = 0; k < this.numWeights; k++) { - weights[k] = this.randomizer(); - } - this.nodes[i][j] = new this.nodeType(i, j, weights, this); - } - } - this.times.initNodes = Date.now() - now; - }; - - 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; - - 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; - }; - - SOM.prototype.trainOne = function trainOne() { - if (this.done) { - - return false; - - } else if (this.numIterations-- > 0) { - - 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)); - } - } - - this.iterationCount++; - - return true; - - } else { - - this.done = true; - return false; - - } - }; - - SOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) { - var now = Date.now(), - x, y, dist, influence; - - var bmu = this._findBestMatchingUnit(trainingValue); - - var now2 = Date.now(); - this.times.findBMU += now2 - now; - - var radiusLimit = Math.floor(neighbourhoodRadius); - var xMin = bmu.x - radiusLimit, - xMax = bmu.x + radiusLimit, - yMin = bmu.y - radiusLimit, - yMax = bmu.y + radiusLimit; - - for (x = xMin; x <= xMax; x++) { - var theX = x; - if (x < 0) { - theX += this.x; - } else if (x >= this.x) { - theX -= this.x; - } - for (y = yMin; y <= yMax; y++) { - var theY = y; - if (y < 0) { - theY += this.y; - } else if (y >= this.y) { - theY -= this.y; - } - - dist = bmu[this.distanceMethod](this.nodes[theX][theY]); - - if (dist < neighbourhoodRadius) { - influence = Math.exp(-dist / (2 * neighbourhoodRadius)); - this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence); - } - - } - } - - this.times.adjust += (Date.now() - now2); - - }; - - 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; - }; - - SOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) { - - var bmu, - lowest = Infinity, - dist; - - for (var i = 0; i < this.x; i++) { - for (var j = 0; j < this.y; j++) { - dist = this.distance(this.nodes[i][j].weights, candidate); - if (dist < lowest) { - lowest = dist; - bmu = this.nodes[i][j]; - } - } - } - - return bmu; - - }; - - SOM.prototype.predict = function predict(data, computePosition) { - if (typeof data === 'boolean') { - computePosition = data; - data = null; - } - if (!data) { - data = this.trainingSet; - } - if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset - var self = this; - return data.map(function (element) { - return self._predict(element, computePosition); - }); - } else { // predict a single element - return this._predict(data, computePosition); - } - }; - - SOM.prototype._predict = function _predict(element, computePosition) { - if (!Array.isArray(element)) { - element = this.extractor(element); - } - var bmu = this._findBestMatchingUnit(element); - var result = [bmu.x, bmu.y]; - if (computePosition) { - result[2] = bmu.getPosition(element); - } - return result; - }; - - // 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; - }; - - 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; - }; - - function getConverters(fields) { - var l = fields.length, - normalizers = new Array(l), - denormalizers = new Array(l); - for (var i = 0; i < l; i++) { - normalizers[i] = getNormalizer(fields[i].range); - denormalizers[i] = getDenormalizer(fields[i].range); - } - return { - extractor: function extractor(value) { - var result = new Array(l); - for (var i = 0; i < l; i++) { - result[i] = normalizers[i](value[fields[i].name]); - } - return result; - }, - creator: function creator(value) { - var result = {}; - for (var i = 0; i < l; i++) { - result[fields[i].name] = denormalizers[i](value[i]); - } - return result; - } - }; - } + var sumOfSquaresXosx = this.Xosc.clone().mul(this.Xosc).sum(); + this.R2X = 1 - sumOfSquaresXosx/sumOfSquaresX; - function getNormalizer(minMax) { - return function normalizer(value) { - return (value - minMax[0]) / (minMax[1] - minMax[0]); - }; - } + this.W = orthoW; + this.T = orthoT; + this.P = orthoP; + this.numberOSC = numberOSC; +} - function getDenormalizer(minMax) { - return function denormalizer(value) { - return (minMax[0] + value * (minMax[1] - minMax[0])); - }; - } +OPLS.prototype.correctDataset = function (dataset) { + var X = new Matrix(dataset); - 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; - } + 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); - function getRandomValue(arr, randomizer) { - return arr[Math.floor(randomizer() * arr.length)]; - } + var t = X.mmul(currentW); + X.sub(t.mmul(currentP)); + } + var sumOfSquaresXosx = X.clone().mul(X).sum(); - 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 R2X = 1 - sumOfSquaresXosx / sumOfSquaresX; - module.exports = SOM; + return { + datasetOsc: X, + R2Dataset: R2X + }; +}; -/***/ }, +/***/ }), +/* 150 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +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); + } + + var tolerance = options.tolerance; + if (tolerance === undefined) { + tolerance = 1e-5; + } + + var X = this.X; + var Y = this.Y; + + 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(); + + 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; + + 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)); + + 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); + } + + t = t1; + var num = transposeX.mmul(t); + var den = (t.transpose().mmul(t))[0][0]; + var p = num.div(den); + var pnorm = Utils.norm(p); + p.div(pnorm); + t.mul(pnorm); + w.mul(pnorm); + + num = u.transpose().mmul(t); + den = (t.transpose().mmul(t))[0][0]; + var b = (num.div(den))[0][0]; + 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); + + B[k][k] = b; + k++; + } + + k--; + T = T.subMatrix(0, T.rows - 1, 0, k); + P = P.subMatrix(0, P.rows - 1, 0, k); + U = U.subMatrix(0, U.rows - 1, 0, k); + Q = Q.subMatrix(0, Q.rows - 1, 0, k); + W = W.subMatrix(0, W.rows - 1, 0, k); + B = B.subMatrix(0, k, 0, k); + + // TODO: review of R2Y + //this.R2Y = t.transpose().mmul(t).mul(q[k][0]*q[k][0]).divS(ssqYcal)[0][0]; + + this.ssqYcal = sumOfSquaresY; + this.E = 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, + }; + } + + /** + * 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 = 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]; + } + 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; + } + } + return maxIndex; +} + + +/***/ }), +/* 151 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* + * 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 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]); + } + + 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); + } + } + } + + _predict(newInputs) { + return this.C * Math.exp(newInputs * this.A); + } + + toJSON() { + var out = {name: 'expRegression', A: this.A, C: this.C}; + if (this.quality) { + out.quality = this.quality; + } + return out; + } + + 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}}'; + } + + } + + static load(json) { + if (json.name !== 'expRegression') { + throw new TypeError('not a exp regression model'); + } + return new ExpRegression(true, json); + } +} + + +module.exports = ExpRegression; + + +/***/ }), +/* 152 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const Matrix = __webpack_require__(0); +const Kernel = __webpack_require__(8); + +const BaseRegression = __webpack_require__(4); + +const defaultOptions = { + lambda: 0.1, + kernelType: 'gaussian', + kernelOptions: {}, + computeCoefficient: false +}; + +// Implements the Kernel ridge regression algorithm. +// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf +class KernelRidgeRegression extends BaseRegression { + constructor(inputs, outputs, options) { + super(); + if (inputs === true) { // reloading model + this.alpha = outputs.alpha; + this.inputs = outputs.inputs; + this.kernelType = outputs.kernelType; + this.kernelOptions = outputs.kernelOptions; + this.kernel = new Kernel(outputs.kernelType, outputs.kernelOptions); + + if (outputs.quality) { + this.quality = outputs.quality; + } + } else { + options = Object.assign({}, defaultOptions, options); + + const kernelFunction = new Kernel(options.kernelType, options.kernelOptions); + const K = kernelFunction.compute(inputs); + const n = inputs.length; + K.add(Matrix.eye(n, n).mul(options.lambda)); + + this.alpha = K.solve(outputs); + this.inputs = inputs; + this.kernelType = options.kernelType; + this.kernelOptions = options.kernelOptions; + this.kernel = kernelFunction; + + if (options.computeQuality) { + this.quality = this.modelQuality(inputs, outputs); + } + } + } + + _predict(newInputs) { + return this.kernel.compute([newInputs], this.inputs).mmul(this.alpha)[0]; + } + + toJSON() { + var out = { + name: 'kernelRidgeRegression', + alpha: this.alpha, + inputs: this.inputs, + kernelType: this.kernelType, + kernelOptions: this.kernelOptions + }; + if (this.quality) { + out.quality = this.quality; + } + return out; + } + + static load(json) { + if (json.name !== 'kernelRidgeRegression') { + throw new TypeError('not a KRR model'); + } + return new KernelRidgeRegression(true, json); + } +} + +module.exports = KernelRidgeRegression; + + +/***/ }), +/* 153 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const Matrix = __webpack_require__(0); +const SVD = Matrix.DC.SingularValueDecomposition; +const BaseRegression = __webpack_require__(4); + +const defaultOptions = { + order: 2 +}; +// Implements the Kernel ridge regression algorithm. +// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf +class PolynomialFitRegression2D extends BaseRegression { + /** + * Constructor for the 2D polynomial fitting + * + * @param inputs + * @param outputs + * @param options + * @constructor + */ + constructor(inputs, outputs, options) { + super(); + if (inputs === true) { // reloading model + this.coefficients = Matrix.columnVector(outputs.coefficients); + this.order = outputs.order; + if (outputs.r) { + this.r = outputs.r; + this.r2 = outputs.r2; + } + if (outputs.chi2) { + this.chi2 = outputs.chi2; + } + } else { + options = Object.assign({}, defaultOptions, options); + this.order = options.order; + this.coefficients = []; + this.X = inputs; + this.y = outputs; + + this.train(this.X, this.y, options); + + if (options.computeQuality) { + this.quality = this.modelQuality(inputs, outputs); + } + } + } + + /** + * Function that fits the model given the data(X) and predictions(y). + * The third argument is an object with the following options: + * * order: order of the polynomial to fit. + * + * @param {Matrix} X - A matrix with n rows and 2 columns. + * @param {Matrix} y - A vector of the prediction values. + */ + train(X, y) { + if (!Matrix.isMatrix(X)) X = new Matrix(X); + if (!Matrix.isMatrix(y)) y = Matrix.columnVector(y); + + //Perhaps y is transpose + if (y.rows !== X.rows) { + y = y.transpose(); + } + + if (X.columns !== 2) { + throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2'); + } + if (X.rows !== y.rows) { + throw new RangeError('X and y must have the same rows'); + } + + var examples = X.rows; + var coefficients = ((this.order + 2) * (this.order + 1)) / 2; + this.coefficients = new Array(coefficients); + + var x1 = X.getColumnVector(0); + var x2 = X.getColumnVector(1); + + var scaleX1 = 1.0 / x1.clone().apply(abs).max(); + var scaleX2 = 1.0 / x2.clone().apply(abs).max(); + var scaleY = 1.0 / y.clone().apply(abs).max(); + + x1.mulColumn(0, scaleX1); + x2.mulColumn(0, scaleX2); + y.mulColumn(0, scaleY); + + var A = new Matrix(examples, coefficients); + var col = 0; + + for (var i = 0; i <= this.order; ++i) { + var limit = this.order - i; + for (var j = 0; j <= limit; ++j) { + var result = powColVector(x1, i).mulColumnVector(powColVector(x2, j)); + A.setColumn(col, result); + col++; + } + } + + var svd = new SVD(A.transpose(), { + computeLeftSingularVectors: true, + computeRightSingularVectors: true, + autoTranspose: false + }); + + var qqs = Matrix.rowVector(svd.diagonal); + qqs = qqs.apply(function (i, j) { + if (this[i][j] >= 1e-15) this[i][j] = 1 / this[i][j]; + else this[i][j] = 0; + }); + + var qqs1 = Matrix.zeros(examples, coefficients); + for (i = 0; i < coefficients; ++i) { + qqs1[i][i] = qqs[0][i]; + } + + qqs = qqs1; + + var U = svd.rightSingularVectors; + var V = svd.leftSingularVectors; + + this.coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y); + + col = 0; + + for (i = 0; i <= coefficients; ++i) { + limit = this.order - i; + for (j = 0; j <= limit; ++j) { + this.coefficients[col][0] = (this.coefficients[col][0] * Math.pow(scaleX1, i) * Math.pow(scaleX2, j)) / scaleY; + col++; + } + } + } + + _predict(newInputs) { + var x1 = newInputs[0]; + var x2 = newInputs[1]; + + var y = 0; + var column = 0; + + for (var i = 0; i <= this.order; i++) { + for (var j = 0; j <= this.order - i; j++) { + y += Math.pow(x1, i) * (Math.pow(x2, j)) * this.coefficients[column][0]; + column++; + } + } + + return y; + } + + toJSON() { + var out = { + name: 'polyfit2D', + order: this.order, + coefficients: this.coefficients + }; + if (this.quality) { + out.quality = this.quality; + } + return out; + } + + static load(json) { + if (json.name !== 'polyfit2D') { + throw new TypeError('not a polyfit2D model'); + } + return new PolynomialFitRegression2D(true, json); + } + +} + +module.exports = PolynomialFitRegression2D; + + +/** + * Function that given a column vector return this: vector^power + * + * @param x - Column vector. + * @param power - Pow number. + * @return {Suite|Matrix} + */ +function powColVector(x, power) { + var result = x.clone(); + for (var i = 0; i < x.rows; ++i) { + result[i][0] = Math.pow(result[i][0], power); + } + return result; +} + +/** + * Function to use in the apply method to get the absolute value + * of each element of the matrix + * + * @param i - current row. + * @param j - current column. + */ +function abs(i, j) { + this[i][j] = Math.abs(this[i][j]); +} + + +/***/ }), +/* 154 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* + * Function that calculate the potential fit in the form f(x) = A*x^M + * with a given M and return de A coefficient. + * + * @param {Vector} X - Vector of the x positions of the points. + * @param {Vector} Y - Vector of the x positions of the points. + * @param {Number, BigNumber} M - The exponent of the potential fit. + * @return {Number|BigNumber} A - The A coefficient of the potential fit. + * Created by acastillo on 5/12/16. + */ + +const maybeToPrecision = __webpack_require__(6).maybeToPrecision; +const PolynomialRegression = __webpack_require__(40); +// const PowerRegression = require('./power-regression'); +const BaseRegression = __webpack_require__(4); + +class PotentialRegression extends BaseRegression { + /** + * @constructor + * @param x: Independent variable + * @param y: Dependent variable + * @param M + * @param options + */ + constructor(x, y, M, options) { + super(); + let opt = options || {}; + if (x === true) { // reloading model + this.A = y.A; + 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'); + } + + var linear = new PolynomialRegression(x, y, [M], {computeCoefficient: true}); + this.A = linear.coefficients[0]; + this.M = M; + if (opt.computeQuality) { + this.quality = this.modelQuality(x, y); + } + } + } + + _predict(x) { + return this.A * Math.pow(x, this.M); + } + + toJSON() { + var out = {name: 'potentialRegression', A: this.A, M: this.M}; + if (this.quality) { + out.quality = this.quality; + } + return out; + } + + toString(precision) { + return 'f(x) = ' + maybeToPrecision(this.A, precision) + ' * x^' + this.M; + } + + toLaTeX(precision) { + + if (this.M >= 0) { + return 'f(x) = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}'; + } else { + return 'f(x) = \\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + (-this.M) + '}}'; + } + } + + static load(json) { + if (json.name !== 'potentialRegression') { + throw new TypeError('not a potential regression model'); + } + return new PotentialRegression(true, json); + } +} + +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 */ -/***/ 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; - -/***/ }, +/***/ (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); + } 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 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 { + 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 new TheilSenRegression(true, json); + } +} + +module.exports = TheilSenRegression; + + +/***/ }), /* 157 */ -/***/ function(module, exports, __webpack_require__) { +/***/ (function(module, exports, __webpack_require__) { - var NodeSquare = __webpack_require__(156); +"use strict"; - function NodeHexagonal(x, y, weights, som) { - NodeSquare.call(this, x, y, weights, som); +exports.array = __webpack_require__(41); +exports.matrix = __webpack_require__(158); - this.hX = x - Math.floor(y / 2); - this.z = 0 - this.hX - y; - } +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var arrayStat = __webpack_require__(41); + +// https://github.com/accord-net/framework/blob/development/Sources/Accord.Statistics/Tools.cs + +function entropy(matrix, eps) { + if (typeof(eps) === 'undefined') { + eps = 0; + } + var sum = 0, + l1 = matrix.length, + l2 = matrix[0].length; + for (var i = 0; i < l1; i++) { + for (var j = 0; j < l2; j++) { + sum += matrix[i][j] * Math.log(matrix[i][j] + eps); + } + } + return -sum; +} + +function mean(matrix, dimension) { + if (typeof(dimension) === 'undefined') { + dimension = 0; + } + var rows = matrix.length, + cols = matrix[0].length, + theMean, N, i, j; + + if (dimension === -1) { + theMean = [0]; + N = rows * cols; + for (i = 0; i < rows; i++) { + for (j = 0; j < cols; j++) { + theMean[0] += matrix[i][j]; + } + } + theMean[0] /= N; + } else if (dimension === 0) { + theMean = new Array(cols); + N = rows; + for (j = 0; j < cols; j++) { + theMean[j] = 0; + for (i = 0; i < rows; i++) { + theMean[j] += matrix[i][j]; + } + theMean[j] /= N; + } + } else if (dimension === 1) { + theMean = new Array(rows); + N = cols; + for (j = 0; j < rows; j++) { + theMean[j] = 0; + for (i = 0; i < cols; i++) { + theMean[j] += matrix[j][i]; + } + theMean[j] /= N; + } + } else { + throw new Error('Invalid dimension'); + } + return theMean; +} + +function standardDeviation(matrix, means, unbiased) { + var vari = variance(matrix, means, unbiased), l = vari.length; + for (var i = 0; i < l; i++) { + vari[i] = Math.sqrt(vari[i]); + } + return vari; +} + +function variance(matrix, means, unbiased) { + if (typeof(unbiased) === 'undefined') { + unbiased = true; + } + means = means || mean(matrix); + var rows = matrix.length; + if (rows === 0) return []; + var cols = matrix[0].length; + var vari = new Array(cols); + + for (var j = 0; j < cols; j++) { + var sum1 = 0, sum2 = 0, x = 0; + for (var i = 0; i < rows; i++) { + x = matrix[i][j] - means[j]; + sum1 += x; + sum2 += x * x; + } + if (unbiased) { + vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1); + } else { + vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows; + } + } + return vari; +} + +function median(matrix) { + var rows = matrix.length, cols = matrix[0].length; + var medians = new Array(cols); + + for (var i = 0; i < cols; i++) { + var data = new Array(rows); + for (var j = 0; j < rows; j++) { + data[j] = matrix[j][i]; + } + data.sort(); + var N = data.length; + if (N % 2 === 0) { + medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5; + } else { + medians[i] = data[Math.floor(N / 2)]; + } + } + return medians; +} + +function mode(matrix) { + var rows = matrix.length, + cols = matrix[0].length, + modes = new Array(cols), + i, j; + for (i = 0; i < cols; i++) { + var itemCount = new Array(rows); + for (var k = 0; k < rows; k++) { + itemCount[k] = 0; + } + var itemArray = new Array(rows); + var count = 0; + + for (j = 0; j < rows; j++) { + var index = itemArray.indexOf(matrix[j][i]); + if (index >= 0) { + itemCount[index]++; + } else { + itemArray[count] = matrix[j][i]; + itemCount[count] = 1; + count++; + } + } + + var maxValue = 0, maxIndex = 0; + for (j = 0; j < count; j++) { + if (itemCount[j] > maxValue) { + maxValue = itemCount[j]; + maxIndex = j; + } + } + + modes[i] = itemArray[maxIndex]; + } + return modes; +} + +function skewness(matrix, unbiased) { + if (typeof(unbiased) === 'undefined') unbiased = true; + var means = mean(matrix); + var n = matrix.length, l = means.length; + var skew = new Array(l); + + for (var j = 0; j < l; j++) { + var s2 = 0, s3 = 0; + for (var i = 0; i < n; i++) { + var dev = matrix[i][j] - means[j]; + s2 += dev * dev; + s3 += dev * dev * dev; + } + + var m2 = s2 / n; + var m3 = s3 / n; + var g = m3 / Math.pow(m2, 3 / 2); + + if (unbiased) { + var a = Math.sqrt(n * (n - 1)); + var b = n - 2; + skew[j] = (a / b) * g; + } else { + skew[j] = g; + } + } + return skew; +} + +function kurtosis(matrix, unbiased) { + if (typeof(unbiased) === 'undefined') unbiased = true; + var means = mean(matrix); + var n = matrix.length, m = matrix[0].length; + var kurt = new Array(m); + + for (var j = 0; j < m; j++) { + var s2 = 0, s4 = 0; + for (var i = 0; i < n; i++) { + var dev = matrix[i][j] - means[j]; + s2 += dev * dev; + s4 += dev * dev * dev * dev; + } + var m2 = s2 / n; + var m4 = s4 / n; + + if (unbiased) { + var v = s2 / (n - 1); + var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3)); + var b = s4 / (v * v); + var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3)); + kurt[j] = a * b - 3 * c; + } else { + kurt[j] = m4 / (m2 * m2) - 3; + } + } + return kurt; +} + +function standardError(matrix) { + var samples = matrix.length; + var standardDeviations = standardDeviation(matrix), l = standardDeviations.length; + var standardErrors = new Array(l); + var sqrtN = Math.sqrt(samples); + + for (var i = 0; i < l; i++) { + standardErrors[i] = standardDeviations[i] / sqrtN; + } + return standardErrors; +} + +function covariance(matrix, dimension) { + return scatter(matrix, undefined, dimension); +} + +function scatter(matrix, divisor, dimension) { + if (typeof(dimension) === 'undefined') { + dimension = 0; + } + if (typeof(divisor) === 'undefined') { + if (dimension === 0) { + divisor = matrix.length - 1; + } else if (dimension === 1) { + divisor = matrix[0].length - 1; + } + } + var means = mean(matrix, dimension), + rows = matrix.length; + if (rows === 0) { + return [[]]; + } + var cols = matrix[0].length, + cov, i, j, s, k; + + if (dimension === 0) { + cov = new Array(cols); + for (i = 0; i < cols; i++) { + cov[i] = new Array(cols); + } + for (i = 0; i < cols; i++) { + for (j = i; j < cols; j++) { + s = 0; + for (k = 0; k < rows; k++) { + s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); + } + s /= divisor; + cov[i][j] = s; + cov[j][i] = s; + } + } + } else if (dimension === 1) { + cov = new Array(rows); + for (i = 0; i < rows; i++) { + cov[i] = new Array(rows); + } + for (i = 0; i < rows; i++) { + for (j = i; j < rows; j++) { + s = 0; + for (k = 0; k < cols; k++) { + s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); + } + s /= divisor; + cov[i][j] = s; + cov[j][i] = s; + } + } + } else { + throw new Error('Invalid dimension'); + } + + return cov; +} + +function correlation(matrix) { + var means = mean(matrix), + standardDeviations = standardDeviation(matrix, true, means), + scores = zScores(matrix, means, standardDeviations), + rows = matrix.length, + cols = matrix[0].length, + i, j; + + var cor = new Array(cols); + for (i = 0; i < cols; i++) { + cor[i] = new Array(cols); + } + for (i = 0; i < cols; i++) { + for (j = i; j < cols; j++) { + var c = 0; + for (var k = 0, l = scores.length; k < l; k++) { + c += scores[k][j] * scores[k][i]; + } + c /= rows - 1; + cor[i][j] = c; + cor[j][i] = c; + } + } + return cor; +} + +function zScores(matrix, means, standardDeviations) { + means = means || mean(matrix); + if (typeof(standardDeviations) === 'undefined') standardDeviations = standardDeviation(matrix, true, means); + return standardize(center(matrix, means, false), standardDeviations, true); +} + +function center(matrix, means, inPlace) { + means = means || mean(matrix); + var result = matrix, + l = matrix.length, + i, j, jj; + + if (!inPlace) { + result = new Array(l); + for (i = 0; i < l; i++) { + result[i] = new Array(matrix[i].length); + } + } + + for (i = 0; i < l; i++) { + var row = result[i]; + for (j = 0, jj = row.length; j < jj; j++) { + row[j] = matrix[i][j] - means[j]; + } + } + return result; +} + +function standardize(matrix, standardDeviations, inPlace) { + if (typeof(standardDeviations) === 'undefined') standardDeviations = standardDeviation(matrix); + var result = matrix, + l = matrix.length, + i, j, jj; + + if (!inPlace) { + result = new Array(l); + for (i = 0; i < l; i++) { + result[i] = new Array(matrix[i].length); + } + } + + for (i = 0; i < l; i++) { + var resultRow = result[i]; + var sourceRow = matrix[i]; + for (j = 0, jj = resultRow.length; j < jj; j++) { + if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) { + resultRow[j] = sourceRow[j] / standardDeviations[j]; + } + } + } + return result; +} + +function weightedVariance(matrix, weights) { + var means = mean(matrix); + var rows = matrix.length; + if (rows === 0) return []; + var cols = matrix[0].length; + var vari = new Array(cols); + + for (var j = 0; j < cols; j++) { + var sum = 0; + var a = 0, b = 0; + + for (var i = 0; i < rows; i++) { + var z = matrix[i][j] - means[j]; + var w = weights[i]; + + sum += w * (z * z); + b += w; + a += w * w; + } + + vari[j] = sum * (b / (b * b - a)); + } + + return vari; +} + +function weightedMean(matrix, weights, dimension) { + if (typeof(dimension) === 'undefined') { + dimension = 0; + } + var rows = matrix.length; + if (rows === 0) return []; + var cols = matrix[0].length, + means, i, ii, j, w, row; + + if (dimension === 0) { + means = new Array(cols); + for (i = 0; i < cols; i++) { + means[i] = 0; + } + for (i = 0; i < rows; i++) { + row = matrix[i]; + w = weights[i]; + for (j = 0; j < cols; j++) { + means[j] += row[j] * w; + } + } + } else if (dimension === 1) { + means = new Array(rows); + for (i = 0; i < rows; i++) { + means[i] = 0; + } + for (j = 0; j < rows; j++) { + row = matrix[j]; + w = weights[j]; + for (i = 0; i < cols; i++) { + means[j] += row[i] * w; + } + } + } else { + throw new Error('Invalid dimension'); + } + + var weightSum = arrayStat.sum(weights); + if (weightSum !== 0) { + for (i = 0, ii = means.length; i < ii; i++) { + means[i] /= weightSum; + } + } + return means; +} + +function weightedCovariance(matrix, weights, means, dimension) { + dimension = dimension || 0; + means = means || weightedMean(matrix, weights, dimension); + var s1 = 0, s2 = 0; + for (var i = 0, ii = weights.length; i < ii; i++) { + s1 += weights[i]; + s2 += weights[i] * weights[i]; + } + var factor = s1 / (s1 * s1 - s2); + return weightedScatter(matrix, weights, means, factor, dimension); +} + +function weightedScatter(matrix, weights, means, factor, dimension) { + dimension = dimension || 0; + means = means || weightedMean(matrix, weights, dimension); + if (typeof(factor) === 'undefined') { + factor = 1; + } + var rows = matrix.length; + if (rows === 0) { + return [[]]; + } + var cols = matrix[0].length, + cov, i, j, k, s; + + if (dimension === 0) { + cov = new Array(cols); + for (i = 0; i < cols; i++) { + cov[i] = new Array(cols); + } + for (i = 0; i < cols; i++) { + for (j = i; j < cols; j++) { + s = 0; + for (k = 0; k < rows; k++) { + s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); + } + cov[i][j] = s * factor; + cov[j][i] = s * factor; + } + } + } else if (dimension === 1) { + cov = new Array(rows); + for (i = 0; i < rows; i++) { + cov[i] = new Array(rows); + } + for (i = 0; i < rows; i++) { + for (j = i; j < rows; j++) { + s = 0; + for (k = 0; k < cols; k++) { + s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); + } + cov[i][j] = s * factor; + cov[j][i] = s * factor; + } + } + } else { + throw new Error('Invalid dimension'); + } + + return cov; +} + +module.exports = { + entropy: entropy, + mean: mean, + standardDeviation: standardDeviation, + variance: variance, + median: median, + mode: mode, + skewness: skewness, + kurtosis: kurtosis, + standardError: standardError, + covariance: covariance, + scatter: scatter, + correlation: correlation, + zScores: zScores, + center: center, + standardize: standardize, + weightedVariance: weightedVariance, + weightedMean: weightedMean, + weightedCovariance: weightedCovariance, + weightedScatter: weightedScatter +}; + + +/***/ }), +/* 159 */ +/***/ (function(module, exports, __webpack_require__) { - NodeHexagonal.prototype = new NodeSquare; - NodeHexagonal.prototype.constructor = NodeHexagonal; +var NodeSquare = __webpack_require__(42); - NodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) { - return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z)); - }; +function NodeHexagonal(x, y, weights, som) { - NodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) { - var distX = Math.abs(this.hX - otherNode.hX), - distY = Math.abs(this.y - otherNode.y), - distZ = Math.abs(this.z - otherNode.z); - return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ)); - }; + NodeSquare.call(this, x, y, weights, som); - NodeHexagonal.prototype.getPosition = function getPosition() { - throw new Error('Unimplemented : cannot get position of the points for hexagonal grid'); - }; + this.hX = x - Math.floor(y / 2); + this.z = 0 - this.hX - y; - module.exports = NodeHexagonal; +} -/***/ }, -/* 158 */ -/***/ function(module, exports, __webpack_require__) { +NodeHexagonal.prototype = new NodeSquare; +NodeHexagonal.prototype.constructor = NodeHexagonal; - module.exports = __webpack_require__(159); +NodeHexagonal.prototype.getDistance = function getDistanceHexagonal(otherNode) { + return Math.max(Math.abs(this.hX - otherNode.hX), Math.abs(this.y - otherNode.y), Math.abs(this.z - otherNode.z)); +}; +NodeHexagonal.prototype.getDistanceTorus = function getDistanceTorus(otherNode) { + var distX = Math.abs(this.hX - otherNode.hX), + distY = Math.abs(this.y - otherNode.y), + distZ = Math.abs(this.z - otherNode.z); + return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY), Math.min(distZ, this.som.gridDim.z - distZ)); +}; -/***/ }, -/* 159 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - - var Layer = __webpack_require__(160); - var Matrix = __webpack_require__(14); - - class FeedforwardNeuralNetwork { - /** - * Constructor for the FNN (Feedforward Neural Networks) that takes an Array of Numbers, - * those numbers corresponds to the size of each layer in the FNN, the first and the last number of the array corresponds to the input and the - * output layer respectively. - * - * @constructor - */ - constructor(X, Y) { - if (X === true) { - const model = Y; - this.layers = model.layers; - this.inputSize = model.inputSize; - this.outputSize = model.outputSize; - } else { - if (X.length !== Y.length) - throw new RangeError("X and Y must have the same size."); - this.X = X; - this.Y = Y; - this.inputSize = X[0].length; - this.outputSize = Y[0].length; - } - } - - /** - * Build the Neural Network with an array that represent each hidden layer size. - * - * @param {Array} layersSize - Array of sizes of each layer. - */ - buildNetwork(layersSize) { - layersSize.push(this.outputSize); - - this.layers = new Array(layersSize.length); - - for (var i = 0; i < layersSize.length; ++i) { - var inSize = (i == 0) ? this.inputSize : layersSize[i - 1]; - this.layers[i] = new Layer(inSize, layersSize[i]); - } - - this.layers[this.layers.length - 1].isSigmoid = false; - } - - /** - * Function that applies a forward propagation over the Neural Network - * with one case of the dataset. - * @param {Array} input - case of the dataset. - * @returns {Array} result of the forward propagation. - */ - forwardNN(input) { - var results = input.slice(); - - for (var i = 0; i < this.layers.length; ++i) { - results = this.layers[i].forward(results); - } - - return results; - } - - /** - * Function that makes one iteration (epoch) over the Neural Network with one element - * of the dataset with corresponding prediction; the other two arguments are the - * learning rate and the momentum that is the regularization term for the parameters - * of each perceptron in the Neural Network. - * @param {Array} data - Element of the dataset. - * @param {Array} prediction - Prediction over the data object. - * @param {Number} learningRate - * @param momentum - the regularization term. - */ - iteration(data, prediction, learningRate, momentum) { - var forwardResult = this.forwardNN(data); - var error = new Array(forwardResult.length); - - if (typeof(prediction) === 'number') - prediction = [prediction]; - - for (var i = 0; i < error.length; i++) { - error[i] = prediction[i] - forwardResult[i]; - } - - var lengthLayers = this.layers.length; - - for (i = 0; i < lengthLayers; ++i) { - error = this.layers[lengthLayers - 1 - i].train(error, learningRate, momentum); - } - } - - /** - * Method that train the neural network with a given training set with corresponding - * predictions. The options argument has an array of the number of perceptrons that we want in each hidden layer, the - * number of iterations (default 50) that we want to perform, the learning rate and the momentum that is the - * regularization term (default 0.1 for both) for the parameters of each perceptron in the Neural Network. - * - * options: - * * hiddenLayers - Array of number with each hidden layer size. - * * iterations - Number - * * learningRate - Number - * * momentum - Number - * - * @param {object} options - */ - train(options) { - if (options === undefined) options = {}; - - const trainingSet = this.X; - const predictions = this.Y; - - var hiddenLayers = options.hiddenLayers === undefined ? [10] : options.hiddenLayers; - var iterations = options.iterations === undefined ? 50 : options.iterations; - var learningRate = options.learningRate === undefined ? 0.1 : options.learningRate; - var momentum = options.momentum === undefined ? 0.1 : options.momentum; - - this.buildNetwork(hiddenLayers); - - for (var i = 0; i < iterations; ++i) { - for (var j = 0; j < predictions.length; ++j) { - var index = randomIntegerFromInterval(0, predictions.length - 1); - this.iteration(trainingSet[index], predictions[index], learningRate, momentum); - } - } - } - - /** - * Function that with a dataset, gives all the predictions for this dataset. - * @param {Matrix} dataset. - * @returns {Array} predictions - */ - predict(dataset) { - if (dataset[0].length !== this.inputSize) - throw new RangeError("The dataset columns must have the same size of the " + - "input layer"); - var result = new Array(dataset.length); - for (var i = 0; i < dataset.length; i++) { - result[i] = this.forwardNN(dataset[i]); - } - - result = new Matrix(result); - //return result.columns === 1 ? result.getColumn(0) : result; - return result; - - } - - toJSON() { - return { - name: 'FNN', - layers: this.layers, - inputSize: this.inputSize, - outputSize: this.outputSize - }; - } - - static load(model) { - if (model.name !== 'FNN') - throw new RangeError('Invalid model: ' + model.name); - return new FeedforwardNeuralNetwork(true, model); - } - } +NodeHexagonal.prototype.getPosition = function getPosition() { + throw new Error('Unimplemented : cannot get position of the points for hexagonal grid'); +}; - module.exports = FeedforwardNeuralNetwork; +module.exports = NodeHexagonal; - /** - * Function that returns a random number between two numbers (inclusive) - * @param {number} min - lower bound - * @param {number} max - upper bound. - * @returns {number} random number - */ - function randomIntegerFromInterval(min, max) { - return Math.floor(Math.random() * (max - min + 1) + min); - } +/***/ }), +/* 160 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var arrayStat = __webpack_require__(14); + +function compareNumbers(a, b) { + return a - b; +} + +exports.max = function max(matrix) { + var max = -Infinity; + for (var i = 0; i < matrix.length; i++) { + for (var j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] > max) max = matrix[i][j]; + } + } + return max; +}; + +exports.min = function min(matrix) { + var min = Infinity; + for (var i = 0; i < matrix.length; i++) { + for (var j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] < min) min = matrix[i][j]; + } + } + return min; +}; + +exports.minMax = function minMax(matrix) { + var min = Infinity; + var max = -Infinity; + for (var i = 0; i < matrix.length; i++) { + for (var j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] < min) min = matrix[i][j]; + if (matrix[i][j] > max) max = matrix[i][j]; + } + } + return { + min:min, + max:max + }; +}; + +exports.entropy = function entropy(matrix, eps) { + if (typeof (eps) === 'undefined') { + eps = 0; + } + var sum = 0, + l1 = matrix.length, + l2 = matrix[0].length; + for (var i = 0; i < l1; i++) { + for (var j = 0; j < l2; j++) { + sum += matrix[i][j] * Math.log(matrix[i][j] + eps); + } + } + return -sum; +}; + +exports.mean = function mean(matrix, dimension) { + if (typeof (dimension) === 'undefined') { + dimension = 0; + } + var rows = matrix.length, + cols = matrix[0].length, + theMean, N, i, j; + + if (dimension === -1) { + theMean = [0]; + N = rows * cols; + for (i = 0; i < rows; i++) { + for (j = 0; j < cols; j++) { + theMean[0] += matrix[i][j]; + } + } + theMean[0] /= N; + } else if (dimension === 0) { + theMean = new Array(cols); + N = rows; + for (j = 0; j < cols; j++) { + theMean[j] = 0; + for (i = 0; i < rows; i++) { + theMean[j] += matrix[i][j]; + } + theMean[j] /= N; + } + } else if (dimension === 1) { + theMean = new Array(rows); + N = cols; + for (j = 0; j < rows; j++) { + theMean[j] = 0; + for (i = 0; i < cols; i++) { + theMean[j] += matrix[j][i]; + } + theMean[j] /= N; + } + } else { + throw new Error('Invalid dimension'); + } + return theMean; +}; + +exports.sum = function sum(matrix, dimension) { + if (typeof (dimension) === 'undefined') { + dimension = 0; + } + var rows = matrix.length, + cols = matrix[0].length, + theSum, i, j; + + if (dimension === -1) { + theSum = [0]; + for (i = 0; i < rows; i++) { + for (j = 0; j < cols; j++) { + theSum[0] += matrix[i][j]; + } + } + } else if (dimension === 0) { + theSum = new Array(cols); + for (j = 0; j < cols; j++) { + theSum[j] = 0; + for (i = 0; i < rows; i++) { + theSum[j] += matrix[i][j]; + } + } + } else if (dimension === 1) { + theSum = new Array(rows); + for (j = 0; j < rows; j++) { + theSum[j] = 0; + for (i = 0; i < cols; i++) { + theSum[j] += matrix[j][i]; + } + } + } else { + throw new Error('Invalid dimension'); + } + return theSum; +}; + +exports.product = function product(matrix, dimension) { + if (typeof (dimension) === 'undefined') { + dimension = 0; + } + var rows = matrix.length, + cols = matrix[0].length, + theProduct, i, j; + + if (dimension === -1) { + theProduct = [1]; + for (i = 0; i < rows; i++) { + for (j = 0; j < cols; j++) { + theProduct[0] *= matrix[i][j]; + } + } + } else if (dimension === 0) { + theProduct = new Array(cols); + for (j = 0; j < cols; j++) { + theProduct[j] = 1; + for (i = 0; i < rows; i++) { + theProduct[j] *= matrix[i][j]; + } + } + } else if (dimension === 1) { + theProduct = new Array(rows); + for (j = 0; j < rows; j++) { + theProduct[j] = 1; + for (i = 0; i < cols; i++) { + theProduct[j] *= matrix[j][i]; + } + } + } else { + throw new Error('Invalid dimension'); + } + return theProduct; +}; + +exports.standardDeviation = function standardDeviation(matrix, means, unbiased) { + var vari = exports.variance(matrix, means, unbiased), l = vari.length; + for (var i = 0; i < l; i++) { + vari[i] = Math.sqrt(vari[i]); + } + return vari; +}; + +exports.variance = function variance(matrix, means, unbiased) { + if (typeof (unbiased) === 'undefined') { + unbiased = true; + } + means = means || exports.mean(matrix); + var rows = matrix.length; + if (rows === 0) return []; + var cols = matrix[0].length; + var vari = new Array(cols); + + for (var j = 0; j < cols; j++) { + var sum1 = 0, sum2 = 0, x = 0; + for (var i = 0; i < rows; i++) { + x = matrix[i][j] - means[j]; + sum1 += x; + sum2 += x * x; + } + if (unbiased) { + vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1); + } else { + vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows; + } + } + return vari; +}; + +exports.median = function median(matrix) { + var rows = matrix.length, cols = matrix[0].length; + var medians = new Array(cols); + + for (var i = 0; i < cols; i++) { + var data = new Array(rows); + for (var j = 0; j < rows; j++) { + data[j] = matrix[j][i]; + } + data.sort(compareNumbers); + var N = data.length; + if (N % 2 === 0) { + medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5; + } else { + medians[i] = data[Math.floor(N / 2)]; + } + } + return medians; +}; + +exports.mode = function mode(matrix) { + var rows = matrix.length, + cols = matrix[0].length, + modes = new Array(cols), + i, j; + for (i = 0; i < cols; i++) { + var itemCount = new Array(rows); + for (var k = 0; k < rows; k++) { + itemCount[k] = 0; + } + var itemArray = new Array(rows); + var count = 0; + + for (j = 0; j < rows; j++) { + var index = itemArray.indexOf(matrix[j][i]); + if (index >= 0) { + itemCount[index]++; + } else { + itemArray[count] = matrix[j][i]; + itemCount[count] = 1; + count++; + } + } + + var maxValue = 0, maxIndex = 0; + for (j = 0; j < count; j++) { + if (itemCount[j] > maxValue) { + maxValue = itemCount[j]; + maxIndex = j; + } + } + + modes[i] = itemArray[maxIndex]; + } + return modes; +}; + +exports.skewness = function skewness(matrix, unbiased) { + if (typeof (unbiased) === 'undefined') unbiased = true; + var means = exports.mean(matrix); + var n = matrix.length, l = means.length; + var skew = new Array(l); + + for (var j = 0; j < l; j++) { + var s2 = 0, s3 = 0; + for (var i = 0; i < n; i++) { + var dev = matrix[i][j] - means[j]; + s2 += dev * dev; + s3 += dev * dev * dev; + } + + var m2 = s2 / n; + var m3 = s3 / n; + var g = m3 / Math.pow(m2, 3 / 2); + + if (unbiased) { + var a = Math.sqrt(n * (n - 1)); + var b = n - 2; + skew[j] = (a / b) * g; + } else { + skew[j] = g; + } + } + return skew; +}; + +exports.kurtosis = function kurtosis(matrix, unbiased) { + if (typeof (unbiased) === 'undefined') unbiased = true; + var means = exports.mean(matrix); + var n = matrix.length, m = matrix[0].length; + var kurt = new Array(m); + + for (var j = 0; j < m; j++) { + var s2 = 0, s4 = 0; + for (var i = 0; i < n; i++) { + var dev = matrix[i][j] - means[j]; + s2 += dev * dev; + s4 += dev * dev * dev * dev; + } + var m2 = s2 / n; + var m4 = s4 / n; + + if (unbiased) { + var v = s2 / (n - 1); + var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3)); + var b = s4 / (v * v); + var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3)); + kurt[j] = a * b - 3 * c; + } else { + kurt[j] = m4 / (m2 * m2) - 3; + } + } + return kurt; +}; + +exports.standardError = function standardError(matrix) { + var samples = matrix.length; + var standardDeviations = exports.standardDeviation(matrix); + var l = standardDeviations.length; + var standardErrors = new Array(l); + var sqrtN = Math.sqrt(samples); + + for (var i = 0; i < l; i++) { + standardErrors[i] = standardDeviations[i] / sqrtN; + } + return standardErrors; +}; + +exports.covariance = function covariance(matrix, dimension) { + return exports.scatter(matrix, undefined, dimension); +}; + +exports.scatter = function scatter(matrix, divisor, dimension) { + if (typeof (dimension) === 'undefined') { + dimension = 0; + } + if (typeof (divisor) === 'undefined') { + if (dimension === 0) { + divisor = matrix.length - 1; + } else if (dimension === 1) { + divisor = matrix[0].length - 1; + } + } + var means = exports.mean(matrix, dimension); + var rows = matrix.length; + if (rows === 0) { + return [[]]; + } + var cols = matrix[0].length, + cov, i, j, s, k; + + if (dimension === 0) { + cov = new Array(cols); + for (i = 0; i < cols; i++) { + cov[i] = new Array(cols); + } + for (i = 0; i < cols; i++) { + for (j = i; j < cols; j++) { + s = 0; + for (k = 0; k < rows; k++) { + s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); + } + s /= divisor; + cov[i][j] = s; + cov[j][i] = s; + } + } + } else if (dimension === 1) { + cov = new Array(rows); + for (i = 0; i < rows; i++) { + cov[i] = new Array(rows); + } + for (i = 0; i < rows; i++) { + for (j = i; j < rows; j++) { + s = 0; + for (k = 0; k < cols; k++) { + s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); + } + s /= divisor; + cov[i][j] = s; + cov[j][i] = s; + } + } + } else { + throw new Error('Invalid dimension'); + } + + return cov; +}; + +exports.correlation = function correlation(matrix) { + var means = exports.mean(matrix), + standardDeviations = exports.standardDeviation(matrix, true, means), + scores = exports.zScores(matrix, means, standardDeviations), + rows = matrix.length, + cols = matrix[0].length, + i, j; + + var cor = new Array(cols); + for (i = 0; i < cols; i++) { + cor[i] = new Array(cols); + } + for (i = 0; i < cols; i++) { + for (j = i; j < cols; j++) { + var c = 0; + for (var k = 0, l = scores.length; k < l; k++) { + c += scores[k][j] * scores[k][i]; + } + c /= rows - 1; + cor[i][j] = c; + cor[j][i] = c; + } + } + return cor; +}; + +exports.zScores = function zScores(matrix, means, standardDeviations) { + means = means || exports.mean(matrix); + if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means); + return exports.standardize(exports.center(matrix, means, false), standardDeviations, true); +}; + +exports.center = function center(matrix, means, inPlace) { + means = means || exports.mean(matrix); + var result = matrix, + l = matrix.length, + i, j, jj; + + if (!inPlace) { + result = new Array(l); + for (i = 0; i < l; i++) { + result[i] = new Array(matrix[i].length); + } + } + + for (i = 0; i < l; i++) { + var row = result[i]; + for (j = 0, jj = row.length; j < jj; j++) { + row[j] = matrix[i][j] - means[j]; + } + } + return result; +}; + +exports.standardize = function standardize(matrix, standardDeviations, inPlace) { + if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix); + var result = matrix, + l = matrix.length, + i, j, jj; + + if (!inPlace) { + result = new Array(l); + for (i = 0; i < l; i++) { + result[i] = new Array(matrix[i].length); + } + } + + for (i = 0; i < l; i++) { + var resultRow = result[i]; + var sourceRow = matrix[i]; + for (j = 0, jj = resultRow.length; j < jj; j++) { + if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) { + resultRow[j] = sourceRow[j] / standardDeviations[j]; + } + } + } + return result; +}; + +exports.weightedVariance = function weightedVariance(matrix, weights) { + var means = exports.mean(matrix); + var rows = matrix.length; + if (rows === 0) return []; + var cols = matrix[0].length; + var vari = new Array(cols); + + for (var j = 0; j < cols; j++) { + var sum = 0; + var a = 0, b = 0; + + for (var i = 0; i < rows; i++) { + var z = matrix[i][j] - means[j]; + var w = weights[i]; + + sum += w * (z * z); + b += w; + a += w * w; + } + + vari[j] = sum * (b / (b * b - a)); + } + + return vari; +}; + +exports.weightedMean = function weightedMean(matrix, weights, dimension) { + if (typeof (dimension) === 'undefined') { + dimension = 0; + } + var rows = matrix.length; + if (rows === 0) return []; + var cols = matrix[0].length, + means, i, ii, j, w, row; + + if (dimension === 0) { + means = new Array(cols); + for (i = 0; i < cols; i++) { + means[i] = 0; + } + for (i = 0; i < rows; i++) { + row = matrix[i]; + w = weights[i]; + for (j = 0; j < cols; j++) { + means[j] += row[j] * w; + } + } + } else if (dimension === 1) { + means = new Array(rows); + for (i = 0; i < rows; i++) { + means[i] = 0; + } + for (j = 0; j < rows; j++) { + row = matrix[j]; + w = weights[j]; + for (i = 0; i < cols; i++) { + means[j] += row[i] * w; + } + } + } else { + throw new Error('Invalid dimension'); + } + + var weightSum = arrayStat.sum(weights); + if (weightSum !== 0) { + for (i = 0, ii = means.length; i < ii; i++) { + means[i] /= weightSum; + } + } + return means; +}; + +exports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) { + dimension = dimension || 0; + means = means || exports.weightedMean(matrix, weights, dimension); + var s1 = 0, s2 = 0; + for (var i = 0, ii = weights.length; i < ii; i++) { + s1 += weights[i]; + s2 += weights[i] * weights[i]; + } + var factor = s1 / (s1 * s1 - s2); + return exports.weightedScatter(matrix, weights, means, factor, dimension); +}; + +exports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) { + dimension = dimension || 0; + means = means || exports.weightedMean(matrix, weights, dimension); + if (typeof (factor) === 'undefined') { + factor = 1; + } + var rows = matrix.length; + if (rows === 0) { + return [[]]; + } + var cols = matrix[0].length, + cov, i, j, k, s; + + if (dimension === 0) { + cov = new Array(cols); + for (i = 0; i < cols; i++) { + cov[i] = new Array(cols); + } + for (i = 0; i < cols; i++) { + for (j = i; j < cols; j++) { + s = 0; + for (k = 0; k < rows; k++) { + s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]); + } + cov[i][j] = s * factor; + cov[j][i] = s * factor; + } + } + } else if (dimension === 1) { + cov = new Array(rows); + for (i = 0; i < rows; i++) { + cov[i] = new Array(rows); + } + for (i = 0; i < rows; i++) { + for (j = i; j < rows; j++) { + s = 0; + for (k = 0; k < cols; k++) { + s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]); + } + cov[i][j] = s * factor; + cov[j][i] = s * factor; + } + } + } else { + throw new Error('Invalid dimension'); + } + + return cov; +}; + + +/***/ }), +/* 161 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Function that creates the tree + * @param {Array } X - chemical shifts of the signal + * @param {Array } Y - intensity of the signal + * @param {number} from - the low limit of x + * @param {number} to - the top limit of x + * @param {number} minWindow - smallest range to accept in x + * @param {number} threshold - smallest range to accept in y + * @returns {{sum: number, center: number, left: {json}, right: {json}}} + * left and right have the same structure than the parent, or have a + * undefined value if are leafs + */ +function createTree (X, Y, from, to, minWindow, threshold) { + minWindow = minWindow || 0.16; + threshold = threshold || 0.01; + if ((to - from) < minWindow) + return undefined; + var sum = 0; + for (var i = 0; X[i] < to; i++) { + if (X[i] > from) + sum += Y[i]; + } + if (sum < threshold) { + return undefined; + } + var center = 0; + for (var j = 0; X[j] < to; j++) { + if (X[i] > from) + center += X[j] * Y[j]; + } + center = center / sum; + if (((center - from) < 10e-6) || ((to - center) < 10e-6)) return undefined; + if ((center - from) < (minWindow /4)) { + return createTree(X, Y, center, to, minWindow, threshold); + } + else { + if ((to - center) < (minWindow / 4)) { + return createTree(X, Y, from, center, minWindow, threshold); + } + else { + return { + 'sum': sum, + 'center': center, + 'left': createTree(X, Y, from, center, minWindow, threshold), + 'right': createTree(X, Y, center, to, minWindow, threshold) + }; + } + } +} + +/** + * Similarity between two nodes + * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node + * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node + * @param {number} alpha - weights the relative importance of intensity vs. shift match + * @param {number} beta - weights the relative importance of node matching and children matching + * @param {number} gamma - controls the attenuation of the effect of chemical shift differences + * @returns {number} similarity measure between tree nodes + */ +function S(a, b, alpha, beta, gamma) { + if (a === undefined || b === undefined) { + return 0; + } + else { + var C = (alpha*Math.min(a.sum, b.sum)/Math.max(a.sum, b.sum)+ (1-alpha)*Math.exp(-gamma*Math.abs(a.center - b.center))); + } + return beta*C + (1-beta)*(S(a.left, b.left, alpha, beta, gamma)+S(a.right, b.right, alpha, beta, gamma)); +} + +/** + * @type {number} alpha - weights the relative importance of intensity vs. shift match + * @type {number} beta - weights the relative importance of node matching and children matching + * @type {number} gamma - controls the attenuation of the effect of chemical shift differences + * @type {number} minWindow - smallest range to accept in x + * @type {number} threshold - smallest range to accept in y + */ +var defaultOptions = { + minWindow: 0.16, + threshold : 0.01, + alpha: 0.1, + beta: 0.33, + gamma: 0.001 +}; + +/** + * Builds a tree based in the spectra and compares this trees + * @param {{x: Array, y: Array}} A - first spectra to be compared + * @param {{x: Array, y: Array}} B - second spectra to be compared + * @param {number} from - the low limit of x + * @param {number} to - the top limit of x + * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options + * @returns {number} similarity measure between the spectra + */ +function tree(A, B, from, to, options) { + options = options || {}; + for (var o in defaultOptions) + if (!options.hasOwnProperty(o)) { + options[o] = defaultOptions[o]; + } + var Atree, Btree; + if (A.sum) + Atree = A; + else + Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold); + if (B.sum) + Btree = B; + else + Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold); + return S(Atree, Btree, options.alpha, options.beta, options.gamma); +} + +module.exports = { + calc: tree, + createTree: createTree +}; + +/***/ }), +/* 162 */ +/***/ (function(module, exports) { + +module.exports = newArray + +function newArray (n, value) { + n = n || 0 + var array = new Array(n) + for (var i = 0; i < n; i++) { + array[i] = value + } + return array +} + + +/***/ }), +/* 163 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = Number.isNaN || function (x) { + return x !== x; +}; + + +/***/ }), +/* 164 */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), +/* 165 */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + + +/***/ }), +/* 166 */ +/***/ (function(module, exports) { + +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} + +/***/ }), +/* 167 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(166); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = __webpack_require__(165); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(168), __webpack_require__(164))) + +/***/ }), +/* 168 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +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); -/***/ }, -/* 160 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - - var Matrix = __webpack_require__(14); - - class Layer { - /** - * Constructor that creates a layer for the neural network given the number of inputs - * and outputs. - * @param inputSize - * @param outputSize - * @constructor - */ - constructor(inputSize, outputSize) { - this.output = Matrix.zeros(1, outputSize).getRow(0); - this.input = Matrix.zeros(1, inputSize + 1).getRow(0); //+1 for bias term - this.deltaWeights = Matrix.zeros(1, (1 + inputSize) * outputSize).getRow(0); - this.weights = randomInitializeWeights(this.deltaWeights.length, inputSize, outputSize); - this.isSigmoid = true; - } - - /** - * Function that performs the forward propagation for the current layer - * @param {Array} input - output from the previous layer. - * @returns {Array} output - output for the next layer. - */ - forward(input) { - this.input = input.slice(); - this.input.push(1); // bias - var offs = 0; // offset used to get the current weights in the current perceptron - this.output = Matrix.zeros(1, this.output.length).getRow(0); - - for (var i = 0; i < this.output.length; ++i) { - for (var j = 0; j < this.input.length; ++j) { - this.output[i] += this.weights[offs + j] * this.input[j]; - } - if (this.isSigmoid) - this.output[i] = sigmoid(this.output[i]); - - offs += this.input.length; - } - - return this.output.slice(); - } - - /** - * Function that performs the backpropagation algorithm for the current layer. - * @param {Array} error - errors from the previous layer. - * @param {Number} learningRate - Learning rate for the actual layer. - * @param {Number} momentum - The regularizarion term. - * @returns {Array} the error for the next layer. - */ - train(error, learningRate, momentum) { - var offs = 0; - var nextError = Matrix.zeros(1, this.input.length).getRow(0);//new Array(this.input.length); - - for (var i = 0; i < this.output.length; ++i) { - var delta = error[i]; - - if (this.isSigmoid) - delta *= sigmoidGradient(this.output[i]); - - for (var j = 0; j < this.input.length; ++j) { - var index = offs + j; - nextError[j] += this.weights[index] * delta; - - var deltaWeight = this.input[j] * delta * learningRate; - this.weights[index] += this.deltaWeights[index] * momentum + deltaWeight; - this.deltaWeights[index] = deltaWeight; - } - - offs += this.input.length; - } - - return nextError; - } - } +// Clustering +var Clust = exports.Clust = {}; - module.exports = Layer; - - /** - * Function that create a random array of numbers between value depending - * on the input and output size given the following formula: - * - * sqrt(6) / sqrt(l_in + l_out); - * - * Taken from the coursera course of machine learning from Andrew Ng, - * Exercise 4, Page 7 of the exercise PDF. - * - * @param numberOfWeights - size of the array. - * @param inputSize - number of input of the current layer - * @param outputSize - number of output of the current layer - * @returns {Array} random array of numbers. - */ - function randomInitializeWeights(numberOfWeights, inputSize, outputSize) { - var epsilon = 2.449489742783 / Math.sqrt(inputSize + outputSize); - return Matrix.rand(1, numberOfWeights).mul(2 * epsilon).sub(epsilon).getRow(0); - } +Clust.kmeans = __webpack_require__(48); +Clust.hclust = __webpack_require__(47); - /** - * Function that calculates the sigmoid (logistic) function. - * @param value - * @returns {number} - */ - function sigmoid(value) { - return 1.0 / (1 + Math.exp(-value)); - } - /** - * Function that calculates the derivate of the sigmoid function. - * @param value - * @returns {number} - */ - function sigmoidGradient(value) { - return value * (1 - value); - } +// Neural networks +var NN = exports.NN = exports.nn = {}; +NN.SOM = __webpack_require__(58); +NN.FNN = __webpack_require__(46); -/***/ } -/******/ ]) -}); -; \ No newline at end of file + +/***/ }) +/******/ ]); +}); \ No newline at end of file diff --git a/dist/ml.min.js b/dist/ml.min.js index 8b6c89a..4d857df 100644 --- a/dist/ml.min.js +++ b/dist/ml.min.js @@ -1,127 +1,127 @@ -(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]={exports:{},id:O,loaded:!1};return I[O].call(E.exports,E,E.exports,R),E.loaded=!0,E.exports}var D={};return R.m=I,R.c=D,R.p='',R(0)}([function(I,R,D){'use strict';R.ArrayUtils=R.AU=D(1),R.BitArray=D(9),R.HashTable=D(11),R.Matrix=D(14),R.PadArray=D(34),R.Regression=D(36),R.BinarySearch=D(8);var O=R.Math={},E=D(59);O.Distance=E.distance,O.Similarity=E.similarity,O.SG=D(114),O.SGG=D(116),O.Matrix=R.Matrix,O.SparseMatrix=D(120),O.BellOptimizer=D(121),O.CurveFitting=D(122),O.Kernel=D(45);var G=R.Stat={};G.array=D(3).array,G.matrix=D(3).matrix,G.PCA=D(125),G.Performance=D(126);var Z=R.RNG={};Z.XSadd=D(128);var $=R.SL={};$.CV=D(129),$.CrossValidation=$.CV,$.SVM=D(132),$.KNN=D(133),$.NaiveBayes=D(136),$.PLS=D(138);var ee=R.Clust={};ee.kmeans=D(142),ee.hclust=D(144);var te=R.NN=R.nn={};te.SOM=D(155),te.FNN=D(158)},function(I,R,D){I.exports=R=D(2),R.getEquallySpacedData=D(6).getEquallySpacedData,R.SNV=D(7).SNV,R.binarySearch=D(8)},function(I,R,D){'use strict';function O(G){for(var Z=Array(G[0].length),$=0;$O&&(O=E[Z]);return O},R.min=function(E){for(var O=E[0],G=E.length,Z=1;ZZ&&(Z=E[ee]);return{min:G,max:Z}},R.arithmeticMean=function(E){for(var G=0,Z=E.length,$=0;$Z)throw new RangeError('sum of values is negative');return G/Z},R.median=function(E,G){G===void 0&&(G=!1),G||(E=[].concat(E).sort(D));var Z=E.length,$=Math.floor(Z/2);return 0==Z%2?0.5*(E[$-1]+E[$]):E[$]},R.variance=function(E,G){G===void 0&&(G=!0);for(var Z=R.mean(E),$=0,ee=E.length,te=0;tene&&(ne=Z[$],oe=$);return ee[oe]},R.covariance=function(E,G,Z){'undefined'==typeof Z&&(Z=!0);var $=R.mean(E),ee=R.mean(G);if(E.length!==G.length)throw'Vectors do not have the same dimensions';for(var te=0,ie=E.length,ne=0;neG&&(G=Z[$][ee]);return G},R.min=function(Z){for(var G=1/0,$=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;neue&&(ue=oe[ne],ce=ne);te[ie]=ae[ce]}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;oe=me)throw new Error('x must be an increasing serie');for(;0=fe?0:xe/fe,je++,je===te)break main;le=de,de+=ne,xe=0,fe=0}ue>le&&(xe+=ce,fe++),(ue==-Number.MAX_VALUE||1Z[1]&&(Z=Z.slice().reverse(),$=$.slice().reverse());var te=Z.length;if(te!==$.length)throw new RangeError('the x and y vector doesn\'t have the same size.');ee===void 0&&(ee={});var ie=ee.from===void 0?Z[0]:ee.from;if(isNaN(ie)||!isFinite(ie))throw new RangeError('\'From\' value must be a number');var ne=ee.to===void 0?Z[Z.length-1]:ee.to;if(isNaN(ne)||!isFinite(ne))throw new RangeError('\'To\' value must be a number');var oe=ie>ne;if(oe){var se=ie;ie=ne,ne=se}var ae=ee.numberOfPoints===void 0?100:ee.numberOfPoints;if(isNaN(ae)||!isFinite(ae))throw new RangeError('\'Number of points\' value must be a number');if(1>ae)throw new RangeError('the number of point must be higher than 1');var le='slot'===ee.variant?'slot':'smooth',de='slot'==le?O(Z,$,ie,ne,ae):D(Z,$,ie,ne,ae);return oe?de.reverse():de},R.integral=E},function(I,R,D){'use strict';R.SNV=function(G){for(var Z=O.mean(G),$=O.standardDeviation(G),ee=G.slice(),te=0;te>>1,te=O[ee];if(teE)$=ee-1;else return ee}return-(Z+1)}},function(I,R,D){'use strict';function O(G){for(var Z='',$=0;$>>0).toString(2);Z+='00000000000000000000000000000000'.substr(ee.length)+ee}return Z}var E=D(10);I.exports={count:function(Z){for(var $=0,ee=0;ee>8]+E[255&Z[ee]>>16]+E[255&Z[ee]>>24];return $},and:function(Z,$){for(var ee=Array(Z.length),te=0;te>5]&1<<31-$%32)},setBit:function(Z,$,ee){var te=$>>5,ie=1<<31-$%32;return Z[te]=ee?ie|Z[te]:~ie&Z[te],Z},toBinaryString:O,parseBinaryString:function(Z){for(var $=Z.length/32,ee=Array($),te=0;te<$;te++)ee[te]=0|parseInt(Z.substr(32*te,32),2);return ee},toHexString:function(Z){for(var $='',ee=0;ee>>0).toString(16);$+='00000000'.substr(te.length)+te}return $},parseHexString:function(Z){for(var $=Z.length/8,ee=Array($),te=0;te<$;te++)ee[te]=0|parseInt(Z.substr(8*te,8),16);return ee},toDebug:function(Z){for(var $=O(Z),ee='',te=0;teie;ie+=4)ee+=' '+$.substr(32*te+ie,4);teO;O++){for(var E=O,G=0;E;)E=E&E-1,G++;D[O]=G}I.exports=D},function(I,R,D){'use strict';function O(le,de){return 0|le*de}function E(le,de){return Math.min(le-2,0|le*de)}function G(le,de,ue){return te(Math.max(le+1,0|4*le/(3*de+ue)))}function Z(le,de,ue){return te(Math.max(le+1,0|4*le/(de+3*ue)))}const $=D(12),ee=D(13),te=ee.nextPrime,ie=ee.largestPrime,ne=0,oe=1,se=2;class le{constructor(de={}){if(de instanceof le)return this.table=de.table.slice(),this.values=de.values.slice(),this.state=de.state.slice(),this.minLoadFactor=de.minLoadFactor,this.maxLoadFactor=de.maxLoadFactor,this.distinct=de.distinct,this.freeEntries=de.freeEntries,this.lowWaterMark=de.lowWaterMark,void(this.highWaterMark=de.maxLoadFactor);const ue=de.initialCapacity===void 0?150:de.initialCapacity;if(0>ue)throw new RangeError(`initial capacity must not be less than zero: ${ue}`);const ce=de.minLoadFactor===void 0?1/6:de.minLoadFactor,me=de.maxLoadFactor===void 0?2/3:de.maxLoadFactor;if(0>ce||1<=ce)throw new RangeError(`invalid minLoadFactor: ${ce}`);if(0>=me||1<=me)throw new RangeError(`invalid maxLoadFactor: ${me}`);if(ce>=me)throw new RangeError(`minLoadFactor (${ce}) must be smaller than maxLoadFactor (${me})`);let pe=ue;pe=0|pe/me,pe=te(pe),0===pe&&(pe=1),this.table=$(pe,0),this.values=$(pe,0),this.state=$(pe,0),this.minLoadFactor=ce,this.maxLoadFactor=pe===ie?1:me,this.distinct=0,this.freeEntries=pe,this.lowWaterMark=0,this.highWaterMark=E(pe,this.maxLoadFactor)}clone(){return new le(this)}get size(){return this.distinct}get(de){const ue=this.indexOfKey(de);return 0>ue?0:this.values[ue]}set(de,ue){let ce=this.indexOfInsertion(de);if(0>ce)return ce=-ce-1,this.values[ce]=ue,!1;if(this.distinct>this.highWaterMark){const me=G(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);return this.rehash(me),this.set(de,ue)}if(this.table[ce]=de,this.values[ce]=ue,this.state[ce]===ne&&this.freeEntries--,this.state[ce]=oe,this.distinct++,1>this.freeEntries){const me=G(this.distinct+1,this.minLoadFactor,this.maxLoadFactor);this.rehash(me)}return!0}remove(de,ue){const ce=this.indexOfKey(de);return!(0>ce)}delete(de,ue){const ce=this.indexOfKey(de);return!(0>ce)}maybeShrinkCapacity(){if(this.distinctge&&(ge+=me);return ce[ge]===ne?-1:ge}containsValue(de){return 0<=this.indexOfValue(de)}indexOfValue(de){const ue=this.values,ce=this.state;for(var me=0;mege&&(ge+=me);if(ce[ge]===se){for(const xe=ge;ce[ge]!==ne&&(ce[ge]===se||ue[ge]!==de);)ge-=he,0>ge&&(ge+=me);ce[ge]===ne&&(ge=xe)}return ce[ge]===oe?-ge-1:ge}ensureCapacity(de){if(this.table.lengthZ-$),R.nextPrime=function($){let ee=O(G,$);return 0>ee&&(ee=-ee-1),G[ee]},R.largestPrime=E},function(I,R,D){'use strict';I.exports=D(15),I.exports.Decompositions=I.exports.DC=D(27)},function(I,R,D){'use strict';D(16);var O=D(17),E=D(18);class Z extends O(Array){constructor($,ee){if(1===arguments.length&&'number'==typeof $)return Array($);if(Z.isMatrix($))return $.clone();if(Number.isInteger($)&&0<$){if(super($),Number.isInteger(ee)&&0R&&(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=D)throw new RangeError('min should be strictly smaller than max');for(var O=this.constructor.empty(this.rows,this.columns),E=0;E=D)throw new RangeError('min should be strictly smaller than max');for(var O=this.constructor.empty(this.rows,this.columns),E=0;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;if(D>E||O>G||0>D||D>=this.rows||0>E||E>=this.rows||0>O||O>=this.columns||0>G||G>=this.columns)throw new RangeError('Argument out of range');for(var Z=0;Z>','signPropagatingRightShift'],['>>>','rightShift','zeroFillRightShift']];for(var operator of operators)for(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]})),i=1;iE||E>Z)throw new RangeError('Row index out of range')},R.checkColumnIndex=function(O,E,G){var Z=G?O.columns:O.columns-1;if(0>E||E>Z)throw new RangeError('Column index out of range')},R.checkRowVector=function(O,E){if(E.to1DArray&&(E=E.to1DArray()),E.length!==O.columns)throw new RangeError('vector size must be the same as the number of columns');return E},R.checkColumnVector=function(O,E){if(E.to1DArray&&(E=E.to1DArray()),E.length!==O.rows)throw new RangeError('vector size must be the same as the number of rows');return E},R.checkIndices=function(O,E,G){var Z=E.some(ee=>{return 0>ee||ee>=O.rows}),$=G.some(ee=>{return 0>ee||ee>=O.columns});if(Z||$)throw new RangeError('Indices are out of range');if('object'!=typeof E||'object'!=typeof G)throw new TypeError('Unexpected type for row/column indices');return Array.isArray(E)||(E=Array.from(E)),Array.isArray(G)||(E=Array.from(G)),{row:E,column:G}},R.checkRange=function(O,E,G,Z,$){if(5!==arguments.length)throw new TypeError('Invalid argument type');var ee=Array.from(arguments).slice(1).some(function(te){return'number'!=typeof te});if(ee)throw new TypeError('Invalid argument type');if(E>G||Z>$||0>E||E>=O.rows||0>G||G>=O.rows||0>Z||Z>=O.columns||0>$||$>=O.columns)throw new RangeError('Submatrix indices are out of range')},R.getRange=function(O,E){for(var G=Array(E-O+1),Z=0;Zue[we][we]&&(me[we]=-me[we]),je=we;jehe[we+1]&&(he[we]=-he[we]),je=we+1;je=we&&Se!==we;Se--)if(ve=(Se===be?0:Math.abs(he[Se]))+(Se===we+1?0:Math.abs(he[Se-1])),Math.abs(me[Se])<=Ue*ve){me[Se]=0;break}Se===we?Ie=3:Se===be-1?Ie=1:(Ie=2,we=Se)}switch(we++,Ie){case 1:{for(Me=he[be-2],he[be-2]=0,ke=be-2;ke>=we;ke--)if(ve=Z(me[ke],Me),ze=me[ke]/ve,qe=Me/ve,me[ke]=ve,ke!==we&&(Me=-qe*he[ke-1],he[ke-1]=ze*he[ke-1]),ae)for(je=0;je_e&&(Le=-Le),Le=Oe/(_e+Le)),Me=(Ae+De)*(Ae-De)+Le,Fe=Ae*Ne,ke=we;ke=me[we]&&(me[we]=0>me[we]?-me[we]:0,ae))for(je=0;je<=Te;je++)ge[je][we]=-ge[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 te=this.threshold,ie=this.s.length,ne=E.zeros(ie,ie),oe;for(oe=0;oete?ee[se][ae]/this.s[ae]:0;var le=this.U,de=le.length,ue=le[0].length,ce=new E(ie,de),me,pe;for(se=0;seMath.abs(E)){var G=E/O;return Math.abs(O)*Math.sqrt(1+G*G)}if(0!==E){var G=O/E;return Math.abs(E)*Math.sqrt(1+G*G)}return 0},R.getEmpty2DArray=function(D,O){for(var E=Array(D),G=0;Gxe){qe=0;do{for(qe=qe+1,ce=de[xe],ye=(de[xe+1]-ce)/(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=ce-de[xe],pe=xe+2;pe=xe;pe--)for(ve=be,be=we,ze=Me,ce=we*le[pe],me=we*ye,je=ne(ye,le[pe]),le[pe+1]=Me*je,Me=le[pe]/je,we=ye/je,ye=we*de[pe]-Me*ce,de[pe+1]=me+Me*(we*ce+Me*de[pe]),he=0;heRe*Ie)}de[xe]=de[xe]+Ce,le[xe]=0}for(pe=0;pe=ye;xe--)de[xe]=le[xe][ye-1]/je,he+=de[xe]*de[xe];for(ge=Math.sqrt(he),0=ye;xe--)pe+=de[xe]*le[xe][fe];for(pe=pe/he,xe=ye;xe<=me;xe++)le[xe][fe]-=pe*de[xe]}for(xe=0;xe<=me;xe++){for(pe=0,fe=me;fe>=ye;fe--)pe+=de[fe]*le[xe][fe];for(pe=pe/he,fe=ye;fe<=me;fe++)le[xe][fe]-=pe*de[fe]}de[ye]=je*de[ye],le[ye][ye-1]=je*ge}}for(xe=0;xe=ce+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(ge=0,xe=ye;xe<=me;xe++)ge+=de[xe]*ue[xe][fe];for(ge=ge/de[ye]/le[ye][ye-1],xe=ye;xe<=me;xe++)ue[xe][fe]+=ge*de[xe]}}}function $(ae,le,de,ue,ce){var me=ae-1,pe=0,ge=ae-1,he=Math.pow(2,-52),xe=0,fe=0,ye=0,je=0,ke=0,we=0,be=0,ve=0,Se,Me,ze,qe,Ce,Ie,Re,De,Ve,Pe,Ae,Ne,_e,Oe,Le;for(Se=0;Sege)&&(de[Se]=ce[Se][Se],le[Se]=0),Me=Math.max(Se-1,0);Me=pe;){for(qe=me;qe>pe&&(we=Math.abs(ce[qe-1][qe-1])+Math.abs(ce[qe][qe]),0==we&&(we=fe),!(Math.abs(ce[qe][qe-1])=qe&&(be=ce[Ce][Ce],ke=De-be,we=Ve-be,ye=(ke*we-Re)/ce[Ce+1][Ce]+ce[Ce][Ce+1],je=ce[Ce+1][Ce+1]-be-ke-we,ke=ce[Ce+2][Ce+1],we=Math.abs(ye)+Math.abs(je)+Math.abs(ke),ye=ye/we,je=je/we,ke=ke/we,Ce!=qe)&&!(Math.abs(ce[Ce][Ce-1])*(Math.abs(je)+Math.abs(ke))Ce+2&&(ce[Se][Se-3]=0);for(ze=Ce;ze<=me-1&&(Oe=ze!==me-1,ze!=Ce&&(ye=ce[ze][ze-1],je=ce[ze+1][ze-1],ke=Oe?ce[ze+2][ze-1]:0,De=Math.abs(ye)+Math.abs(je)+Math.abs(ke),0!==De&&(ye=ye/De,je=je/De,ke=ke/De)),0!==De);ze++)if(we=Math.sqrt(ye*ye+je*je+ke*ke),0>ye&&(we=-we),0!==we){for(ze==Ce?qe!==Ce&&(ce[ze][ze-1]=-ce[ze][ze-1]):ce[ze][ze-1]=-we*De,ye=ye+we,De=ye/we,Ve=je/we,be=ke/we,je=je/ye,ke=ke/ye,Me=ze;Mele[Se])be=Re,we=ke;else if(qe=Se,0===le[Se]?ce[Se][me]=0===Re?-ke/(he*fe):-ke/Re:(De=ce[Se][Se+1],Ve=ce[Se+1][Se],je=(de[Se]-ye)*(de[Se]-ye)+le[Se]*le[Se],Ie=(De*we-be*ke)/je,ce[Se][me]=Ie,ce[Se+1][me]=Math.abs(De)>Math.abs(be)?(-ke-Re*Ie)/De:(-we-Ve*Ie)/be),Ie=Math.abs(ce[Se][me]),1je)for(qe=me-1,Math.abs(ce[me][me-1])>Math.abs(ce[me-1][me])?(ce[me-1][me-1]=je/ce[me][me-1],ce[me-1][me]=-(ce[me][me]-ye)/ce[me][me-1]):(Le=ee(0,-ce[me-1][me],ce[me-1][me-1]-ye,je),ce[me-1][me-1]=Le[0],ce[me-1][me]=Le[1]),ce[me][me-1]=0,ce[me][me]=1,Se=me-2;0<=Se;Se--){for(Pe=0,Ae=0,Me=qe;Me<=me;Me++)Pe=Pe+ce[Se][Me]*ce[Me][me-1],Ae=Ae+ce[Se][Me]*ce[Me][me];if(Re=ce[Se][Se]-ye,0>le[Se])be=Re,ke=Pe,we=Ae;else if(qe=Se,0===le[Se]?(Le=ee(-Pe,-Ae,Re,je),ce[Se][me-1]=Le[0],ce[Se][me]=Le[1]):(De=ce[Se][Se+1],Ve=ce[Se+1][Se],Ne=(de[Se]-ye)*(de[Se]-ye)+le[Se]*le[Se]-je*je,_e=2*(de[Se]-ye)*je,0===Ne&&0===_e&&(Ne=he*fe*(Math.abs(Re)+Math.abs(je)+Math.abs(De)+Math.abs(Ve)+Math.abs(be))),Le=ee(De*ke-be*Pe+je*Ae,De*we-be*Ae-je*Pe,Ne,_e),ce[Se][me-1]=Le[0],ce[Se][me]=Le[1],Math.abs(De)>Math.abs(be)+Math.abs(je)?(ce[Se+1][me-1]=(-Pe-Re*ce[Se][me-1]+je*ce[Se][me])/De,ce[Se+1][me]=(-Ae-Re*ce[Se][me]-je*ce[Se][me-1])/De):(Le=ee(-ke-Ve*ce[Se][me-1],-we-Ve*ce[Se][me],be,je),ce[Se+1][me-1]=Le[0],ce[Se+1][me]=Le[1])),Ie=Math.max(Math.abs(ce[Se][me-1]),Math.abs(ce[Se][me])),1ge)for(Me=Se;Me=pe;Me--)for(Se=pe;Se<=ge;Se++){for(be=0,ze=pe;ze<=Math.min(Me,ge);ze++)be=be+ue[Se][ze]*ce[ze][Me];ue[Se][Me]=be}}}function ee(ae,le,de,ue){var ce,me;return Math.abs(de)>Math.abs(ue)?(ce=ue/de,me=de+ce*ue,[(ae+ce*le)/me,(le-ce*ae)/me]):(ce=de/ue,me=ue+ce*de,[(ce*ae+le)/me,(ce*le-ae)/me])}const te=D(15),ie=D(29),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,ue=new te(ae,ae),ce,me;for(ce=0;cele[ce]&&(ue[ce][ce-1]=le[ce])}return ue}},I.exports=O},function(I,R,D){'use strict';function O(G){if(!(this instanceof O))return new O(G);G=E.checkMatrix(G);var Z=G.clone(),$=Z.rows,ee=Z.columns,te=Array($),ie=1,ne,oe,se,ae,le,de,ue,ce,me,pe;for(ne=0;ne<$;ne++)te[ne]=ne;for(me=Array($),oe=0;oeMath.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(Z,$),te=0;te$[se][se]&&(le=-le),ne=se;nete||ee.size[1]>te)throw new RangeError('expanded value should not be bigger than the data length');for(oe=0;oeMath.abs(ie-1)?'':ie)+'x',this.intercept){var ne=Math.abs(this.intercept),oe=ne===this.intercept?'+':'-';te+=' '+oe+' '+E(ne,ee)}}else te+=E(this.intercept,ee);return te}toLaTeX(ee){return this.toString(ee)}static load(ee){if('TheilSenRegression'!==ee.name)throw new TypeError('not a Theil-Sen model');return new $(!0,ee)}}I.exports=$},function(I,R,D){'use strict';R.distance=D(60),R.similarity=D(105)},function(I,R,D){'use strict';R.additiveSymmetric=D(61),R.avg=D(62),R.bhattacharyya=D(63),R.canberra=D(64),R.chebyshev=D(65),R.clark=D(66),R.czekanowski=D(67),R.dice=D(69),R.divergence=D(70),R.euclidean=D(47),R.fidelity=D(71),R.gower=D(72),R.harmonicMean=D(73),R.hellinger=D(74),R.innerProduct=D(75),R.intersection=D(76),R.jaccard=D(77),R.jeffreys=D(78),R.jensenDifference=D(79),R.jensenShannon=D(80),R.kdivergence=D(81),R.kulczynski=D(82),R.kullbackLeibler=D(83),R.kumarHassebrook=D(84),R.kumarJohnson=D(85),R.lorentzian=D(86),R.manhattan=D(87),R.matusita=D(88),R.minkowski=D(89),R.motyka=D(90),R.neyman=D(91),R.pearson=D(92),R.probabilisticSymmetric=D(93),R.ruzicka=D(94),R.soergel=D(95),R.sorensen=D(96),R.squared=D(97),R.squaredChord=D(98),R.squaredEuclidean=D(47).squared,R.taneja=D(99),R.tanimoto=D(100),R.topsoe=D(102),R.tree=D(103),R.waveHedges=D(104)},function(I,R){I.exports=function(O,E){for(var G=0,Z=O.length,$=0;G$&&(ne+=Z[oe]);if(ne$&&(se+=G[ae]*Z[ae]);return(se=se/ne,0.00001>se-$||0.00001>ee-se)?void 0:se-$ie.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=E(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=O.ones(ie.windowSize,ie.polynomial+1),de=-(ie.windowSize-1)/2,ue=0;ue=ne)for(var se=ie-ne+1;se<=ie;se++)oe*=se;return oe}function Z(ie,ne,oe,se,ae){for(var le=0,de=0;de<=se;de++)le+=(2*de+1)*(G(2*oe,de)/G(2*oe+de+1,de+1))*E(ie,oe,de,0)*E(ne,oe,de,ae);return le}function $(ie,ne,oe){for(var se=Array(ie),ae=Math.floor(ie/2),le=-ae;le<=ae;le++){se[le+ae]=Array(ie);for(var de=-ae;de<=ae;de++)se[le+ae][de+ae]=Z(de,le,ae,ne,oe)}return se}var ee=D(115);D(117);var te={windowSize:9,derivative:0,polynomial:3};I.exports=function(ne,oe,se){if(se=ee({},te,se),0==se.windowSize%2||5>se.windowSize||!Number.isInteger(se.windowSize))throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');if(se.windowSize>ne.length)throw new RangeError('Window size is higher than the data length '+se.windowSize+'>'+ne.length);if(0>se.derivative||!Number.isInteger(se.derivative))throw new RangeError('Derivative should be a positive integer');if(1>se.polynomial||!Number.isInteger(se.polynomial))throw new RangeError('Polynomial should be a positive integer');6<=se.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 ae=se.windowSize,le=Math.floor(ae/2),de=ne.length,ue=Array(de),ce=$(ae,se.polynomial,se.derivative),me=0,pe=!0;'[object Array]'===Object.prototype.toString.call(oe)?pe=!1:me=Math.pow(oe,se.derivative);for(var ge=0;geO&&(O=E[Z]);return O},R.min=function(E){for(var O=1/0,G=E.length,Z=0;ZZ&&(Z=E[ee]);return{min:G,max:Z}},R.arithmeticMean=function(E){for(var G=0,Z=E.length,$=0;$Z)throw new RangeError('sum of values is negative');return G/Z},R.median=function(E,G){G===void 0&&(G=!1),G||(E=E.slice().sort(D));var Z=E.length,$=Math.floor(Z/2);return 0==Z%2?0.5*(E[$-1]+E[$]):E[$]},R.variance=function(E,G){G===void 0&&(G=!0);for(var Z=R.mean(E),$=0,ee=E.length,te=0;tene&&(ne=Z[$],oe=$);return ee[oe]},R.covariance=function(E,G,Z){'undefined'==typeof Z&&(Z=!0);var $=R.mean(E),ee=R.mean(G);if(E.length!==G.length)throw'Vectors do not have the same dimensions';for(var te=0,ie=E.length,ne=0;neye&&(ye=pe[me],je=me);ue[ce]=he[je]}return ue},skewness:function(ae,le){'undefined'==typeof le&&(le=!0);for(var de=O(ae),ue=ae.length,ce=de.length,me=Array(ce),pe=0;pe{return this.get(O,D)===E&&E}),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.elements.maybeShrinkCapacity(),this}getNonZeros(){const R=this.cardinality,D=Array(R),O=Array(R),E=Array(R);var G=0;return this.forEachNonZero((Z,$,ee)=>{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=` - (function %name%(value) { - if (typeof value === 'number') return this.%name%S(value); - return this.%name%M(value); - }) - `,inplaceOperatorScalar=` - (function %name%S(value) { - this.forEachNonZero((i, j, v) => v %op% value); - return this; - }) - `,inplaceOperatorMatrix=` - (function %name%M(matrix) { - matrix.forEachNonZero((i, j, v) => { - this.set(i, j, this.get(i, j) %op% v); - return v; - }); - return this; - }) - `,staticOperator=` - (function %name%(matrix, value) { - var newMatrix = new SparseMatrix(matrix); - return newMatrix.%name%(value); - }) - `,inplaceMethod=` - (function %name%() { - this.forEachNonZero((i, j, v) => %method%(v)); - return this; - }) - `,staticMethod=` - (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;ile[0].rows)return null;var de=le[0],ue=le[1],ce=le[2],me=de.rows,pe=[me/Math.sqrt(ue.dot(ue))],ae=Object.create(ae.LMOptions||[3,100,0.001,0.001,0.001,0.01,0.01,11,9,1]),ge=Math.abs(de[0][0]-de[1][0]),he=new ne([[-ge/10000],[-0.001],[-ge/10000]]),xe=new ne([[se.x],[1],[se.width]]),fe=new ne([[se.x-ge],[0.75],[se.width/4]]),ye=new ne([[se.x+ge],[1.25],[4*se.width]]),je=te.optimize(E,xe,de,ue,pe,he,fe,ye,[],ae);return je=je.p,[je[0],[je[1][0]*ce],je[2]]}function $(oe,se,ae){ae=ae||{};var le=ee(oe,ae.percentage||0);if(null===le||3>le[0].rows)return null;var de=le[0],ue=le[1],ce=le[2],me=de.rows,pe=[me/Math.sqrt(ue.dot(ue))],ae=Object.create(ae.LMOptions||[3,100,0.001,0.001,0.001,0.01,0.01,11,9,1]),ge=Math.abs(de[0][0]-de[1][0]),he=new ne([[-ge/10000],[-0.001],[-ge/10000]]),he=new ne([[-Math.abs(de[0][0]-de[1][0])/1000],[-0.001],[-se.width/1000]]),xe=new ne([[se.x],[1],[se.width]]),fe=new ne([[se.x-ge],[0.75],[se.width/4]]),ye=new ne([[se.x+ge],[1.25],[4*se.width]]),je=te.optimize(G,xe,de,ue,pe,he,fe,ye,[],ae);return je=je.p,[je[0],[je[1][0]*ce],je[2]]}function ee(oe,se){var ae=oe.length,le=null,de=null,ue,ce,me=0,pe;if(2==ae){var ge=oe[0].length;if(le=Array(ge),de=Array(ge),ue=oe[0],ce=oe[1],'number'==typeof ue[0])for(pe=0;peme&&(me=ce[pe]);else if('object'==typeof ue[0])for(pe=0;peme&&(me=ce[pe][0])}else{var ge=ae;for(le=Array(ge),de=Array(ge),pe=0;peme&&(me=de[pe])}for(pe=0;pede[0].rows)return null;var ue=de[0],ce=de[1],me=de[2],pe=ue.rows,ge,he=[pe/ie.sqrt(ce.dot(ce))],le=Object.create(le||[3,100,0.001,0.001,0.001,0.01,0.01,11,9,1]),xe=ae.length,fe=new ne(3*xe,1),ye=new ne(3*xe,1),je=new ne(3*xe,1),ke=new ne(3*xe,1),we=Math.abs(ue[0][0]-ue[1][0]);for(ge=0;gede[0].rows)return null;var ue=de[0],ce=de[1],me=de[2],pe=ue.rows,ge,he=new ne(pe,1),xe=pe/ie.sqrt(ce.dot(ce));for(ge=0;gede[0].rows)return null;for(var ue=de[0],ce=de[1],me=de[2],pe=0,ge=ue.length,ye=[],ke=0,he,xe,fe,me,je;kede[0].rows)return null;for(var ue=de[0],ce=de[1],me=de[2],pe=0,ge=ue.length,ye=[],ke=0,he,xe,fe,me,je;keZ[ie][ne]?G[ie][ne]:Z[ie][ne];return te},solve:function(G,Z){return G.solve(Z)},inv:function(G){return'number'==typeof G?1/G:G.inverse()},sqrt:function(G){if('number'==typeof G)return Math.sqrt(G);for(var Z=G.rows,$=G.columns,ee=new O(Z,$),te=0;teoe[0].length,ae){oe=this._adjust(oe,se);const ue=oe.transposeView().mmul(oe).div(oe.rows-1);this._computeFromCovarianceMatrix(ue)}else{oe=this._adjust(oe,se);var le=new G(oe,{computeLeftSingularVectors:!1,computeRightSingularVectors:!0,autoTranspose:!0});this.U=le.rightSingularVectors;const ue=le.diagonal,ce=Array(ue.length);for(var de=0;deae/oe)}getCumulativeVariance(){for(var oe=this.getExplainedVariance(),se=1;seMath.sqrt(oe))}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(oe,se){if(this.center=!!se.center,this.scale=!!se.scale,oe=new O(oe),this.center){const le=$(oe),de=this.scale?ee(oe,le,!0):null;if(this.means=le,oe.subRowVector(le),this.scale){for(var ae=0;aete||te!==ie)throw new Error('When "all" option is false, the prediction matrix must be square and have at least 3 columns');for(var se=0;sewe.pred-be.pred):oe.sort((we,be)=>be.pred-we.pred);const le=this.cutoffs=[ne?Number.MIN_VALUE:Number.MAX_VALUE],de=this.fp=[0],ue=this.tp=[0];for(var ce=0,me=0,pe=oe[0].pred,ge=0,he=0,se=0;se{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.length,E=Array(O);for(var G=0;G{const O=D.cutoffs.slice();return O[0]=O[1],O}},function(I,R){'use strict';function D(te,ie){if(!(te instanceof ie))throw new TypeError('Cannot call a class as a function')}function O(te,ie){te>>>=0,ie>>>=0;var ne=65535&te,oe=te-ne;return(oe*ie>>>0)+ne*ie>>>0}function E(te){0===te.state[0]&&0===te.state[1]&&0===te.state[2]&&0===te.state[3]&&(te.state[0]=88,te.state[1]=83,te.state[2]=65,te.state[3]=68)}function G(te){var ie=te.state[0];ie^=ie<<15,ie^=ie>>>18,ie^=te.state[3]<<11,te.state[0]=te.state[1],te.state[1]=te.state[2],te.state[2]=te.state[3],te.state[3]=ie}Object.defineProperty(R,'__esModule',{value:!0});var Z=function(){function te(ie,ne){for(var oe=0;oe=arguments.length||void 0===arguments[0]?Date.now():arguments[0];D(this,te),this.state=new Uint32Array(4),this.init(ie)}return Z(te,[{key:'init',value:function(ne){this.state[0]=ne,this.state[1]=0,this.state[2]=0,this.state[3]=0;for(var oe=1;oe<$;oe++)this.state[3&oe]^=oe+O(1812433253,this.state[3&oe-1]^this.state[3&oe-1]>>>30>>>0)>>>0;E(this);for(var oe=0;oe<$;oe++)G(this)}},{key:'getUint32',value:function(){return G(this),this.state[3]+this.state[2]>>>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}}]),te}();R['default']=ee,I.exports=R['default']},function(I,R,D){'use strict';function O(ie,ne){if(ie.length!==ne.length)throw new Error('features and labels should have the same length')}function E(ie,ne){return Array(ie).fill(0).map(()=>Array(ne).fill(0))}function G(ie){var ne=new Set;for(let oe=0;oe=ie[de];)de++;if(0===ie[de-1]){for(le=de-1;1!==le;le--)ie[le]=-1;ie[de]=0,ne=se=0,ie[1]=1,oe=de-1}else{1$.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]*(pe-ge)/je;if(we>ye?we=ye:weMath.abs(xe-we))continue;ae[ie]=we,ae[te]=ae[te]+ee[te]*ee[ie]*(xe-we),de=this.b-pe-ee[te]*(ae[te]-he)*oe[te][te]-ee[ie]*(ae[ie]-xe)*oe[te][ie],ue=this.b-ge-ee[te]*(ae[te]-he)*oe[te][ie]-ee[ie]*(ae[ie]-xe)*oe[ie][ie],this.b=(de+ue)/2,ae[te]this.options.alphaTol&&(Se.push(this.X[te]),Me.push(ee[te]),ze.push(this.alphas[te]),this._supportVectorIdx.push(te));this.X=Se,this.Y=Me,this.N=Se.length,this.alphas=ze,this._trained=!0},O.prototype.predictOne=function($){var ee=this.marginOne($);return 0ie&&(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){'use strict';/** - * k-d Tree JavaScript - V 1.01 - * - * https://github.com/ubilabs/kd-tree-javascript - * - * @author Mircea Pricop , 2012 - * @author Martin Kleppe , 2012 - * @author Ubilabs http://ubilabs.net, 2012 - * @license MIT License - */function D(G,Z,$){this.obj=G,this.left=null,this.right=null,this.parent=$,this.dimension=Z}function O(G,Z,$){function ee(ie,ne,oe){var se=ne%$.length,ae,le;return 0===ie.length?null:1===ie.length?new D(ie[0],se,oe):(ie.sort(function(de,ue){return de[$[se]]-ue[$[se]]}),ae=Math.floor(ie.length/2),le=new D(ie[ae],se,oe),le.left=ee(ie.slice(0,ae),ne+1,le),le.right=ee(ie.slice(ae+1),ne+1,le),le)}var te=this;Array.isArray(G)?this.root=ee(G,0,null):function(ne){function oe(se){se.left&&(se.left.parent=se,oe(se.left)),se.right&&(se.right.parent=se,oe(se.right))}te.root=ne,oe(te.root)}(G,Z,$),this.toJSON=function(ie){ie||(ie=this.root);var ne=new D(ie.obj,ie.dimension,null);return ie.left&&(ne.left=te.toJSON(ie.left)),ie.right&&(ne.right=te.toJSON(ie.right)),ne},this.insert=function(ie){function ne(le,de){if(null===le)return de;var ue=$[le.dimension];return ie[ue]ne&&de.pop()}var pe=$[ue.dimension],ge=Z(ie,ue.obj),he={},me,xe,fe,ye;for(ye=0;ye<$.length;ye+=1)he[$[ye]]=ye===ue.dimension?ie[$[ye]]:ue.obj[$[ye]];return xe=Z(he,ue.obj),null===ue.right&&null===ue.left?void((de.size()oe&&(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;aeie&&(ie=oe,te=ne)}return te}var G=D(14),Z=D(140);class ee{constructor(te,ie){if(!0===te){const ne=ie;this.meanX=ne.meanX,this.stdDevX=ne.stdDevX,this.meanY=ne.meanY,this.stdDevY=ne.stdDevY,this.PBQ=G.checkMatrix(ne.PBQ),this.R2X=ne.R2X}else{if(te.length!==ie.length)throw new RangeError('The number of X rows must be equal to the number of Y rows');const ne=Z.featureNormalize(te);this.X=ne.result,this.meanX=ne.means,this.stdDevX=ne.std;const oe=Z.featureNormalize(ie);this.Y=oe.result,this.meanY=oe.means,this.stdDevY=oe.std}}train(te){te===void 0&&(te={});var ie=te.latentVectors;ie===void 0&&(ie=Math.min(this.X.length-1,this.X[0].length));var ne=te.tolerance;ne===void 0&&(ne=0.00001);for(var oe=this.X,se=this.Y,ae=oe.rows,le=oe.columns,de=se.rows,ue=se.columns,ce=oe.clone().mul(oe).sum(),me=se.clone().mul(se).sum(),pe=ie,ge=G.zeros(ae,pe),he=G.zeros(le,pe),xe=G.zeros(de,pe),fe=G.zeros(ue,pe),ye=G.zeros(pe,pe),je=he.clone(),ke=0;Z.norm(se)>ne&&kene;){var Ce=we.mmul(ze);Ce.div(Z.norm(Ce)),qe=Me,Me=oe.mmul(Ce);var Ie=be.mmul(Me);Ie.div(Z.norm(Ie)),ze=se.mmul(Ie)}qe=Me;var Re=we.mmul(qe),De=qe.transpose().mmul(qe)[0][0],Ve=Re.div(De),Pe=Z.norm(Ve);Ve.div(Pe),qe.mul(Pe),Ce.mul(Pe),Re=ze.transpose().mmul(qe),De=qe.transpose().mmul(qe)[0][0];var Ae=Re.div(De)[0][0];oe.sub(qe.mmul(Ve.transpose())),se.sub(qe.clone().mul(Ae).mmul(Ie.transpose())),ge.setColumn(ke,qe),he.setColumn(ke,Ve),xe.setColumn(ke,ze),fe.setColumn(ke,Ie),je.setColumn(ke,Ce),ye[ke][ke]=Ae,ke++}ke--,ge=ge.subMatrix(0,ge.rows-1,0,ke),he=he.subMatrix(0,he.rows-1,0,ke),xe=xe.subMatrix(0,xe.rows-1,0,ke),fe=fe.subMatrix(0,fe.rows-1,0,ke),je=je.subMatrix(0,je.rows-1,0,ke),ye=ye.subMatrix(0,ke,0,ke),this.ssqYcal=me,this.E=oe,this.F=se,this.T=ge,this.P=he,this.U=xe,this.Q=fe,this.W=je,this.B=ye,this.PBQ=he.mmul(ye).mmul(fe.transpose()),this.R2X=qe.transpose().mmul(qe).mmul(Ve.transpose().mmul(Ve)).div(ce)[0][0]}predict(te){var ie=G.checkMatrix(te);ie=ie.subRowVector(this.meanX).divRowVector(this.stdDevX);var ne=ie.mmul(this.PBQ);return ne=ne.mulRowVector(this.stdDevY).addRowVector(this.meanY),ne}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(te){if('PLS'!==te.name)throw new RangeError('Invalid model: '+te.name);return new ee(!0,te)}}I.exports=ee},function(I,R,D){'use strict';function O(Z,$){return this[Z][$]=this[Z][$]*this[Z][$],this}const E=D(14),G=D(3);I.exports={norm:function($){return Math.sqrt($.clone().apply(O).sum())},pow2array:O,featureNormalize:function($){var ee=G.matrix.mean($),te=G.matrix.standardDeviation($,ee,!0),ie=E.checkMatrix($).subRowVector(ee);return{result:ie.divRowVector(te),means:ee,std:te}}}},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,te.rows,te.columns;var ne=te.clone().mul(te).sum(),oe=te.transpose().mmul(ie);oe.div(G.norm(oe));for(var se=Array(ee),ae=Array(ee),le=Array(ee),de=0;de=le){for(let ge=0;geG)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=[];0<$.length;){var 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,D){I.exports=D(149)},function(I,R,D){var O,E,G;(function(){var Z,$,ee,te,ie,ne,oe,se,ae,le,de,ue,ce,me,pe;ee=Math.floor,le=Math.min,$=function(ge,he){return gehe?1:0},ae=function(ge,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=ge.length);xeye(he,ge[je])?fe=je:xe=je+1;return[].splice.apply(ge,[xe,xe-xe].concat(he)),he},ne=function(ge,he,xe){return null==xe&&(xe=$),ge.push(he),me(ge,0,ge.length-1,xe)},ie=function(ge,he){var xe,fe;return null==he&&(he=$),xe=ge.pop(),ge.length?(fe=ge[0],ge[0]=xe,pe(ge,0,he)):fe=xe,fe},se=function(ge,he,xe){var fe;return null==xe&&(xe=$),fe=ge[0],ge[0]=he,pe(ge,0,xe),fe},oe=function(ge,he,xe){var fe;return null==xe&&(xe=$),ge.length&&0>xe(ge[0],he)&&(fe=[ge[0],he],he=fe[0],ge[0]=fe[1],pe(ge,0,xe)),he},te=function(ge,he){var xe,fe,ye,je,ke,we;for(null==he&&(he=$),je=function(){we=[];for(var be=0,ve=ee(ge.length/2);0<=ve?beve;0<=ve?be++:be--)we.push(be);return we}.apply(this).reverse(),ke=[],(fe=0,ye=je.length);fexe(fe,je)&&(ae(ke,fe,0,null,xe),ke.pop(),je=ke[ke.length-1]);return ke}for(te(ge,xe),ze=[],(ye=be=0,Me=le(he,ge.length));0<=Me?beMe;ye=0<=Me?++be:--be)ze.push(ie(ge,xe));return ze},me=function(ge,he,xe,fe){var ye,je,ke;for(null==fe&&(fe=$),ye=ge[xe];xe>he;){if(ke=xe-1>>1,je=ge[ke],0>fe(ye,je)){ge[xe]=je,xe=ke;continue}break}return ge[xe]=ye},pe=function(ge,he,xe){var fe,ye,je,ke,we;for(null==xe&&(xe=$),ye=ge.length,we=he,je=ge[he],fe=2*he+1;fexe(ge[fe],ge[ke]))&&(fe=ke),ge[he]=ge[fe],he=fe,fe=2*he+1;return ge[he]=je,me(ge,we,he,xe)},Z=function(){function ge(he){this.cmp=null==he?$:he,this.nodes=[]}return ge.push=ne,ge.pop=ie,ge.replace=se,ge.pushpop=oe,ge.heapify=te,ge.updateItem=ce,ge.nlargest=de,ge.nsmallest=ue,ge.prototype.push=function(he){return ne(this.nodes,he,this.cmp)},ge.prototype.pop=function(){return ie(this.nodes,this.cmp)},ge.prototype.peek=function(){return this.nodes[0]},ge.prototype.contains=function(he){return-1!==this.nodes.indexOf(he)},ge.prototype.replace=function(he){return se(this.nodes,he,this.cmp)},ge.prototype.pushpop=function(he){return oe(this.nodes,he,this.cmp)},ge.prototype.heapify=function(){return te(this.nodes,this.cmp)},ge.prototype.updateItem=function(he){return ce(this.nodes,he,this.cmp)},ge.prototype.clear=function(){return this.nodes=[]},ge.prototype.empty=function(){return 0===this.nodes.length},ge.prototype.size=function(){return this.nodes.length},ge.prototype.clone=function(){var he=new ge;return he.nodes=this.nodes.slice(0),he},ge.prototype.toArray=function(){return this.nodes.slice(0)},ge.prototype.insert=ge.prototype.push,ge.prototype.top=ge.prototype.peek,ge.prototype.front=ge.prototype.peek,ge.prototype.has=ge.prototype.contains,ge.prototype.copy=ge.prototype.clone,ge}(),function(ge,he){return E=[],O=he,G='function'==typeof O?O.apply(R,E):O,!(G!==void 0&&(I.exports=G))}(this,function(){return Z})}).call(this)},function(I,R,D){(function(O,E){function G(qe,Ce){var Ie={seen:[],stylize:$};return 3<=arguments.length&&(Ie.depth=arguments[2]),4<=arguments.length&&(Ie.colors=arguments[3]),de(Ce)?Ie.showHidden=Ce:Ce&&R._extend(Ie,Ce),pe(Ie.showHidden)&&(Ie.showHidden=!1),pe(Ie.depth)&&(Ie.depth=2),pe(Ie.colors)&&(Ie.colors=!1),pe(Ie.customInspect)&&(Ie.customInspect=!0),Ie.colors&&(Ie.stylize=Z),te(Ie,qe,Ie.depth)}function Z(qe,Ce){var Ie=G.styles[Ce];return Ie?'\u001b['+G.colors[Ie][0]+'m'+qe+'\u001b['+G.colors[Ie][1]+'m':qe}function $(qe,Ce){return qe}function ee(qe){var Ce={};return qe.forEach(function(Ie,Re){Ce[Ie]=!0}),Ce}function te(qe,Ce,Ie){if(qe.customInspect&&Ce&&ye(Ce.inspect)&&Ce.inspect!==R.inspect&&!(Ce.constructor&&Ce.constructor.prototype===Ce)){var Re=Ce.inspect(Ie,qe);return me(Re)||(Re=te(qe,Re,Ie)),Re}var De=ie(qe,Ce);if(De)return De;var Ve=Object.keys(Ce),Pe=ee(Ve);if(qe.showHidden&&(Ve=Object.getOwnPropertyNames(Ce)),fe(Ce)&&(0<=Ve.indexOf('message')||0<=Ve.indexOf('description')))return ne(Ce);if(0===Ve.length){if(ye(Ce)){var Ae=Ce.name?': '+Ce.name:'';return qe.stylize('[Function'+Ae+']','special')}if(ge(Ce))return qe.stylize(RegExp.prototype.toString.call(Ce),'regexp');if(xe(Ce))return qe.stylize(Date.prototype.toString.call(Ce),'date');if(fe(Ce))return ne(Ce)}var Ne='',_e=!1,Oe=['{','}'];if(le(Ce)&&(_e=!0,Oe=['[',']']),ye(Ce)){var Le=Ce.name?': '+Ce.name:'';Ne=' [Function'+Le+']'}if(ge(Ce)&&(Ne=' '+RegExp.prototype.toString.call(Ce)),xe(Ce)&&(Ne=' '+Date.prototype.toUTCString.call(Ce)),fe(Ce)&&(Ne=' '+ne(Ce)),0===Ve.length&&(!_e||0==Ce.length))return Oe[0]+Ne+Oe[1];if(0>Ie)return ge(Ce)?qe.stylize(RegExp.prototype.toString.call(Ce),'regexp'):qe.stylize('[Object]','special');qe.seen.push(Ce);var Fe;return Fe=_e?oe(qe,Ce,Ie,Pe,Ve):Ve.map(function(Te){return se(qe,Ce,Ie,Pe,Te,_e)}),qe.seen.pop(),ae(Fe,Ne,Oe)}function ie(qe,Ce){if(pe(Ce))return qe.stylize('undefined','undefined');if(me(Ce)){var Ie='\''+JSON.stringify(Ce).replace(/^"|"$/g,'').replace(/'/g,'\\\'').replace(/\\"/g,'"')+'\'';return qe.stylize(Ie,'string')}return ce(Ce)?qe.stylize(''+Ce,'number'):de(Ce)?qe.stylize(''+Ce,'boolean'):ue(Ce)?qe.stylize('null','null'):void 0}function ne(qe){return'['+Error.prototype.toString.call(qe)+']'}function oe(qe,Ce,Ie,Re,De){for(var Ve=[],Pe=0,Ae=Ce.length;Peqe.seen.indexOf(Ne.value)?(Ae=ue(Ie)?te(qe,Ne.value,null):te(qe,Ne.value,Ie-1),-1qe?'0'+qe.toString(10):qe.toString(10)}function we(){var qe=new Date,Ce=[ke(qe.getHours()),ke(qe.getMinutes()),ke(qe.getSeconds())].join(':');return[qe.getDate(),ze[qe.getMonth()],Ce].join(' ')}function be(qe,Ce){return Object.prototype.hasOwnProperty.call(qe,Ce)}var ve=/%[sdj%]/g;R.format=function(qe){if(!me(qe)){for(var Ce=[],Ie=0;Ie=De)return Ae;switch(Ae){case'%s':return Re[Ie++]+'';case'%d':return+Re[Ie++];case'%j':try{return JSON.stringify(Re[Ie++])}catch(Ne){return'[Circular]'}default:return Ae;}}),Pe=Re[Ie];Ieue.d&&(ue.d=he-xe,ue.p=fe)}return ue}function te(ae,le,de){for(var ue=0,ce=0,me=0;mege&&(ge=pe,he=je)}if(ge=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 oe,Se=new oe,Me=[Array(ye[he].index.length),[]],ze=0;zege&&(ge=xe,fe=qe)}for(Me[1]=[fe],Me[0].splice(fe,1),xe=ee(Me,le,de.dist);0E?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]),ZE?(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;Z>','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=` +(function %name%(value) { + if (typeof value === 'number') return this.%name%S(value); + return this.%name%M(value); +}) +`,inplaceOperatorScalar=` +(function %name%S(value) { + this.forEachNonZero((i, j, v) => v %op% value); + return this; +}) +`,inplaceOperatorMatrix=` +(function %name%M(matrix) { + matrix.forEachNonZero((i, j, v) => { + this.set(i, j, this.get(i, j) %op% v); + return v; + }); + return this; +}) +`,staticOperator=` +(function %name%(matrix, value) { + var newMatrix = new SparseMatrix(matrix); + return newMatrix.%name%(value); +}) +`,inplaceMethod=` +(function %name%() { + this.forEachNonZero((i, j, v) => %method%(v)); + return this; +}) +`,staticMethod=` +(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';/** +* k-d Tree JavaScript - V 1.01 +* +* https://github.com/ubilabs/kd-tree-javascript +* +* @author Mircea Pricop , 2012 +* @author Martin Kleppe , 2012 +* @author Ubilabs http://ubilabs.net, 2012 +* @license MIT License +*/function 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];Pe 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 = 4\n ** module chunks = 0\n **/","'use strict';\n\nvar arrayStat = require('./array');\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nexports.max = function max(matrix) {\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return max;\n};\n\nexports.min = function min(matrix) {\n var min = Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n }\n }\n return min;\n};\n\nexports.minMax = function minMax(matrix) {\n var min = Infinity;\n var max = -Infinity;\n for (var i = 0; i < matrix.length; i++) {\n for (var j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] < min) min = matrix[i][j];\n if (matrix[i][j] > max) max = matrix[i][j];\n }\n }\n return {\n min:min,\n max:max\n };\n};\n\nexports.entropy = function entropy(matrix, eps) {\n if (typeof (eps) === 'undefined') {\n eps = 0;\n }\n var sum = 0,\n l1 = matrix.length,\n l2 = matrix[0].length;\n for (var i = 0; i < l1; i++) {\n for (var j = 0; j < l2; j++) {\n sum += matrix[i][j] * Math.log(matrix[i][j] + eps);\n }\n }\n return -sum;\n};\n\nexports.mean = function mean(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theMean, N, i, j;\n\n if (dimension === -1) {\n theMean = [0];\n N = rows * cols;\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theMean[0] += matrix[i][j];\n }\n }\n theMean[0] /= N;\n } else if (dimension === 0) {\n theMean = new Array(cols);\n N = rows;\n for (j = 0; j < cols; j++) {\n theMean[j] = 0;\n for (i = 0; i < rows; i++) {\n theMean[j] += matrix[i][j];\n }\n theMean[j] /= N;\n }\n } else if (dimension === 1) {\n theMean = new Array(rows);\n N = cols;\n for (j = 0; j < rows; j++) {\n theMean[j] = 0;\n for (i = 0; i < cols; i++) {\n theMean[j] += matrix[j][i];\n }\n theMean[j] /= N;\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theMean;\n};\n\nexports.sum = function sum(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theSum, i, j;\n\n if (dimension === -1) {\n theSum = [0];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theSum[0] += matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theSum = new Array(cols);\n for (j = 0; j < cols; j++) {\n theSum[j] = 0;\n for (i = 0; i < rows; i++) {\n theSum[j] += matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theSum = new Array(rows);\n for (j = 0; j < rows; j++) {\n theSum[j] = 0;\n for (i = 0; i < cols; i++) {\n theSum[j] += matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theSum;\n};\n\nexports.product = function product(matrix, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length,\n cols = matrix[0].length,\n theProduct, i, j;\n\n if (dimension === -1) {\n theProduct = [1];\n for (i = 0; i < rows; i++) {\n for (j = 0; j < cols; j++) {\n theProduct[0] *= matrix[i][j];\n }\n }\n } else if (dimension === 0) {\n theProduct = new Array(cols);\n for (j = 0; j < cols; j++) {\n theProduct[j] = 1;\n for (i = 0; i < rows; i++) {\n theProduct[j] *= matrix[i][j];\n }\n }\n } else if (dimension === 1) {\n theProduct = new Array(rows);\n for (j = 0; j < rows; j++) {\n theProduct[j] = 1;\n for (i = 0; i < cols; i++) {\n theProduct[j] *= matrix[j][i];\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n return theProduct;\n};\n\nexports.standardDeviation = function standardDeviation(matrix, means, unbiased) {\n var vari = exports.variance(matrix, means, unbiased), l = vari.length;\n for (var i = 0; i < l; i++) {\n vari[i] = Math.sqrt(vari[i]);\n }\n return vari;\n};\n\nexports.variance = function variance(matrix, means, unbiased) {\n if (typeof (unbiased) === 'undefined') {\n unbiased = true;\n }\n means = means || exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum1 = 0, sum2 = 0, x = 0;\n for (var i = 0; i < rows; i++) {\n x = matrix[i][j] - means[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / (rows - 1);\n } else {\n vari[j] = (sum2 - ((sum1 * sum1) / rows)) / rows;\n }\n }\n return vari;\n};\n\nexports.median = function median(matrix) {\n var rows = matrix.length, cols = matrix[0].length;\n var medians = new Array(cols);\n\n for (var i = 0; i < cols; i++) {\n var data = new Array(rows);\n for (var j = 0; j < rows; j++) {\n data[j] = matrix[j][i];\n }\n data.sort(compareNumbers);\n var N = data.length;\n if (N % 2 === 0) {\n medians[i] = (data[N / 2] + data[(N / 2) - 1]) * 0.5;\n } else {\n medians[i] = data[Math.floor(N / 2)];\n }\n }\n return medians;\n};\n\nexports.mode = function mode(matrix) {\n var rows = matrix.length,\n cols = matrix[0].length,\n modes = new Array(cols),\n i, j;\n for (i = 0; i < cols; i++) {\n var itemCount = new Array(rows);\n for (var k = 0; k < rows; k++) {\n itemCount[k] = 0;\n }\n var itemArray = new Array(rows);\n var count = 0;\n\n for (j = 0; j < rows; j++) {\n var index = itemArray.indexOf(matrix[j][i]);\n if (index >= 0) {\n itemCount[index]++;\n } else {\n itemArray[count] = matrix[j][i];\n itemCount[count] = 1;\n count++;\n }\n }\n\n var maxValue = 0, maxIndex = 0;\n for (j = 0; j < count; j++) {\n if (itemCount[j] > maxValue) {\n maxValue = itemCount[j];\n maxIndex = j;\n }\n }\n\n modes[i] = itemArray[maxIndex];\n }\n return modes;\n};\n\nexports.skewness = function skewness(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, l = means.length;\n var skew = new Array(l);\n\n for (var j = 0; j < l; j++) {\n var s2 = 0, s3 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s3 += dev * dev * dev;\n }\n\n var m2 = s2 / n;\n var m3 = s3 / n;\n var g = m3 / Math.pow(m2, 3 / 2);\n\n if (unbiased) {\n var a = Math.sqrt(n * (n - 1));\n var b = n - 2;\n skew[j] = (a / b) * g;\n } else {\n skew[j] = g;\n }\n }\n return skew;\n};\n\nexports.kurtosis = function kurtosis(matrix, unbiased) {\n if (typeof (unbiased) === 'undefined') unbiased = true;\n var means = exports.mean(matrix);\n var n = matrix.length, m = matrix[0].length;\n var kurt = new Array(m);\n\n for (var j = 0; j < m; j++) {\n var s2 = 0, s4 = 0;\n for (var i = 0; i < n; i++) {\n var dev = matrix[i][j] - means[j];\n s2 += dev * dev;\n s4 += dev * dev * dev * dev;\n }\n var m2 = s2 / n;\n var m4 = s4 / n;\n\n if (unbiased) {\n var v = s2 / (n - 1);\n var a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));\n var b = s4 / (v * v);\n var c = ((n - 1) * (n - 1)) / ((n - 2) * (n - 3));\n kurt[j] = a * b - 3 * c;\n } else {\n kurt[j] = m4 / (m2 * m2) - 3;\n }\n }\n return kurt;\n};\n\nexports.standardError = function standardError(matrix) {\n var samples = matrix.length;\n var standardDeviations = exports.standardDeviation(matrix);\n var l = standardDeviations.length;\n var standardErrors = new Array(l);\n var sqrtN = Math.sqrt(samples);\n\n for (var i = 0; i < l; i++) {\n standardErrors[i] = standardDeviations[i] / sqrtN;\n }\n return standardErrors;\n};\n\nexports.covariance = function covariance(matrix, dimension) {\n return exports.scatter(matrix, undefined, dimension);\n};\n\nexports.scatter = function scatter(matrix, divisor, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n if (typeof (divisor) === 'undefined') {\n if (dimension === 0) {\n divisor = matrix.length - 1;\n } else if (dimension === 1) {\n divisor = matrix[0].length - 1;\n }\n }\n var means = exports.mean(matrix, dimension);\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, s, k;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n s /= divisor;\n cov[i][j] = s;\n cov[j][i] = s;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\nexports.correlation = function correlation(matrix) {\n var means = exports.mean(matrix),\n standardDeviations = exports.standardDeviation(matrix, true, means),\n scores = exports.zScores(matrix, means, standardDeviations),\n rows = matrix.length,\n cols = matrix[0].length,\n i, j;\n\n var cor = new Array(cols);\n for (i = 0; i < cols; i++) {\n cor[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n var c = 0;\n for (var k = 0, l = scores.length; k < l; k++) {\n c += scores[k][j] * scores[k][i];\n }\n c /= rows - 1;\n cor[i][j] = c;\n cor[j][i] = c;\n }\n }\n return cor;\n};\n\nexports.zScores = function zScores(matrix, means, standardDeviations) {\n means = means || exports.mean(matrix);\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means);\n return exports.standardize(exports.center(matrix, means, false), standardDeviations, true);\n};\n\nexports.center = function center(matrix, means, inPlace) {\n means = means || exports.mean(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var row = result[i];\n for (j = 0, jj = row.length; j < jj; j++) {\n row[j] = matrix[i][j] - means[j];\n }\n }\n return result;\n};\n\nexports.standardize = function standardize(matrix, standardDeviations, inPlace) {\n if (typeof (standardDeviations) === 'undefined') standardDeviations = exports.standardDeviation(matrix);\n var result = matrix,\n l = matrix.length,\n i, j, jj;\n\n if (!inPlace) {\n result = new Array(l);\n for (i = 0; i < l; i++) {\n result[i] = new Array(matrix[i].length);\n }\n }\n\n for (i = 0; i < l; i++) {\n var resultRow = result[i];\n var sourceRow = matrix[i];\n for (j = 0, jj = resultRow.length; j < jj; j++) {\n if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {\n resultRow[j] = sourceRow[j] / standardDeviations[j];\n }\n }\n }\n return result;\n};\n\nexports.weightedVariance = function weightedVariance(matrix, weights) {\n var means = exports.mean(matrix);\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length;\n var vari = new Array(cols);\n\n for (var j = 0; j < cols; j++) {\n var sum = 0;\n var a = 0, b = 0;\n\n for (var i = 0; i < rows; i++) {\n var z = matrix[i][j] - means[j];\n var w = weights[i];\n\n sum += w * (z * z);\n b += w;\n a += w * w;\n }\n\n vari[j] = sum * (b / (b * b - a));\n }\n\n return vari;\n};\n\nexports.weightedMean = function weightedMean(matrix, weights, dimension) {\n if (typeof (dimension) === 'undefined') {\n dimension = 0;\n }\n var rows = matrix.length;\n if (rows === 0) return [];\n var cols = matrix[0].length,\n means, i, ii, j, w, row;\n\n if (dimension === 0) {\n means = new Array(cols);\n for (i = 0; i < cols; i++) {\n means[i] = 0;\n }\n for (i = 0; i < rows; i++) {\n row = matrix[i];\n w = weights[i];\n for (j = 0; j < cols; j++) {\n means[j] += row[j] * w;\n }\n }\n } else if (dimension === 1) {\n means = new Array(rows);\n for (i = 0; i < rows; i++) {\n means[i] = 0;\n }\n for (j = 0; j < rows; j++) {\n row = matrix[j];\n w = weights[j];\n for (i = 0; i < cols; i++) {\n means[j] += row[i] * w;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n var weightSum = arrayStat.sum(weights);\n if (weightSum !== 0) {\n for (i = 0, ii = means.length; i < ii; i++) {\n means[i] /= weightSum;\n }\n }\n return means;\n};\n\nexports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n var s1 = 0, s2 = 0;\n for (var i = 0, ii = weights.length; i < ii; i++) {\n s1 += weights[i];\n s2 += weights[i] * weights[i];\n }\n var factor = s1 / (s1 * s1 - s2);\n return exports.weightedScatter(matrix, weights, means, factor, dimension);\n};\n\nexports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) {\n dimension = dimension || 0;\n means = means || exports.weightedMean(matrix, weights, dimension);\n if (typeof (factor) === 'undefined') {\n factor = 1;\n }\n var rows = matrix.length;\n if (rows === 0) {\n return [[]];\n }\n var cols = matrix[0].length,\n cov, i, j, k, s;\n\n if (dimension === 0) {\n cov = new Array(cols);\n for (i = 0; i < cols; i++) {\n cov[i] = new Array(cols);\n }\n for (i = 0; i < cols; i++) {\n for (j = i; j < cols; j++) {\n s = 0;\n for (k = 0; k < rows; k++) {\n s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else if (dimension === 1) {\n cov = new Array(rows);\n for (i = 0; i < rows; i++) {\n cov[i] = new Array(rows);\n }\n for (i = 0; i < rows; i++) {\n for (j = i; j < rows; j++) {\n s = 0;\n for (k = 0; k < cols; k++) {\n s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);\n }\n cov[i][j] = s * factor;\n cov[j][i] = s * factor;\n }\n }\n } else {\n throw new Error('Invalid dimension');\n }\n\n return cov;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-stat/matrix.js\n ** module id = 5\n ** module chunks = 0\n **/","'use strict';\n\n/**\n *\n * Function that returns a Number array of equally spaced numberOfPoints\n * containing a representation of intensities of the spectra arguments x\n * and y.\n *\n * The options parameter contains an object in the following form:\n * from: starting point\n * to: last point\n * numberOfPoints: number of points between from and to\n * variant: \"slot\" or \"smooth\" - smooth is the default option\n *\n * The slot variant consist that each point in the new array is calculated\n * averaging the existing points between the slot that belongs to the current\n * value. The smooth variant is the same but takes the integral of the range\n * of the slot and divide by the step size between two points in the new array.\n *\n * @param x - sorted increasing x values\n * @param y\n * @param options\n * @returns {Array} new array with the equally spaced data.\n *\n */\nfunction getEquallySpacedData(x, y, options) {\n 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 = 6\n ** module chunks = 0\n **/","'use strict';\n\nexports.SNV = SNV;\nvar Stat = require('ml-stat').array;\n\n/**\n * Function that applies the standard normal variate (SNV) to an array of values.\n *\n * @param data - Array of values.\n * @returns {Array} - applied the SNV.\n */\nfunction SNV(data) {\n var mean = Stat.mean(data);\n var std = Stat.standardDeviation(data);\n var result = data.slice();\n for (var i = 0; i < data.length; i++) {\n result[i] = (result[i] - mean) / std;\n }\n return result;\n}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-array-utils/src/snv.js\n ** module id = 7\n ** module chunks = 0\n **/","/**\n * Performs a binary search of value in array\n * @param {number[]} array - Array in which value will be searched. It must be sorted.\n * @param {number} value - Value to search in array\n * @return {number} If value is found, returns its index in array. Otherwise, returns a negative number indicating where the value should be inserted: -(index + 1)\n */\nfunction binarySearch(array, value, options) {\n options = options || {};\n var low = options.from || 0;\n var high = options.to || array.length - 1;\n\n while (low <= high) {\n var mid = (low + high) >>> 1;\n var midValue = array[mid];\n if (midValue < value) {\n low = mid + 1;\n } else if (midValue > value) {\n high = mid - 1;\n } else {\n return mid;\n }\n }\n\n return -(low + 1);\n}\n\nmodule.exports = binarySearch;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-binary-search/src/binarySearch.js\n ** module id = 8\n ** module chunks = 0\n **/","'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 = 9\n ** module chunks = 0\n **/","// auxiliary file to create the 256 look at table elements\n\nvar ans = new Array(256);\nfor (var i = 0; i < 256; i++) {\n var num = i;\n var c = 0;\n while (num) {\n num = num & (num - 1);\n c++;\n }\n ans[i] = c;\n}\n\nmodule.exports = ans;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-bit-array/src/creator.js\n ** module id = 10\n ** module chunks = 0\n **/","'use strict';\n\nconst newArray = require('new-array');\n\nconst primeFinder = require('./primeFinder');\nconst nextPrime = primeFinder.nextPrime;\nconst largestPrime = primeFinder.largestPrime;\n\nconst FREE = 0;\nconst FULL = 1;\nconst REMOVED = 2;\n\nconst defaultInitialCapacity = 150;\nconst defaultMinLoadFactor = 1 / 6;\nconst defaultMaxLoadFactor = 2 / 3;\n\nclass HashTable {\n constructor(options = {}) {\n if (options instanceof HashTable) {\n this.table = options.table.slice();\n this.values = options.values.slice();\n this.state = options.state.slice();\n this.minLoadFactor = options.minLoadFactor;\n this.maxLoadFactor = options.maxLoadFactor;\n this.distinct = options.distinct;\n this.freeEntries = options.freeEntries;\n this.lowWaterMark = options.lowWaterMark;\n this.highWaterMark = options.maxLoadFactor;\n return;\n }\n\n const initialCapacity = options.initialCapacity === undefined ? defaultInitialCapacity : options.initialCapacity;\n if (initialCapacity < 0) {\n throw new RangeError(`initial capacity must not be less than zero: ${initialCapacity}`);\n }\n\n const minLoadFactor = options.minLoadFactor === undefined ? defaultMinLoadFactor : options.minLoadFactor;\n const maxLoadFactor = options.maxLoadFactor === undefined ? defaultMaxLoadFactor : options.maxLoadFactor;\n if (minLoadFactor < 0 || minLoadFactor >= 1) {\n throw new RangeError(`invalid minLoadFactor: ${minLoadFactor}`);\n }\n if (maxLoadFactor <= 0 || maxLoadFactor >= 1) {\n throw new RangeError(`invalid maxLoadFactor: ${maxLoadFactor}`);\n }\n if (minLoadFactor >= maxLoadFactor) {\n throw new RangeError(`minLoadFactor (${minLoadFactor}) must be smaller than maxLoadFactor (${maxLoadFactor})`);\n }\n\n let capacity = initialCapacity;\n // User wants to put at least capacity elements. We need to choose the size based on the maxLoadFactor to\n // avoid the need to rehash before this capacity is reached.\n // actualCapacity * maxLoadFactor >= capacity\n capacity = (capacity / maxLoadFactor) | 0;\n capacity = nextPrime(capacity);\n if (capacity === 0) capacity = 1;\n\n this.table = newArray(capacity, 0);\n this.values = newArray(capacity, 0);\n this.state = newArray(capacity, 0);\n\n this.minLoadFactor = minLoadFactor;\n if (capacity === largestPrime) {\n this.maxLoadFactor = 1;\n } else {\n this.maxLoadFactor = maxLoadFactor;\n }\n\n this.distinct = 0;\n this.freeEntries = capacity;\n\n this.lowWaterMark = 0;\n this.highWaterMark = chooseHighWaterMark(capacity, this.maxLoadFactor);\n }\n\n clone() {\n return new HashTable(this);\n }\n\n get size() {\n return this.distinct;\n }\n\n get(key) {\n const i = this.indexOfKey(key);\n if (i < 0) return 0;\n return this.values[i];\n }\n\n set(key, value) {\n let i = this.indexOfInsertion(key);\n if (i < 0) {\n i = -i - 1;\n this.values[i] = value;\n return false;\n }\n\n if (this.distinct > this.highWaterMark) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n return this.set(key, value);\n }\n\n this.table[i] = key;\n this.values[i] = value;\n if (this.state[i] === FREE) this.freeEntries--;\n this.state[i] = FULL;\n this.distinct++;\n\n if (this.freeEntries < 1) {\n const newCapacity = chooseGrowCapacity(this.distinct + 1, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n\n return true;\n }\n \n remove(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = REMOVED;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n delete(key, noRehash) {\n const i = this.indexOfKey(key);\n if (i < 0) return false;\n\n this.state[i] = FREE;\n this.distinct--;\n\n if (!noRehash) this.maybeShrinkCapacity();\n\n return true;\n }\n\n maybeShrinkCapacity() {\n if (this.distinct < this.lowWaterMark) {\n const newCapacity = chooseShrinkCapacity(this.distinct, this.minLoadFactor, this.maxLoadFactor);\n this.rehash(newCapacity);\n }\n }\n\n containsKey(key) {\n return this.indexOfKey(key) >= 0;\n }\n\n indexOfKey(key) {\n const table = this.table;\n const state = this.state;\n const length = this.table.length;\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === FREE) return -1;\n return i;\n }\n\n containsValue(value) {\n return this.indexOfValue(value) >= 0;\n }\n\n indexOfValue(value) {\n const values = this.values;\n const state = this.state;\n\n for (var i = 0; i < state.length; i++) {\n if (state[i] === FULL && values[i] === value) {\n return i;\n }\n }\n\n return -1;\n }\n\n indexOfInsertion(key) {\n const table = this.table;\n const state = this.state;\n const length = table.length;\n\n\n const hash = key & 0x7fffffff;\n let i = hash % length;\n let decrement = hash % (length - 2);\n if (decrement === 0) decrement = 1;\n\n while (state[i] === FULL && table[i] !== key) {\n i -= decrement;\n if (i < 0) i += length;\n }\n\n if (state[i] === REMOVED) {\n const j = i;\n while (state[i] !== FREE && (state[i] === REMOVED || table[i] !== key)) {\n i -= decrement;\n if (i < 0) i += length;\n }\n if (state[i] === FREE) i = j;\n }\n\n if (state[i] === FULL) {\n return -i - 1;\n }\n\n return i;\n }\n\n ensureCapacity(minCapacity) {\n if (this.table.length < minCapacity) {\n const newCapacity = nextPrime(minCapacity);\n this.rehash(newCapacity);\n }\n }\n\n rehash(newCapacity) {\n const oldCapacity = this.table.length;\n\n if (newCapacity <= this.distinct) throw new Error('Unexpected');\n\n const oldTable = this.table;\n const oldValues = this.values;\n const oldState = this.state;\n\n const newTable = newArray(newCapacity, 0);\n const newValues = newArray(newCapacity, 0);\n const newState = newArray(newCapacity, 0);\n\n this.lowWaterMark = chooseLowWaterMark(newCapacity, this.minLoadFactor);\n this.highWaterMark = chooseHighWaterMark(newCapacity, this.maxLoadFactor);\n\n this.table = newTable;\n this.values = newValues;\n this.state = newState;\n this.freeEntries = newCapacity - this.distinct;\n\n for (var i = 0; i < oldCapacity; i++) {\n if (oldState[i] === FULL) {\n var element = oldTable[i];\n var index = this.indexOfInsertion(element);\n newTable[index] = element;\n newValues[index] = oldValues[i];\n newState[index] = FULL;\n }\n }\n }\n\n forEachKey(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i])) return false;\n }\n }\n return true;\n }\n\n forEachValue(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.values[i])) return false;\n }\n }\n return true;\n }\n\n forEachPair(callback) {\n for (var i = 0; i < this.state.length; i++) {\n if (this.state[i] === FULL) {\n if (!callback(this.table[i], this.values[i])) return false;\n }\n }\n return true;\n }\n}\n\nmodule.exports = HashTable;\n\nfunction chooseLowWaterMark(capacity, minLoad) {\n return (capacity * minLoad) | 0;\n}\n\nfunction chooseHighWaterMark(capacity, maxLoad) {\n return Math.min(capacity - 2, (capacity * maxLoad) | 0);\n}\n\nfunction chooseGrowCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (3 * minLoad + maxLoad)) | 0));\n}\n\nfunction chooseShrinkCapacity(size, minLoad, maxLoad) {\n return nextPrime(Math.max(size + 1, (4 * size / (minLoad + 3 * maxLoad)) | 0));\n}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-hash-table/src/HashTable.js\n ** module id = 11\n ** module chunks = 0\n **/","module.exports = newArray\n\nfunction newArray (n, value) {\n n = n || 0\n var array = new Array(n)\n for (var i = 0; i < n; i++) {\n array[i] = value\n }\n return array\n}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/new-array/index.js\n ** module id = 12\n ** module chunks = 0\n **/","const binarySearch = require('ml-binary-search');\n\nconst largestPrime = 0x7fffffff;\n\nconst primeNumbers = [\n //chunk #0\n largestPrime, // 2^31-1\n\n //chunk #1\n 5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759,\n 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939,\n 210719881, 421439783, 842879579, 1685759167,\n\n //chunk #2\n 433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107,\n 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699,\n 1854585413,\n\n //chunk #3\n 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341,\n 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963,\n 2004663929,\n\n //chunk #4\n 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963,\n 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463,\n\n //chunk #5\n 31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953,\n 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013,\n 587742049, 1175484103,\n\n //chunk #6\n 599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729,\n 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683,\n\n //chunk #7\n 311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867,\n 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673,\n 1344393353,\n\n //chunk #8\n 3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #9\n 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337,\n 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741,\n 759155483, 1518310967,\n\n //chunk #10\n 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611,\n 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929,\n 1600153859,\n\n //chunk #11\n 13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683,\n 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407,\n 276172823, 552345671, 1104691373,\n\n //chunk #12\n 19, 41, 83, 167, 337, 677,\n 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #13\n 53, 107, 223, 449, 907, 1823, 3659, 7321, 14653, 29311, 58631, 117269,\n 234539, 469099, 938207, 1876417, 3752839, 7505681, 15011389, 30022781,\n 60045577, 120091177, 240182359, 480364727, 960729461, 1921458943\n];\n\nprimeNumbers.sort((a, b) => a - b);\n\nfunction nextPrime(value) {\n let index = binarySearch(primeNumbers, value);\n if (index < 0) {\n index = -index - 1;\n }\n return primeNumbers[index];\n}\n\nexports.nextPrime = nextPrime;\nexports.largestPrime = largestPrime;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-hash-table/src/primeFinder.js\n ** module id = 13\n ** module chunks = 0\n **/","'use strict';\n\nmodule.exports = require('./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 = 14\n ** module chunks = 0\n **/","'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 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 (var 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 var 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 (var 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 }\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 * @returns {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 * @returns {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 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 * @returns {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 * @returns {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 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 * @returns {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\nmodule.exports = Matrix;\nMatrix.abstractMatrix = abstractMatrix;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-matrix/src/matrix.js\n ** module id = 15\n ** module chunks = 0\n **/","'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 = 16\n ** module chunks = 0\n **/","'use strict';\n\nmodule.exports = abstractMatrix;\n\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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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] - Random number generator (default: Math.random)\n * @returns {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 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] - Number of columns (Default: rows)\n * @returns {Matrix} - The new identity matrix\n */\n static eye(rows, columns) {\n if (columns === undefined) columns = rows;\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, 1);\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 * @returns {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 matrix1\n * @param matrix2\n * @returns {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 matrix1\n * @param matrix2\n * @returns {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 * @returns {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 * @property {number} - 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 * @returns {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 * @returns {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 * @returns {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 * @returns {boolean} true if the matrix has one row\n */\n isRowVector() {\n return this.rows === 1;\n }\n\n /**\n * @returns {boolean} true if the matrix has one column\n */\n isColumnVector() {\n return this.columns === 1;\n }\n\n /**\n * @returns {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 * @returns {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 * @returns {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 * @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 * @returns {Matrix} this\n */\n set(rowIndex, columnIndex, value) {\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 * @param {number} rowIndex - Index of the row\n * @param {number} columnIndex - Index of the column\n * @returns {number}\n */\n get(rowIndex, columnIndex) {\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 * @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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 }\n\n /**\n * Returns the maximum value of the matrix\n * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 of all elements of the matrix\n * @returns {number}\n */\n sum() {\n var v = 0;\n for (var i = 0; i < this.rows; i++) {\n for (var j = 0; j < this.columns; j++) {\n v += this.get(i, j);\n }\n }\n return v;\n }\n\n /**\n * Returns the mean of all elements of the matrix\n * @returns {number}\n */\n mean() {\n return this.sum() / this.size;\n }\n\n /**\n * Returns the product of all elements of the matrix\n * @returns {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 * @returns {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 * @returns {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 * @returns {Matrix}\n */\n mmul(other) {\n other = this.constructor.checkMatrix(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 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 /**\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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 * @returns {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 startRow - The index of the first row to set\n * @param startColumn - The index of the first column to set\n * @returns {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 if ((startRow > endRow) || (startColumn > endColumn) || (startRow < 0) || (startRow >= this.rows) || (endRow < 0) || (endRow >= this.rows) || (startColumn < 0) || (startColumn >= this.columns) || (endColumn < 0) || (endColumn >= this.columns)) {\n throw new RangeError('Argument out of range');\n }\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 * @returns {Matrix} The new matrix\n */\n selection(rowIndices, columnIndices) {\n var indices = util.checkIndices(this, rowIndices, columnIndices);\n var newMatrix = new this.constructor(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 * @returns {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 transposeView() {\n return new MatrixTransposeView(this);\n }\n\n rowView(row) {\n util.checkRowIndex(this, row);\n return new MatrixRowView(this, row);\n }\n\n columnView(column) {\n util.checkColumnIndex(this, column);\n return new MatrixColumnView(this, column);\n }\n\n flipRowView() {\n return new MatrixFlipRowView(this);\n }\n\n flipColumnView() {\n return new MatrixFlipColumnView(this);\n }\n\n subMatrixView(startRow, endRow, startColumn, endColumn) {\n return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);\n }\n\n selectionView(rowIndices, columnIndices) {\n return new MatrixSelectionView(this, rowIndices, columnIndices);\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) {\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\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(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(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(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 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 (var 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 (var 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 (var 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 (var 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 inplaceMethod = eval(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));\n var inplaceMethodS = eval(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));\n var inplaceMethodM = eval(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));\n var staticMethod = eval(fillTemplateFunction(staticMethodWithOneArg, tmplVar));\n for (var i = 2; i < methodWithArg.length; i++) {\n Matrix.prototype[methodWithArg[i]] = inplaceMethod;\n Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM;\n Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS;\n Matrix[methodWithArg[i]] = staticMethod;\n }\n }\n }\n\n function 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 return Matrix;\n}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-matrix/src/abstractMatrix.js\n ** module id = 17\n ** module chunks = 0\n **/","'use strict';\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 * @returns {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 * @returns {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\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-matrix/src/util.js\n ** module id = 18\n ** module chunks = 0\n **/","'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 = 19\n ** module chunks = 0\n **/","'use strict';\n\nvar abstractMatrix = require('../abstractMatrix');\nvar 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 if (!Matrix) {\n Matrix = require('../matrix');\n }\n return Matrix;\n }\n}\n\nmodule.exports = BaseView;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-matrix/src/views/base.js\n ** module id = 20\n ** module chunks = 0\n **/","'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 = 21\n ** module chunks = 0\n **/","'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 = 22\n ** module chunks = 0\n **/","'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 = 23\n ** module chunks = 0\n **/","'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, columnIndex) {\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 = 24\n ** module chunks = 0\n **/","'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 = 25\n ** module chunks = 0\n **/","'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 = 26\n ** module chunks = 0\n **/","'use strict';\n\nvar Matrix = require('./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\nMatrix.inverse = Matrix.inv = inverse;\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 = 27\n ** module chunks = 0\n **/","'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.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)\n wantu = false;\n if (options.computeRightSingularVectors === false)\n 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 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] = -e[k];\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 }\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 = 28\n ** module chunks = 0\n **/","'use strict';\n\nexports.hypotenuse = function hypotenuse(a, b) {\n if (Math.abs(a) > Math.abs(b)) {\n var r = b / a;\n return Math.abs(a) * Math.sqrt(1 + r * r);\n }\n if (b !== 0) {\n var 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 = 29\n ** module chunks = 0\n **/","'use strict';\n\nconst Matrix = require('../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 }\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 }\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 }\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 = 30\n ** module chunks = 0\n **/","'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 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 var determinant = this.pivotSign, col = data.columns;\n for (var j = 0; j < col; j++)\n determinant *= data[j][j];\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 if (this.isSingular())\n throw new Error('LU matrix is singular');\n\n var count = value.columns,\n X = value.subMatrixRow(this.pivotVector, 0, count - 1),\n columns = lu.columns,\n 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 = 31\n ** module chunks = 0\n **/","'use strict';\n\nvar Matrix = require('../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 if (!this.isFullRank())\n throw new Error('Matrix is rank deficient');\n\n var count = value.columns,\n X = value.clone(),\n n = qr.columns,\n 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 = 32\n ** module chunks = 0\n **/","'use strict';\n\nvar Matrix = require('../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 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 = 33\n ** module chunks = 0\n **/","'use strict';\n\nvar extend = require('extend');\n\nvar defaultOptions = {\n size: 1,\n value: 0\n};\n\n/**\n * Case when the entry is an array\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction arrayCase(data, options) {\n var len = data.length;\n if (typeof options.size === 'number')\n options.size = [options.size, options.size];\n\n var cond = len + options.size[0] + options.size[1];\n\n var output;\n if (options.output) {\n if (options.output.length !== cond)\n throw new RangeError('Wrong output size');\n output = options.output;\n }\n else\n output = new Array(cond);\n\n var i;\n\n // circular option\n if (options.value === 'circular') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[((len - (options.size[0] % len)) + i) % len];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[(i - options.size[0]) % len];\n }\n }\n\n // replicate option\n else if (options.value === 'replicate') {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[0];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[len - 1];\n }\n }\n\n // symmetric option\n else if (options.value === 'symmetric') {\n if ((options.size[0] > len) || (options.size[1] > len))\n throw new RangeError('expanded value should not be bigger than the data length');\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = data[options.size[0] - 1 - i];\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = data[2*len + options.size[0] - i - 1];\n }\n }\n\n // default option\n else {\n for (i = 0; i < cond; i++) {\n if (i < options.size[0])\n output[i] = options.value;\n else if (i < (options.size[0] + len))\n output[i] = data[i - options.size[0]];\n else\n output[i] = options.value;\n }\n }\n\n return output;\n}\n\n/**\n * Case when the entry is a matrix\n * @param data\n * @param options\n * @returns {Array}\n */\nfunction matrixCase(data, options) {\n var row = data.length;\n var col = data[0].length;\n if (options.size[0] === undefined)\n options.size = [options.size, options.size, options.size, options.size];\n throw new Error('matrix not supported yet, sorry');\n}\n\n/**\n * Pads and array\n * @param {Array } data\n * @param {object} options\n */\nfunction padArray (data, options) {\n options = extend({}, defaultOptions, options);\n\n if (Array.isArray(data)) {\n if (Array.isArray(data[0]))\n return matrixCase(data, options);\n else\n return arrayCase(data, options);\n }\n else\n throw new TypeError('data should be an array');\n}\n\nmodule.exports = padArray;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-pad-array/src/index.js\n ** module id = 34\n ** module chunks = 0\n **/","'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 ** ./~/ml-pad-array/~/extend/index.js\n ** module id = 35\n ** module chunks = 0\n **/","'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 = 36\n ** module chunks = 0\n **/","'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 ySquared = 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 ySquared += y[i] * y[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 = 'y = ';\n if (this.slope) {\n var xFactor = maybeToPrecision(this.slope, precision);\n result += (xFactor == 1 ? '' : 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 = 37\n ** module chunks = 0\n **/","'use strict';\n\nexports.maybeToPrecision = function maybeToPrecision(value, digits) {\n if (digits) return value.toPrecision(digits);\n else return value.toString();\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-regression/src/regression/util.js\n ** module id = 38\n ** module chunks = 0\n **/","'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(x) {\n throw new Error('_compute not implemented');\n }\n\n train(options) {\n //Do nothing for this package\n }\n\n toString(precision) {\n return '';\n }\n\n toLaTeX(precision) {\n return '';\n }\n\n /**\n * Return the correlation coefficient of determination (r) and chi-square.\n * @param x\n * @param y\n * @returns {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 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 = 39\n ** module chunks = 0\n **/","'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 if (this.coefficients[k] > 0)\n str = '+' + str;\n }\n fn = str + fn;\n }\n if (fn.charAt(0) === '+') {\n fn = fn.slice(1);\n }\n\n return 'y = ' + 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\n **/","'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');\nconst 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 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 'y = ' + maybeToPrecision(this.A, precision) + '*x^' + this.M;\n }\n\n toLaTeX(precision) {\n\n if (this.M >= 0)\n return 'y = ' + maybeToPrecision(this.A, precision) + 'x^{' + this.M + '}';\n else\n return 'y = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + (-this.M) + '}}';\n }\n\n static load(json) {\n if (json.name !== 'potentialRegression') {\n throw new TypeError('not a potential regression model');\n }\n return new PowerRegression(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 = 41\n ** module chunks = 0\n **/","'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 'y = ' + maybeToPrecision(this.A, precision) + '*x^' + maybeToPrecision(this.B, precision);\n }\n\n toLaTeX(precision) {\n if (this.B >= 0)\n return 'y = ' + maybeToPrecision(this.A, precision) + 'x^{' + maybeToPrecision(this.B, precision) + '}';\n else\n return 'y = \\\\frac{' + maybeToPrecision(this.A, precision) + '}{x^{' + maybeToPrecision(-this.B, precision) + '}}';\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 = 42\n ** module chunks = 0\n **/","'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 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.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 'y = ' + maybeToPrecision(this.C, precision) + '*exp(' + maybeToPrecision(this.A, precision) + '*x)';\n }\n\n toLaTeX(precision) {\n if (this.A >= 0)\n return 'y = ' + maybeToPrecision(this.C, precision) + 'e^{' + maybeToPrecision(this.A, precision) + 'x}';\n else\n return 'y = \\\\frac{' + maybeToPrecision(this.C, precision) + '}{e^{' + maybeToPrecision(-this.A, precision) + 'x}}';\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 = 43\n ** module chunks = 0\n **/","'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 = 44\n ** module chunks = 0\n **/","'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 = 45\n ** module chunks = 0\n **/","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass GaussianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = GaussianKernel;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kernel-gaussian/gaussian-kernel.js\n ** module id = 46\n ** module chunks = 0\n **/","'use strict';\n\nfunction squaredEuclidean(p, q) {\n var d = 0;\n for (var i = 0; i < p.length; i++) {\n d += (p[i] - q[i]) * (p[i] - q[i]);\n }\n return d;\n}\n\nfunction euclidean(p, q) {\n return Math.sqrt(squaredEuclidean(p, q));\n}\n\nmodule.exports = euclidean;\neuclidean.squared = squaredEuclidean;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance-euclidean/euclidean.js\n ** module id = 47\n ** module chunks = 0\n **/","'use strict';\n\nconst defaultOptions = {\n degree: 1,\n constant: 1,\n scale: 1\n};\n\nclass PolynomialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n\n this.degree = options.degree;\n this.constant = options.constant;\n this.scale = options.scale;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.pow(this.scale * sum + this.constant, this.degree);\n }\n}\n\nmodule.exports = PolynomialKernel;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kernel-polynomial/polynomial-kernel.js\n ** module id = 48\n ** module chunks = 0\n **/","'use strict';\n\nconst defaultOptions = {\n sigma: 1,\n degree: 1\n};\n\nclass ANOVAKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.degree = options.degree;\n }\n\n compute(x, y) {\n var sum = 0;\n var len = Math.min(x.length, y.length);\n for (var i = 1; i <= len; ++i) {\n sum += Math.pow(Math.exp(-this.sigma * Math.pow(Math.pow(x[i - 1], i) -\n Math.pow(y[i - 1], i), 2)), this.degree);\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kernel/src/kernels/anova-kernel.js\n ** module id = 49\n ** module chunks = 0\n **/","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass CauchyKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma));\n }\n}\n\nmodule.exports = CauchyKernel;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kernel/src/kernels/cauchy-kernel.js\n ** module id = 50\n ** module chunks = 0\n **/","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass ExponentialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = ExponentialKernel;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kernel/src/kernels/exponential-kernel.js\n ** module id = 51\n ** module chunks = 0\n **/","'use strict';\n\nclass HistogramIntersectionKernel {\n compute(x, y) {\n var min = Math.min(x.length, y.length);\n var sum = 0;\n for (var i = 0; i < min; ++i)\n sum += Math.min(x[i], y[i]);\n\n 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 = 52\n ** module chunks = 0\n **/","'use strict';\n\nconst euclidean = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass LaplacianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.sigma);\n }\n}\n\nmodule.exports = LaplacianKernel;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kernel/src/kernels/laplacian-kernel.js\n ** module id = 53\n ** module chunks = 0\n **/","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass MultiquadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant);\n }\n}\n\nmodule.exports = MultiquadraticKernel;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kernel/src/kernels/multiquadratic-kernel.js\n ** module id = 54\n ** module chunks = 0\n **/","'use strict';\n\nconst squaredEuclidean = require('ml-distance-euclidean').squared;\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass RationalQuadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return 1 - (distance / (distance + this.constant));\n }\n}\n\nmodule.exports = RationalQuadraticKernel;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kernel/src/kernels/rational-quadratic-kernel.js\n ** module id = 55\n ** module chunks = 0\n **/","'use strict';\n\nconst defaultOptions = {\n alpha: 0.01,\n constant: -Math.E\n};\n\nclass SigmoidKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.alpha = options.alpha;\n this.constant = options.constant;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.tanh(this.alpha * sum + this.constant);\n }\n}\n\nmodule.exports = SigmoidKernel;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kernel-sigmoid/sigmoid-kernel.js\n ** module id = 56\n ** module chunks = 0\n **/","'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 X - A matrix with n rows and 2 columns.\n * @param y - A vector of the prediction values.\n * @param options\n */\n train(X, y, options) {\n if (!Matrix.isMatrix(X)) X = new Matrix(X);\n if (!Matrix.isMatrix(y)) y = Matrix.columnVector(y);\n\n if (y.rows !== X.rows)//Perhaps y is transpose\n y = y.transpose();\n\n if (X.columns !== 2)\n throw new RangeError('You give X with ' + X.columns + ' columns and it must be 2');\n if (X.rows !== y.rows)\n throw new RangeError('X and y must have the same rows');\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 * @returns {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 = 57\n ** module chunks = 0\n **/","'use strict';\n\nconst BaseRegression = require('./base-regression');\nconst maybeToPrecision = require('./util').maybeToPrecision;\nconst median = require('ml-stat/array').median;\n\n/**\n * Theil–Sen estimator\n *\n * https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n * @class\n */\nclass TheilSenRegression extends BaseRegression {\n\n /**\n *\n * @param x\n * @param y\n * @param 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 = 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 // 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 = 'y = ';\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 = 58\n ** module chunks = 0\n **/","'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 = 59\n ** module chunks = 0\n **/","\"use strict\";\n\nexports.additiveSymmetric = require('./distances/additiveSymmetric');\nexports.avg = require('./distances/avg');\nexports.bhattacharyya = require('./distances/bhattacharyya');\nexports.canberra = require('./distances/canberra');\nexports.chebyshev = require('./distances/chebyshev');\nexports.clark = require('./distances/clark');\nexports.czekanowski = require('./distances/czekanowski');\nexports.dice = require('./distances/dice');\nexports.divergence = require('./distances/divergence');\nexports.euclidean = require('ml-distance-euclidean');\nexports.fidelity = require('./distances/fidelity');\nexports.gower = require('./distances/gower');\nexports.harmonicMean = require('./distances/harmonicMean');\nexports.hellinger = require('./distances/hellinger');\nexports.innerProduct = require('./distances/innerProduct');\nexports.intersection = require('./distances/intersection');\nexports.jaccard = require('./distances/jaccard');\nexports.jeffreys = require('./distances/jeffreys');\nexports.jensenDifference = require('./distances/jensenDifference');\nexports.jensenShannon = require('./distances/jensenShannon');\nexports.kdivergence = require('./distances/kdivergence');\nexports.kulczynski = require('./distances/kulczynski');\nexports.kullbackLeibler = require('./distances/kullbackLeibler');\nexports.kumarHassebrook = require('./distances/kumarHassebrook');\nexports.kumarJohnson = require('./distances/kumarJohnson');\nexports.lorentzian = require('./distances/lorentzian');\nexports.manhattan = require('./distances/manhattan');\nexports.matusita = require('./distances/matusita');\nexports.minkowski = require('./distances/minkowski');\nexports.motyka = require('./distances/motyka');\nexports.neyman = require('./distances/neyman');\nexports.pearson = require('./distances/pearson');\nexports.probabilisticSymmetric = require('./distances/probabilisticSymmetric');\nexports.ruzicka = require('./distances/ruzicka');\nexports.soergel = require('./distances/soergel');\nexports.sorensen = require('./distances/sorensen');\nexports.squared = require('./distances/squared');\nexports.squaredChord = require('./distances/squaredChord');\nexports.squaredEuclidean = require('ml-distance-euclidean').squared;\nexports.taneja = require('./distances/taneja');\nexports.tanimoto = require('./distances/tanimoto');\nexports.topsoe = require('./distances/topsoe');\nexports.tree = require('ml-tree-similarity');\nexports.waveHedges = require('./distances/waveHedges');\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances.js\n ** module id = 60\n ** module chunks = 0\n **/","module.exports = function additiveSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i]) * (a[i] + b[i])) / (a[i] * b[i]);\n }\n return 2 * d;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/additiveSymmetric.js\n ** module id = 61\n ** module chunks = 0\n **/","module.exports = function avg(a, b) {\n var ii = a.length,\n max = 0,\n ans = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n ans += aux;\n if (max < aux) {\n max = aux;\n }\n }\n return (max + ans) / 2;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/avg.js\n ** module id = 62\n ** module chunks = 0\n **/","module.exports = function bhattacharyya(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return - Math.log(ans);\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/bhattacharyya.js\n ** module id = 63\n ** module chunks = 0\n **/","module.exports = function canberra(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]) / (a[i] + b[i]);\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/canberra.js\n ** module id = 64\n ** module chunks = 0\n **/","module.exports = function chebyshev(a, b) {\n var ii = a.length,\n max = 0,\n aux = 0;\n for (var i = 0; i < ii ; i++) {\n aux = Math.abs(a[i] - b[i]);\n if (max < aux) {\n max = aux;\n }\n }\n return max;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/chebyshev.js\n ** module id = 65\n ** module chunks = 0\n **/","module.exports = function clark(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.sqrt(((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i])));\n }\n return 2 * d;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/clark.js\n ** module id = 66\n ** module chunks = 0\n **/","'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 = 67\n ** module chunks = 0\n **/","'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 = 68\n ** module chunks = 0\n **/","module.exports = function dice(a, b) {\n var ii = a.length,\n p = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p + q1);\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/dice.js\n ** module id = 69\n ** module chunks = 0\n **/","module.exports = function divergence(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / ((a[i] + b[i]) * (a[i] + b[i]));\n }\n return 2 * d;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/divergence.js\n ** module id = 70\n ** module chunks = 0\n **/","module.exports = function fidelity(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/fidelity.js\n ** module id = 71\n ** module chunks = 0\n **/","module.exports = function gower(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.abs(a[i] - b[i]);\n }\n return ans / ii;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/gower.js\n ** module id = 72\n ** module chunks = 0\n **/","module.exports = function harmonicMean(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] * b[i]) / (a[i] + b[i]);\n }\n return 2 * ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/harmonicMean.js\n ** module id = 73\n ** module chunks = 0\n **/","module.exports = function hellinger(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return 2 * Math.sqrt(1 - ans);\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/hellinger.js\n ** module id = 74\n ** module chunks = 0\n **/","module.exports = function innerProduct(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * b[i];\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/innerProduct.js\n ** module id = 75\n ** module chunks = 0\n **/","module.exports = function intersection(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.min(a[i], b[i]);\n }\n return 1 - ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/intersection.js\n ** module id = 76\n ** module chunks = 0\n **/","module.exports = function jaccard(a, b) {\n var ii = a.length,\n p1 = 0,\n p2 = 0,\n q1 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p1 += a[i] * b[i];\n p2 += a[i] * a[i];\n q1 += b[i] * b[i];\n q2 += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return q2 / (p2 + q1 - p1);\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/jaccard.js\n ** module id = 77\n ** module chunks = 0\n **/","module.exports = function jeffreys(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] - b[i]) * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/jeffreys.js\n ** module id = 78\n ** module chunks = 0\n **/","module.exports = function jensenDifference(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += ((a[i] * Math.log(a[i]) + b[i] * Math.log(b[i])) / 2) - ((a[i] + b[i]) / 2) * Math.log((a[i] + b[i]) / 2);\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/jensenDifference.js\n ** module id = 79\n ** module chunks = 0\n **/","module.exports = function jensenShannon(a, b) {\n var ii = a.length,\n p = 0,\n q = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n q += b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return (p + q) / 2;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/jensenShannon.js\n ** module id = 80\n ** module chunks = 0\n **/","module.exports = function kdivergence(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i]));\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/kdivergence.js\n ** module id = 81\n ** module chunks = 0\n **/","module.exports = function kulczynski(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.min(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/kulczynski.js\n ** module id = 82\n ** module chunks = 0\n **/","module.exports = function kullbackLeibler(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(a[i] / b[i]);\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/kullbackLeibler.js\n ** module id = 83\n ** module chunks = 0\n **/","module.exports = function kumarHassebrook(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (p2 + q2 - p);\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/kumarHassebrook.js\n ** module id = 84\n ** module chunks = 0\n **/","module.exports = function kumarJohnson(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.pow(a[i] * a[i] - b[i] * b[i],2) / (2 * Math.pow(a[i] * b[i],1.5));\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/kumarJohnson.js\n ** module id = 85\n ** module chunks = 0\n **/","module.exports = function lorentzian(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.log(Math.abs(a[i] - b[i]) + 1);\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/lorentzian.js\n ** module id = 86\n ** module chunks = 0\n **/","module.exports = function manhattan(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.abs(a[i] - b[i]);\n }\n return d;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/manhattan.js\n ** module id = 87\n ** module chunks = 0\n **/","module.exports = function matusita(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += Math.sqrt(a[i] * b[i]);\n }\n return Math.sqrt(2 - 2 * ans);\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/matusita.js\n ** module id = 88\n ** module chunks = 0\n **/","module.exports = function minkowski(a, b, p) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += Math.pow(Math.abs(a[i] - b[i]),p);\n }\n return Math.pow(d,(1/p));\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/minkowski.js\n ** module id = 89\n ** module chunks = 0\n **/","module.exports = function motyka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i], b[i]);\n down += a[i] + b[i];\n }\n return 1 - (up / down);\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/motyka.js\n ** module id = 90\n ** module chunks = 0\n **/","module.exports = function neyman(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / a[i];\n }\n return d;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/neyman.js\n ** module id = 91\n ** module chunks = 0\n **/","module.exports = function pearson(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / b[i];\n }\n return d;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/pearson.js\n ** module id = 92\n ** module chunks = 0\n **/","module.exports = function probabilisticSymmetric(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return 2 * d;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/probabilisticSymmetric.js\n ** module id = 93\n ** module chunks = 0\n **/","module.exports = function ruzicka(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.min(a[i],b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/ruzicka.js\n ** module id = 94\n ** module chunks = 0\n **/","module.exports = function soergel(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += Math.max(a[i],b[i]);\n }\n return up / down;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/soergel.js\n ** module id = 95\n ** module chunks = 0\n **/","module.exports = function sorensen(a, b) {\n var ii = a.length,\n up = 0,\n down = 0;\n for (var i = 0; i < ii ; i++) {\n up += Math.abs(a[i] - b[i]);\n down += a[i] + b[i];\n }\n return up / down;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/sorensen.js\n ** module id = 96\n ** module chunks = 0\n **/","module.exports = function squared(a, b) {\n var i = 0,\n ii = a.length,\n d = 0;\n for (; i < ii; i++) {\n d += ((a[i] - b[i]) * (a[i] - b[i])) / (a[i] + b[i]);\n }\n return d;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/squared.js\n ** module id = 97\n ** module chunks = 0\n **/","module.exports = function squaredChord(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (Math.sqrt(a[i]) - Math.sqrt(b[i])) * (Math.sqrt(a[i]) - Math.sqrt(b[i]));\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/squaredChord.js\n ** module id = 98\n ** module chunks = 0\n **/","module.exports = function taneja(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += (a[i] + b[i]) / 2 * Math.log((a[i] + b[i]) / (2 * Math.sqrt(a[i] * b[i])));\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/taneja.js\n ** module id = 99\n ** module chunks = 0\n **/","var tanimotoS = require('./../similarities/tanimoto');\n\nmodule.exports = function tanimoto(a, b, bitvector) {\n if (bitvector)\n return 1 - tanimotoS(a, b, bitvector);\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return (p + q - 2 * m) / (p + q - m);\n }\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/tanimoto.js\n ** module id = 100\n ** module chunks = 0\n **/","module.exports = function tanimoto(a, b, bitvector) {\n if (bitvector) {\n var inter = 0,\n union = 0;\n for (var j = 0; j < a.length; j++) {\n inter += a[j] && b[j];\n union += a[j] || b[j];\n }\n if (union === 0)\n return 1;\n return inter / union;\n }\n else {\n var ii = a.length,\n p = 0,\n q = 0,\n m = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i];\n q += b[i];\n m += Math.min(a[i],b[i]);\n }\n return 1 - (p + q - 2 * m) / (p + q - m);\n }\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/similarities/tanimoto.js\n ** module id = 101\n ** module chunks = 0\n **/","module.exports = function topsoe(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += a[i] * Math.log(2 * a[i] / (a[i] + b[i])) + b[i] * Math.log(2 * b[i] / (a[i] + b[i]));\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/topsoe.js\n ** module id = 102\n ** module chunks = 0\n **/","\"use strict\";\n\n/**\n * Function that creates the tree\n * @param {Array } X - chemical shifts of the signal\n * @param {Array } Y - intensity of the signal\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {number} minWindow - smallest range to accept in x\n * @param {number} threshold - smallest range to accept in y\n * @returns {{sum: number, center: number, left: {json}, right: {json}}}\n * left and right have the same structure than the parent, or have a\n * undefined value if are leafs\n */\nfunction createTree (X, Y, from, to, minWindow, threshold) {\n minWindow = minWindow || 0.16;\n threshold = threshold || 0.01;\n if ((to - from) < minWindow)\n return undefined;\n var sum = 0;\n for (var i = 0; X[i] < to; i++) {\n if (X[i] > from)\n sum += Y[i];\n }\n if (sum < threshold) {\n return undefined;\n }\n var center = 0;\n for (var j = 0; X[j] < to; j++) {\n if (X[i] > from)\n center += X[j] * Y[j];\n }\n center = center / sum;\n if (((center - from) < 10e-6) || ((to - center) < 10e-6)) return undefined;\n if ((center - from) < (minWindow /4)) {\n return createTree(X, Y, center, to, minWindow, threshold);\n }\n else {\n if ((to - center) < (minWindow / 4)) {\n return createTree(X, Y, from, center, minWindow, threshold);\n }\n else {\n return {\n 'sum': sum,\n 'center': center,\n 'left': createTree(X, Y, from, center, minWindow, threshold),\n 'right': createTree(X, Y, center, to, minWindow, threshold)\n };\n }\n }\n}\n\n/**\n * Similarity between two nodes\n * @param {{sum: number, center: number, left: {json}, right: {json}}} a - tree A node\n * @param {{sum: number, center: number, left: {json}, right: {json}}} b - tree B node\n * @param {number} alpha - weights the relative importance of intensity vs. shift match\n * @param {number} beta - weights the relative importance of node matching and children matching\n * @param {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @returns {number} similarity measure between tree nodes\n */\nfunction S(a, b, alpha, beta, gamma) {\n if (a === undefined || b === undefined) {\n return 0;\n }\n else {\n var C = (alpha*Math.min(a.sum, b.sum)/Math.max(a.sum, b.sum)+ (1-alpha)*Math.exp(-gamma*Math.abs(a.center - b.center)));\n }\n return beta*C + (1-beta)*(S(a.left, b.left, alpha, beta, gamma)+S(a.right, b.right, alpha, beta, gamma));\n}\n\n/**\n * @type {number} alpha - weights the relative importance of intensity vs. shift match\n * @type {number} beta - weights the relative importance of node matching and children matching\n * @type {number} gamma - controls the attenuation of the effect of chemical shift differences\n * @type {number} minWindow - smallest range to accept in x\n * @type {number} threshold - smallest range to accept in y\n */\nvar defaultOptions = {\n minWindow: 0.16,\n threshold : 0.01,\n alpha: 0.1,\n beta: 0.33,\n gamma: 0.001\n};\n\n/**\n * Builds a tree based in the spectra and compares this trees\n * @param {{x: Array, y: Array}} A - first spectra to be compared\n * @param {{x: Array, y: Array}} B - second spectra to be compared\n * @param {number} from - the low limit of x\n * @param {number} to - the top limit of x\n * @param {{minWindow: number, threshold: number, alpha: number, beta: number, gamma: number}} options\n * @returns {number} similarity measure between the spectra\n */\nfunction tree(A, B, from, to, options) {\n options = options || {};\n for (var o in defaultOptions)\n if (!options.hasOwnProperty(o)) {\n options[o] = defaultOptions[o];\n }\n var Atree, Btree;\n if (A.sum)\n Atree = A;\n else\n Atree = createTree(A.x, A.y, from, to, options.minWindow, options.threshold);\n if (B.sum)\n Btree = B;\n else\n Btree = createTree(B.x, B.y, from, to, options.minWindow, options.threshold);\n return S(Atree, Btree, options.alpha, options.beta, options.gamma);\n}\n\nmodule.exports = {\n calc: tree,\n createTree: createTree\n};\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-tree-similarity/src/index.js\n ** module id = 103\n ** module chunks = 0\n **/","module.exports = function waveHedges(a, b) {\n var ii = a.length,\n ans = 0;\n for (var i = 0; i < ii ; i++) {\n ans += 1 - (Math.min(a[i], b[i]) / Math.max(a[i], b[i]));\n }\n return ans;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/distances/waveHedges.js\n ** module id = 104\n ** module chunks = 0\n **/","\"use strict\";\n\nexports.cosine = require('./similarities/cosine');\nexports.czekanowski = require('./similarities/czekanowski');\nexports.dice = require('./similarities/dice');\nexports.intersection = require('./similarities/intersection');\nexports.jaccard = require('./similarities/jaccard');\nexports.kulczynski = require('./similarities/kulczynski');\nexports.motyka = require('./similarities/motyka');\nexports.pearson = require('./similarities/pearson');\nexports.squaredChord = require('./similarities/squaredChord');\nexports.tanimoto = require('./similarities/tanimoto');\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/similarities.js\n ** module id = 105\n ** module chunks = 0\n **/","module.exports = function cosine(a, b) {\n var ii = a.length,\n p = 0,\n p2 = 0,\n q2 = 0;\n for (var i = 0; i < ii ; i++) {\n p += a[i] * b[i];\n p2 += a[i] * a[i];\n q2 += b[i] * b[i];\n }\n return p / (Math.sqrt(p2) * Math.sqrt(q2));\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-distance/src/similarities/cosine.js\n ** module id = 106\n ** module chunks = 0\n **/","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 = 107\n ** module chunks = 0\n **/","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 = 108\n ** module chunks = 0\n **/","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 = 109\n ** module chunks = 0\n **/","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 = 110\n ** module chunks = 0\n **/","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 = 111\n ** module chunks = 0\n **/","'use strict';\n\nvar stat=require('ml-stat').array;\nvar cosine=require('./cosine');\n\nmodule.exports = function pearson(a, b) {\n var avgA=stat.mean(a);\n var avgB=stat.mean(b);\n\n var newA=new Array(a.length);\n var newB=new Array(b.length);\n for (var i=0; i} 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 = 114\n ** module chunks = 0\n **/","'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 = 115\n ** module chunks = 0\n **/","//Code translate from Pascal source in http://pubs.acs.org/doi/pdf/10.1021/ac00205a007\nvar extend = require('extend');\nvar stat = require('ml-stat');\n\nvar defaultOptions = {\n windowSize: 9,\n derivative: 0,\n polynomial: 3,\n};\n\n\nfunction SavitzkyGolay(data, h, options) {\n options = extend({}, defaultOptions, options);\n\n if ((options.windowSize % 2 === 0) || (options.windowSize < 5) || !(Number.isInteger(options.windowSize)))\n throw new RangeError('Invalid window size (should be odd and at least 5 integer number)')\n\n\n if (options.windowSize>data.length)\n throw new RangeError('Window size is higher than the data length '+options.windowSize+\">\"+data.length);\n if ((options.derivative < 0) || !(Number.isInteger(options.derivative)))\n throw new RangeError('Derivative should be a positive integer');\n if ((options.polynomial < 1) || !(Number.isInteger(options.polynomial)))\n throw new RangeError('Polynomial should be a positive integer');\n if (options.polynomial >= 6)\n console.warn('You should not use polynomial grade higher than 5 if you are' +\n ' not sure that your data arises from such a model. Possible polynomial oscillation problems');\n\n var windowSize = options.windowSize;\n\n var half = Math.floor(windowSize/2);\n var np = data.length;\n var ans = new Array(np);\n var weights = fullWeights(windowSize,options.polynomial,options.derivative);\n var hs = 0;\n var constantH = true;\n if( Object.prototype.toString.call( h ) === '[object Array]' ) {\n constantH = false;\n }\n else{\n hs = Math.pow(h, options.derivative);\n }\n //console.log(\"Constant h: \"+constantH);\n //For the borders\n for(var i=0;i=0 && i < h.length-1){\n hs+= (h[i+1]-h[i]);\n count++;\n }\n }\n return Math.pow(hs/count,derivative);\n}\n\nfunction GramPoly(i,m,k,s){\n var Grampoly = 0;\n if(k>0){\n Grampoly = (4*k-2)/(k*(2*m-k+1))*(i*GramPoly(i,m,k-1,s) +\n s*GramPoly(i,m,k-1,s-1)) - ((k-1)*(2*m+k))/(k*(2*m-k+1))*GramPoly(i,m,k-2,s);\n }\n else{\n if(k==0&&s==0){\n Grampoly=1;\n }\n else{\n Grampoly=0;\n }\n }\n //console.log(Grampoly);\n return Grampoly;\n}\n\nfunction GenFact(a,b){\n var gf=1;\n if(a>=b){\n for(var j=a-b+1;j<=a;j++){\n gf*=j;\n }\n }\n return gf;\n}\n\nfunction Weight(i,t,m,n,s){\n var sum=0;\n for(var k=0;k<=n;k++){\n //console.log(k);\n sum+=(2*k+1)*(GenFact(2*m,k)/GenFact(2*m+k+1,k+1))*GramPoly(i,m,k,0)*GramPoly(t,m,k,s)\n }\n return sum;\n}\n\n/**\n *\n * @param m Number of points\n * @param n Polynomial grade\n * @param s Derivative\n */\nfunction fullWeights(m,n,s){\n var weights = new Array(m);\n var np = Math.floor(m/2);\n for(var t=-np;t<=np;t++){\n weights[t+np] = new Array(m);\n for(var j=-np;j<=np;j++){\n weights[t+np][j+np]=Weight(j,t,np,n,s);\n }\n }\n return weights;\n}\n\n/*function entropy(data,h,options){\n var trend = SavitzkyGolay(data,h,trendOptions);\n var copy = new Array(data.length);\n var sum = 0;\n var max = 0;\n for(var i=0;i 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 = 118\n ** module chunks = 0\n **/","'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 = 119\n ** module chunks = 0\n **/","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 = 120\n ** module chunks = 0\n **/","'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 = 121\n ** module chunks = 0\n **/","'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 = 122\n ** module chunks = 0\n **/","/**\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 = 123\n ** module chunks = 0\n **/","/**\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 = 124\n ** module chunks = 0\n **/","'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 = 125\n ** module chunks = 0\n **/","'use strict';\n\nconst measures = require('./measures');\n\nclass Performance {\n /**\n *\n * @param prediction - The prediction matrix\n * @param target - The target matrix (values: truthy for same class, falsy for different class)\n * @param options\n *\n * @option all True if the entire matrix must be used. False to ignore the diagonal and lower part (default is false, for similarity/distance matrices)\n * @option max True if the max value corresponds to a perfect match (like in similarity matrices), false if it is the min value (default is false, like in distance matrices. All values will be multiplied by -1)\n */\n constructor(prediction, target, options) {\n options = options || {};\n if (prediction.length !== target.length || prediction[0].length !== target[0].length) {\n throw new Error('dimensions of prediction and target do not match');\n }\n const rows = prediction.length;\n const columns = prediction[0].length;\n const isDistance = !options.max;\n\n const predP = [];\n\n if (options.all) {\n for (var i = 0; i < rows; i++) {\n for (var j = 0; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n } else {\n if (rows < 3 || rows !== columns) {\n throw new Error('When \"all\" option is false, the prediction matrix must be square and have at least 3 columns');\n }\n for (var i = 0; i < rows - 1; i++) {\n for (var j = i + 1; j < columns; j++) {\n predP.push({\n pred: prediction[i][j],\n targ: target[i][j]\n });\n }\n }\n }\n\n if (isDistance) {\n predP.sort((a, b) => a.pred - b.pred);\n } else {\n predP.sort((a, b) => b.pred - a.pred);\n }\n \n const cutoffs = this.cutoffs = [isDistance ? Number.MIN_VALUE : Number.MAX_VALUE];\n const fp = this.fp = [0];\n const tp = this.tp = [0];\n\n var nPos = 0;\n var nNeg = 0;\n\n var currentPred = predP[0].pred;\n var nTp = 0;\n var nFp = 0;\n for (var i = 0; i < predP.length; i++) {\n if (predP[i].pred !== currentPred) {\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n currentPred = predP[i].pred;\n }\n if (predP[i].targ) {\n nPos++;\n nTp++;\n } else {\n nNeg++;\n nFp++;\n }\n }\n cutoffs.push(currentPred);\n fp.push(nFp);\n tp.push(nTp);\n\n const l = cutoffs.length;\n const fn = this.fn = new Array(l);\n const tn = this.tn = new Array(l);\n const nPosPred = this.nPosPred = new Array(l);\n const nNegPred = this.nNegPred = new Array(l);\n\n for (var i = 0; i < l; i++) {\n fn[i] = nPos - tp[i];\n tn[i] = nNeg - fp[i];\n\n nPosPred[i] = tp[i] + fp[i];\n nNegPred[i] = tn[i] + fn[i];\n }\n\n this.nPos = nPos;\n this.nNeg = nNeg;\n this.nSamples = nPos + nNeg;\n }\n\n /**\n * Computes a measure from the prediction object.\n *\n * Many measures are available and can be combined :\n * To create a ROC curve, you need fpr and tpr\n * To create a DET curve, you need fnr and fpr\n * To create a Lift chart, you need rpp and lift\n *\n * Possible measures are : threshold (Threshold), acc (Accuracy), err (Error rate),\n * fpr (False positive rate), tpr (True positive rate), fnr (False negative rate), tnr (True negative rate), ppv (Positive predictive value),\n * npv (Negative predictive value), pcfall (Prediction-conditioned fallout), pcmiss (Prediction-conditioned miss), lift (Lift value), rpp (Rate of positive predictions), rnp (Rate of negative predictions)\n *\n * @param measure - The short name of the measure\n *\n * @return [number]\n */\n getMeasure(measure) {\n if (typeof measure !== 'string') {\n throw new Error('No measure specified');\n }\n if (!measures[measure]) {\n throw new Error(`The specified measure (${measure}) does not exist`);\n }\n return measures[measure](this);\n }\n\n /**\n * Returns the area under the ROC curve\n */\n getAURC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fp[i] / this.nNeg;\n y[i] = this.tp[i] / this.nPos;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] - x[i - 1]) * (y[i] + y[i - 1]);\n }\n return auc;\n }\n\n /**\n * Returns the area under the DET curve\n */\n getAUDC() {\n const l = this.cutoffs.length;\n const x = new Array(l);\n const y = new Array(l);\n for (var i = 0; i < l; i++) {\n x[i] = this.fn[i] / this.nPos;\n y[i] = this.fp[i] / this.nNeg;\n }\n var auc = 0;\n for (i = 1; i < l; i++) {\n auc += 0.5 * (x[i] + x[i - 1]) * (y[i] - y[i - 1]);\n }\n return auc;\n }\n\n getDistribution(options) {\n options = options || {};\n var cutLength = this.cutoffs.length;\n var cutLow = options.xMin || Math.floor(this.cutoffs[cutLength - 1] * 100) / 100;\n var cutHigh = options.xMax || Math.ceil(this.cutoffs[1] * 100) / 100;\n var interval = options.interval || Math.floor(((cutHigh - cutLow) / 20 * 10000000) - 1) / 10000000; // Trick to avoid the precision problem of float numbers\n\n var xLabels = [];\n var interValues = [];\n var intraValues = [];\n var interCumPercent = [];\n var intraCumPercent = [];\n\n var nTP = this.tp[cutLength - 1], currentTP = 0;\n var nFP = this.fp[cutLength - 1], currentFP = 0;\n\n for (var i = cutLow, j = (cutLength - 1); i <= cutHigh; i += interval) {\n while (this.cutoffs[j] < i)\n j--;\n\n xLabels.push(i);\n\n var thisTP = nTP - currentTP - this.tp[j];\n var thisFP = nFP - currentFP - this.fp[j];\n\n currentTP += thisTP;\n currentFP += thisFP;\n\n interValues.push(thisFP);\n intraValues.push(thisTP);\n\n interCumPercent.push(100 - (nFP - this.fp[j]) / nFP * 100);\n intraCumPercent.push(100 - (nTP - this.tp[j]) / nTP * 100);\n }\n\n return {\n xLabels: xLabels,\n interValues: interValues,\n intraValues: intraValues,\n interCumPercent: interCumPercent,\n intraCumPercent: intraCumPercent\n };\n }\n}\n\nPerformance.names = {\n acc: 'Accuracy',\n err: 'Error rate',\n fpr: 'False positive rate',\n tpr: 'True positive rate',\n fnr: 'False negative rate',\n tnr: 'True negative rate',\n ppv: 'Positive predictive value',\n npv: 'Negative predictive value',\n pcfall: 'Prediction-conditioned fallout',\n pcmiss: 'Prediction-conditioned miss',\n lift: 'Lift value',\n rpp: 'Rate of positive predictions',\n rnp: 'Rate of negative predictions',\n threshold: 'Threshold'\n};\n\nmodule.exports = Performance;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-performance/src/index.js\n ** module id = 126\n ** module chunks = 0\n **/","'use strict';\n\n// Accuracy\nexports.acc = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.tn[i] + pred.tp[i]) / (l - 1);\n }\n return result;\n};\n\n// Error rate\nexports.err = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.fp[i] / (l - 1));\n }\n return result;\n};\n\n// False positive rate\nexports.fpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fp[i] / pred.nNeg;\n }\n return result;\n};\n\n// True positive rate\nexports.tpr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tp[i] / pred.nPos;\n }\n return result;\n};\n\n// False negative rate\nexports.fnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.fn[i] / pred.nPos;\n }\n return result;\n};\n\n// True negative rate\nexports.tnr = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.tn[i] / pred.nNeg;\n }\n return result;\n};\n\n// Positive predictive value\nexports.ppv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 0;\n }\n return result;\n};\n\n// Negative predictive value\nexports.npv = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 0;\n }\n return result;\n};\n\n// Prediction conditioned fallout\nexports.pcfall = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fp[i] + pred.tp[i] !== 0) ? 1 - (pred.tp[i] / (pred.fp[i] + pred.tp[i])) : 1;\n }\n return result;\n};\n\n// Prediction conditioned miss\nexports.pcmiss = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.fn[i] + pred.tn[i] !== 0) ? 1 - (pred.tn[i] / (pred.fn[i] + pred.tn[i])) : 1;\n }\n return result;\n};\n\n// Lift value\nexports.lift = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = (pred.nPosPred[i] !== 0) ? ((pred.tp[i] / pred.nPos) / (pred.nPosPred[i] / pred.nSamples)) : 0;\n }\n return result;\n};\n\n// Rate of positive predictions\nexports.rpp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nPosPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Rate of negative predictions\nexports.rnp = pred => {\n const l = pred.cutoffs.length;\n const result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = pred.nNegPred[i] / pred.nSamples;\n }\n return result;\n};\n\n// Threshold\nexports.threshold = pred => {\n const clone = pred.cutoffs.slice();\n clone[0] = clone[1]; // Remove the infinite value\n return clone;\n};\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-performance/src/measures.js\n ** module id = 127\n ** module chunks = 0\n **/","\"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 = 128\n ** module chunks = 0\n **/","'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 = 129\n ** module chunks = 0\n **/","'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 = 130\n ** module chunks = 0\n **/","'use strict';\nconst defaultOptions = {\n mode: 'index'\n};\n\nmodule.exports = function *(M, N, options) {\n options = Object.assign({}, defaultOptions, options);\n var a = new Array(N);\n var c = new Array(M);\n var b = new Array(N);\n var p = new Array(N + 2);\n var x, y, z;\n\n // init a and b\n for (var i = 0; i < N; i++) {\n a[i] = i;\n if (i < N - M) b[i] = 0;\n else b[i] = 1;\n }\n\n // init c\n for (i = 0; i < M; i++) {\n c[i] = N - M + i;\n }\n\n // init p\n for (i = 0; i < p.length; i++) {\n if (i === 0) p[i] = N + 1;\n else if (i <= N - M) p[i] = 0;\n else if (i <= N) p[i] = i - N + M;\n else p[i] = -2;\n }\n\n function twiddle() {\n var i, j, k;\n j = 1;\n while (p[j] <= 0)\n j++;\n 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 = 131\n ** module chunks = 0\n **/","'use strict';\nconst Kernel = require('ml-kernel');\nconst stat = require('ml-stat').array;\n\nvar defaultOptions = {\n C: 1,\n tol: 1e-4,\n maxPasses: 10,\n maxIterations: 10000,\n kernel: 'linear',\n alphaTol: 1e-6,\n random: Math.random,\n whitening: true\n};\n\n/**\n * Simplified version of the Sequential Minimal Optimization algorithm for training\n * support vector machines\n * @param {{Object}} options - SVM options\n * @param {Number} [options.C=1] - regularization parameter\n * @param {Number} [options.tol=1e-4] - numerical tolerance\n * @param {Number} [options.alphaTol=1e-6] - alpha tolerance, threshold to decide support vectors\n * @param {Number} [options.maxPasses=10] - max number of times to iterate over alphas without changing\n * @param {Number} [options.maxIterations=10000] - max number of iterations\n * @param {String} [options.kernel=linear] - the kind of kernel. {@link https://github.com/mljs/kernel/tree/1252de5f9012776e6e0eb06c7b434b8631fb21f0 List of kernels}\n * @param {Function} [options.random=Math.random] - custom random number generator\n * @constructor\n */\nfunction SVM(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n this.kernel = new Kernel(this.options.kernel, this.options.kernelOptions);\n this.b = 0;\n}\n\n/**\n * Train the SVM model\n * @param {Array >} features - training data features\n * @param {Array } labels - training data labels in the domain {1,-1}\n */\nSVM.prototype.train = function (features, labels) {\n if (features.length !== labels.length) {\n throw new Error('Features and labels should have the same length');\n }\n if (features.length < 2) {\n throw new Error('Cannot train with less than 2 observations');\n }\n this._trained = false;\n this._loaded = false;\n this.N = labels.length;\n this.D = features[0].length;\n if (this.options.whitening) {\n this.X = new Array(this.N);\n for (var i = 0; i < this.N; i++) {\n this.X[i] = new Array(this.D);\n }\n this.minMax = new Array(this.D);\n // Apply normalization and keep normalization parameters\n for (var j = 0; j < this.D; j++) {\n var d = new Array(this.N);\n for (i = 0; i < this.N; i++) {\n d[i] = features[i][j];\n }\n this.minMax[j] = stat.minMax(d);\n for (i = 0; i < this.N; i++) {\n this.X[i][j] = (features[i][j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n }\n } else {\n this.X = features;\n }\n this.Y = labels;\n this.b = 0;\n this.W = undefined;\n\n var kernel = this.kernel.compute(this.X);\n var m = labels.length;\n var alpha = new Array(m).fill(0);\n this.alphas = alpha;\n for (var a = 0; a < m; a++)\n alpha[a] = 0;\n\n var b1 = 0,\n b2 = 0,\n iter = 0,\n passes = 0,\n Ei = 0,\n Ej = 0,\n ai = 0,\n aj = 0,\n L = 0,\n H = 0,\n eta = 0;\n\n while (passes < this.options.maxPasses && iter < this.options.maxIterations) {\n var numChange = 0;\n for (i = 0; i < m; i++) {\n Ei = this._marginOnePrecomputed(i, kernel) - labels[i];\n if (labels[i] * Ei < -this.options.tol && alpha[i] < this.options.C || labels[i] * Ei > this.options.tol && alpha[i] > 0) {\n j = i;\n while (j === i) j = Math.floor(this.options.random() * m);\n Ej = this._marginOnePrecomputed(j, kernel) - labels[j];\n ai = alpha[i];\n aj = alpha[j];\n if (labels[i] === labels[j]) {\n L = Math.max(0, ai + aj - this.options.C);\n H = Math.min(this.options.C, ai + aj);\n } else {\n L = Math.max(0, aj - ai);\n H = Math.min(this.options.C, this.options.C + aj + ai);\n }\n if (Math.abs(L - H) < 1e-4) continue;\n\n eta = 2 * kernel[i][j] - kernel[i][i] - kernel[j][j];\n if (eta >= 0) continue;\n var newaj = alpha[j] - labels[j] * (Ei - Ej) / eta;\n if (newaj > H)\n newaj = H;\n else if (newaj < L)\n newaj = L;\n if (Math.abs(aj - newaj) < 10e-4) continue;\n alpha[j] = newaj;\n alpha[i] = alpha[i] + labels[i] * labels[j] * (aj - newaj);\n b1 = this.b - Ei - labels[i] * (alpha[i] - ai) * kernel[i][i] - labels[j] * (alpha[j] - aj) * kernel[i][j];\n b2 = this.b - Ej - labels[i] * (alpha[i] - ai) * kernel[i][j] - labels[j] * (alpha[j] - aj) * kernel[j][j];\n this.b = (b1 + b2) / 2;\n if (alpha[i] < this.options.C && alpha[i] > 0) this.b = b1;\n if (alpha[j] < this.options.C && alpha[j] > 0) this.b = b2;\n numChange += 1;\n }\n }\n iter++;\n if (numChange === 0)\n passes += 1;\n else\n passes = 0;\n }\n if (iter === this.options.maxIterations) {\n throw new Error('max iterations reached');\n }\n\n this.iterations = iter;\n\n // Compute the weights (useful for fast decision on new test instances when linear SVM)\n if (this.options.kernel === 'linear') {\n this.W = new Array(this.D);\n for (var r = 0; r < this.D; r++) {\n this.W[r] = 0;\n for (var w = 0; w < m; w++)\n this.W[r] += labels[w] * alpha[w] * this.X[w][r];\n }\n }\n\n // Keep only support vectors\n // It will compute decision on new test instances faster\n // We also keep the index of the support vectors\n // in the original data\n var nX = [];\n var nY = [];\n var nAlphas = [];\n this._supportVectorIdx = [];\n for (i = 0; i < this.N; i++) {\n if (this.alphas[i] > this.options.alphaTol) {\n nX.push(this.X[i]);\n nY.push(labels[i]);\n nAlphas.push(this.alphas[i]);\n this._supportVectorIdx.push(i);\n\n }\n }\n this.X = nX;\n this.Y = nY;\n this.N = nX.length;\n this.alphas = nAlphas;\n\n\n // A flag to say this SVM has been trained\n this._trained = true;\n};\n\n/**\n * Get prediction ({-1,1}) given one observation's features.\n * @private\n * @param p The observation's features.\n * @returns {number} Classification result ({-1,1})\n */\nSVM.prototype.predictOne = function (p) {\n var margin = this.marginOne(p);\n return margin > 0 ? 1 : -1;\n};\n\n/**\n * Predict the classification outcome of a trained svm given one or several observations' features.\n * @param {Array} features - The observation(s)' features\n * @returns {Array|Number} An array of {-1, 1} if several observations are given or a number if one observation\n * is given\n */\nSVM.prototype.predict = function (features) {\n if (!this._trained && !this._loaded) throw new Error('Cannot predict, you need to train the SVM first');\n if (Array.isArray(features) && Array.isArray(features[0])) {\n return features.map(this.predictOne.bind(this));\n } else {\n return this.predictOne(features);\n }\n};\n\n/**\n * Get margin given one observation's features\n * @private\n * @param {Array} features - Features\n * @returns {Number} - The computed margin\n */\nSVM.prototype.marginOne = function (features, noWhitening) {\n // Apply normalization\n if (this.options.whitening && !noWhitening) {\n features = this._applyWhitening(features);\n }\n var ans = this.b, i;\n if (this.options.kernel === 'linear' && this.W) {\n // Use weights, it's faster\n for (i = 0; i < this.W.length; i++) {\n ans += this.W[i] * features[i];\n }\n } else {\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * this.kernel.compute([features], [this.X[i]])[0][0];\n }\n }\n return ans;\n};\n\n\n/**\n * Get a margin using the precomputed kernel. Much faster than normal margin computation\n * @private\n * @param {Number} index - Train data index\n * @param {Array< Array >} kernel - The precomputed kernel\n * @returns {number} Computed margin\n * @private\n */\nSVM.prototype._marginOnePrecomputed = function (index, kernel) {\n var ans = this.b, i;\n for (i = 0; i < this.N; i++) {\n ans += this.alphas[i] * this.Y[i] * kernel[index][i];\n }\n return ans;\n};\n\n\n/**\n * Returns the margin of one or several observations given its features\n * @param {Array >|Array} features - Features from on or several observations.\n * @returns {Number|Array} The computed margin. Is an Array if several observations' features given, or a Number if\n * only one observation's features given\n */\nSVM.prototype.margin = function (features) {\n if (Array.isArray(features)) {\n return features.map(this.marginOne.bind(this));\n } else {\n return this.marginOne(features);\n }\n};\n\n/**\n * Get support vectors indexes of the trained classifier. WARINNG: this method does not work for svm instances\n * created from {@link #SVM.load load} if linear kernel\n * @returns {Array} The indices in the training vector of the support vectors\n */\nSVM.prototype.supportVectors = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot get support vectors, you need to train the SVM first');\n if (this._loaded && this.options.kernel === 'linear') throw new Error('Cannot get support vectors from saved linear model, you need to train the SVM to have them');\n return this._supportVectorIdx;\n};\n\n/**\n * Create a SVM instance from a saved model\n * @param {Object} model - Object such as returned by a trained SVM instance with {@link #SVM#toJSON toJSON}\n * @returns {SVM} Instance of svm classifier\n */\nSVM.load = function (model) {\n this._loaded = true;\n this._trained = false;\n var svm = new SVM(model.options);\n if (model.options.kernel === 'linear') {\n svm.W = model.W.slice();\n svm.D = svm.W.length;\n } else {\n svm.X = model.X.slice();\n svm.Y = model.Y.slice();\n svm.alphas = model.alphas.slice();\n svm.N = svm.X.length;\n svm.D = svm.X[0].length;\n }\n svm.minMax = model.minMax;\n svm.b = model.b;\n svm._loaded = true;\n svm._trained = false;\n return svm;\n};\n\n/**\n * Export the minimal object that enables to reload the model\n * @returns {Object} Model object that can be reused with {@link #SVM.load load}\n */\nSVM.prototype.toJSON = function () {\n if (!this._trained && !this._loaded) throw new Error('Cannot export, you need to train the SVM first');\n var model = {};\n model.options = Object.assign({}, this.options);\n model.b = this.b;\n model.minMax = this.minMax;\n if (model.options.kernel === 'linear') {\n model.W = this.W.slice();\n } else {\n // Exporting non-linear models is heavier\n model.X = this.X.slice();\n model.Y = this.Y.slice();\n model.alphas = this.alphas.slice();\n }\n return model;\n};\n\nSVM.prototype._applyWhitening = function (features) {\n if (!this.minMax) throw new Error('Could not apply whitening');\n var whitened = new Array(features.length);\n for (var j = 0; j < features.length; j++) {\n whitened[j] = (features[j] - this.minMax[j].min) / (this.minMax[j].max - this.minMax[j].min);\n }\n return whitened;\n};\n\nmodule.exports = SVM;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-svm/src/svm.js\n ** module id = 132\n ** module chunks = 0\n **/","'use strict';\n\nmodule.exports = require('./knn');\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-knn/src/index.js\n ** module id = 133\n ** module chunks = 0\n **/","'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 = 134\n ** module chunks = 0\n **/","'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 = 135\n ** module chunks = 0\n **/","'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 = 136\n ** module chunks = 0\n **/","'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 = 137\n ** module chunks = 0\n **/","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 = 138\n ** module chunks = 0\n **/","'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 = 139\n ** module chunks = 0\n **/","'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 = 140\n ** module chunks = 0\n **/","'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 = 141\n ** module chunks = 0\n **/","'use strict';\n\nconst squaredDistance = require('ml-euclidean-distance').squared;\n\n/**\n * Calculates the sum of squared errors\n * @param {Array >} data - the (x,y) points to cluster\n * @param {Array >} centers - the K centers in format (x,y)\n * @param {Array } clusterID - the cluster identifier for each data dot\n * @returns {Number} the sum of squared errors\n */\nfunction computeSSE(data, centers, clusterID) {\n let sse = 0;\n let nData = data.length;\n let c = 0;\n for (let i = 0; i < nData; i++) {\n c = clusterID[i];\n sse += squaredDistance(data[i], centers[c]);\n }\n return sse;\n}\n\n/**\n * Updates the cluster identifier based in the new data\n * @param {Array >} data - the (x,y) points to cluster\n * @param {Array >} centers - the K centers in format (x,y)\n * @returns {Array} the cluster identifier for each data dot\n */\nfunction updateClusterID(data, centers) {\n let nData = data.length;\n let k = centers.length;\n let aux = 0;\n let clusterID = new Array(nData);\n for (let i = 0; i < nData; i++)\n clusterID[i] = 0;\n let d = new Array(nData);\n for (let i = 0; i < nData; i++) {\n d[i] = new Array(k);\n for (let j = 0; j < k; j++) {\n aux = squaredDistance(data[i], centers[j]);\n d[i][j] = new Array(2);\n d[i][j][0] = aux;\n d[i][j][1] = j;\n }\n let min = d[i][0][0];\n let id = 0;\n for (let j = 0; j < k; j++)\n if (d[i][j][0] < min) {\n min = d[i][j][0];\n id = d[i][j][1];\n }\n clusterID[i] = id;\n }\n return clusterID;\n}\n\n/**\n * Update the center values based in the new configurations of the clusters\n * @param {Array >} data - the (x,y) 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)\n */\nfunction updateCenters(data, clusterID, K) {\n let nDim = data[0].length;\n let nData = data.length;\n let centers = new Array(K);\n for (let i = 0; i < K; i++) {\n centers[i] = new Array(nDim);\n for (let j = 0; j < nDim; j++)\n centers[i][j] = 0;\n }\n\n for (let k = 0; k < K; k++) {\n let cluster = [];\n for (let i = 0; i < nData; i++)\n if (clusterID[i] === k)\n cluster.push(data[i]);\n for (let d = 0; d < nDim; d++) {\n let x = [];\n for (let i = 0; i < nData; i++)\n if (clusterID[i] === k)\n x.push(data[i][d]);\n let sum = 0;\n let l = x.length;\n for (let i = 0; i < l; i++)\n sum += x[i];\n centers[k][d] = sum / l;\n }\n }\n return centers;\n}\n\nconst defaultOptions = {\n maxIterations: 100,\n tolerance: 1e-6,\n withIterations: false\n};\n\n/**\n * K-means algorithm\n * @param {Array >} data - the (x,y) points to cluster\n * @param {Array >} centers - the K centers in format (x,y)\n * @param {Object} options - properties\n * @param {Number} options.maxIterations - maximum of iterations allowed\n * @param {Number} options.tolerance - the error tolerance\n * @param {boolean} options.withIterations - store clusters and centroids for each iteration\n * @returns {Object} the cluster identifier for each data dot and centroids\n */\nfunction kmeans(data, centers, options) {\n if (!options) options = defaultOptions;\n let maxIterations = options.maxIterations || defaultOptions.maxIterations;\n let tolerance = options.tolerance || defaultOptions.tolerance;\n let withIterations = options.withIterations || defaultOptions.withIterations;\n\n let nData = data.length;\n if (nData === 0) {\n return [];\n }\n let K = centers.length;\n let clusterID = new Array(nData);\n for (let i = 0; i < nData; i++)\n clusterID[i] = 0;\n if (K >= nData) {\n for (let i = 0; i < nData; i++)\n clusterID[i] = i;\n return clusterID;\n }\n let lastDistance;\n lastDistance = 1e100;\n let curDistance = 0;\n let iterations = [];\n for (let iter = 0; iter < maxIterations; iter++) {\n clusterID = updateClusterID(data, centers);\n centers = updateCenters(data, clusterID, K);\n curDistance = computeSSE(data, centers, clusterID);\n if (withIterations) {\n iterations.push({\n 'clusters': clusterID,\n 'centroids': centers\n });\n }\n\n if ((lastDistance - curDistance < tolerance) || ((lastDistance - curDistance) / lastDistance < tolerance)) {\n if (withIterations) {\n return {\n 'clusters': clusterID,\n 'centroids': centers,\n 'iterations': iterations\n };\n } else {\n return {\n 'clusters': clusterID,\n 'centroids': centers\n };\n }\n }\n lastDistance = curDistance;\n }\n if (withIterations) {\n return {\n 'clusters': clusterID,\n 'centroids': centers,\n 'iterations': iterations\n };\n } else {\n return {\n 'clusters': clusterID,\n 'centroids': centers\n };\n }\n}\n\nmodule.exports = kmeans;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-kmeans/src/kmeans.js\n ** module id = 142\n ** module chunks = 0\n **/","'use strict';\n\nfunction squaredEuclidean(p, q) {\n var d = 0;\n for (var i = 0; i < p.length; i++) {\n d += (p[i] - q[i]) * (p[i] - q[i]);\n }\n return d;\n}\n\nfunction euclidean(p, q) {\n return Math.sqrt(squaredEuclidean(p, q));\n}\n\nmodule.exports = euclidean;\neuclidean.squared = squaredEuclidean;\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-euclidean-distance/euclidean.js\n ** module id = 143\n ** module chunks = 0\n **/","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 = 144\n ** module chunks = 0\n **/","'use strict';\n\nvar euclidean = require('ml-distance-euclidean');\nvar ClusterLeaf = require('./ClusterLeaf');\nvar Cluster = require('./Cluster');\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction simpleLink(cluster1, cluster2, disFun) {\n var m = 10e100;\n for (var i = 0; i < cluster1.length; i++)\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.min(d,m);\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction completeLink(cluster1, cluster2, disFun) {\n var m = -1;\n for (var i = 0; i < cluster1.length; i++)\n for (var j = 0; j < cluster2.length; j++) {\n var d = disFun[cluster1[i]][ cluster2[j]];\n m = Math.max(d,m);\n }\n return m;\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction averageLink(cluster1, cluster2, disFun) {\n var m = 0;\n for (var i = 0; i < cluster1.length; i++)\n for (var j = 0; j < cluster2.length; j++)\n m += disFun[cluster1[i]][ cluster2[j]];\n return m / (cluster1.length * cluster2.length);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {*}\n */\nfunction centroidLink(cluster1, cluster2, disFun) {\n var m = -1;\n var dist = new Array(cluster1.length*cluster2.length);\n for (var i = 0; i < cluster1.length; i++)\n for (var j = 0; j < cluster2.length; j++) {\n dist[i*cluster1.length+j]=(disFun[cluster1[i]][ cluster2[j]]);\n }\n return median(dist);\n}\n\n/**\n * @private\n * @param cluster1\n * @param cluster2\n * @param disFun\n * @returns {number}\n */\nfunction wardLink(cluster1, cluster2, disFun) {\n return centroidLink(cluster1, cluster2, disFun)\n *cluster1.length*cluster2.length / (cluster1.length+cluster2.length);\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\nfunction median(values, alreadySorted) {\n if (alreadySorted === undefined) alreadySorted = false;\n if (!alreadySorted) {\n values = [].concat(values).sort(compareNumbers);\n }\n var l = values.length;\n var half = Math.floor(l / 2);\n if (l % 2 === 0) {\n return (values[half - 1] + values[half]) * 0.5;\n } else {\n return values[half];\n }\n}\n\nvar defaultOptions = {\n disFunc: euclidean,\n kind: 'single',\n isDistanceMatrix:false\n\n};\n\n/**\n * Continuously merge nodes that have the least dissimilarity\n * @param {Array >} distance - Array of points to be clustered\n * @param {json} options\n * @option isDistanceMatrix: Is the input a distance matrix?\n * @constructor\n */\nfunction agnes(data, options) {\n options = Object.assign({}, defaultOptions, options);\n var len = data.length;\n\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 = 145\n ** module chunks = 0\n **/","'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 = 146\n ** module chunks = 0\n **/","'use strict';\n\nconst Heap = require('heap');\n\nfunction Cluster () {\n this.children = [];\n this.distance = -1;\n this.index = [];\n}\n\n/**\n * Creates an array of values where maximum distance smaller than the threshold\n * @param {number} threshold\n * @return {Array }\n */\nCluster.prototype.cut = function (threshold) {\n if (threshold < 0) throw new RangeError('Threshold too small');\n var root = new Cluster();\n root.children = this.children;\n root.distance = this.distance;\n root.index = this.index;\n var list = [root];\n var ans = [];\n while (list.length > 0) {\n var aux = list.shift();\n if (threshold >= aux.distance)\n ans.push(aux);\n else\n list = list.concat(aux.children);\n }\n 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 = 147\n ** module chunks = 0\n **/","module.exports = require('./lib/heap');\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/heap/index.js\n ** module id = 148\n ** module chunks = 0\n **/","// Generated by CoffeeScript 1.8.0\n(function() {\n var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;\n\n floor = Math.floor, min = Math.min;\n\n\n /*\n Default comparison function to be used\n */\n\n defaultCmp = function(x, y) {\n if (x < y) {\n return -1;\n }\n if (x > y) {\n return 1;\n }\n return 0;\n };\n\n\n /*\n Insert item x in list a, and keep it sorted assuming a is sorted.\n \n If x is already in a, insert it to the right of the rightmost x.\n \n Optional args lo (default 0) and hi (default a.length) bound the slice\n of a to be searched.\n */\n\n insort = function(a, x, lo, hi, cmp) {\n var mid;\n if (lo == null) {\n lo = 0;\n }\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (lo < 0) {\n throw new Error('lo must be non-negative');\n }\n if (hi == null) {\n hi = a.length;\n }\n while (lo < hi) {\n mid = floor((lo + hi) / 2);\n if (cmp(x, a[mid]) < 0) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);\n };\n\n\n /*\n Push item onto heap, maintaining the heap invariant.\n */\n\n heappush = function(array, item, cmp) {\n if (cmp == null) {\n cmp = defaultCmp;\n }\n array.push(item);\n return _siftdown(array, 0, array.length - 1, cmp);\n };\n\n\n /*\n Pop the smallest item off the heap, maintaining the heap invariant.\n */\n\n heappop = function(array, cmp) {\n var lastelt, returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n lastelt = array.pop();\n if (array.length) {\n returnitem = array[0];\n array[0] = lastelt;\n _siftup(array, 0, cmp);\n } else {\n returnitem = lastelt;\n }\n return returnitem;\n };\n\n\n /*\n Pop and return the current smallest value, and add the new item.\n \n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed size heap. Note that the value\n returned may be larger than item! That constrains reasonable use of\n this routine unless written as part of a conditional replacement:\n if item > array[0]\n item = heapreplace(array, item)\n */\n\n heapreplace = function(array, item, cmp) {\n var returnitem;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n returnitem = array[0];\n array[0] = item;\n _siftup(array, 0, cmp);\n return returnitem;\n };\n\n\n /*\n Fast version of a heappush followed by a heappop.\n */\n\n heappushpop = function(array, item, cmp) {\n var _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (array.length && cmp(array[0], item) < 0) {\n _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];\n _siftup(array, 0, cmp);\n }\n return item;\n };\n\n\n /*\n Transform list into a heap, in-place, in O(array.length) time.\n */\n\n heapify = function(array, cmp) {\n var i, _i, _j, _len, _ref, _ref1, _results, _results1;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n _ref1 = (function() {\n _results1 = [];\n for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }\n return _results1;\n }).apply(this).reverse();\n _results = [];\n for (_i = 0, _len = _ref1.length; _i < _len; _i++) {\n i = _ref1[_i];\n _results.push(_siftup(array, i, cmp));\n }\n return _results;\n };\n\n\n /*\n Update the position of the given item in the heap.\n This function should be called every time the item is being modified.\n */\n\n updateItem = function(array, item, cmp) {\n var pos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n pos = array.indexOf(item);\n if (pos === -1) {\n return;\n }\n _siftdown(array, 0, pos, cmp);\n return _siftup(array, pos, cmp);\n };\n\n\n /*\n Find the n largest elements in a dataset.\n */\n\n nlargest = function(array, n, cmp) {\n var elem, result, _i, _len, _ref;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n result = array.slice(0, n);\n if (!result.length) {\n return result;\n }\n heapify(result, cmp);\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n heappushpop(result, elem, cmp);\n }\n return result.sort(cmp).reverse();\n };\n\n\n /*\n Find the n smallest elements in a dataset.\n */\n\n nsmallest = function(array, n, cmp) {\n var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n if (n * 10 <= array.length) {\n result = array.slice(0, n).sort(cmp);\n if (!result.length) {\n return result;\n }\n los = result[result.length - 1];\n _ref = array.slice(n);\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n elem = _ref[_i];\n if (cmp(elem, los) < 0) {\n insort(result, elem, 0, null, cmp);\n result.pop();\n los = result[result.length - 1];\n }\n }\n return result;\n }\n heapify(array, cmp);\n _results = [];\n for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {\n _results.push(heappop(array, cmp));\n }\n return _results;\n };\n\n _siftdown = function(array, startpos, pos, cmp) {\n var newitem, parent, parentpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n newitem = array[pos];\n while (pos > startpos) {\n parentpos = (pos - 1) >> 1;\n parent = array[parentpos];\n if (cmp(newitem, parent) < 0) {\n array[pos] = parent;\n pos = parentpos;\n continue;\n }\n break;\n }\n return array[pos] = newitem;\n };\n\n _siftup = function(array, pos, cmp) {\n var childpos, endpos, newitem, rightpos, startpos;\n if (cmp == null) {\n cmp = defaultCmp;\n }\n endpos = array.length;\n startpos = pos;\n newitem = array[pos];\n childpos = 2 * pos + 1;\n while (childpos < endpos) {\n rightpos = childpos + 1;\n if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {\n childpos = rightpos;\n }\n array[pos] = array[childpos];\n pos = childpos;\n childpos = 2 * pos + 1;\n }\n array[pos] = newitem;\n return _siftdown(array, startpos, pos, cmp);\n };\n\n Heap = (function() {\n Heap.push = heappush;\n\n Heap.pop = heappop;\n\n Heap.replace = heapreplace;\n\n Heap.pushpop = heappushpop;\n\n Heap.heapify = heapify;\n\n Heap.updateItem = updateItem;\n\n Heap.nlargest = nlargest;\n\n Heap.nsmallest = nsmallest;\n\n function Heap(cmp) {\n this.cmp = cmp != null ? cmp : defaultCmp;\n this.nodes = [];\n }\n\n Heap.prototype.push = function(x) {\n return heappush(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pop = function() {\n return heappop(this.nodes, this.cmp);\n };\n\n Heap.prototype.peek = function() {\n return this.nodes[0];\n };\n\n Heap.prototype.contains = function(x) {\n return this.nodes.indexOf(x) !== -1;\n };\n\n Heap.prototype.replace = function(x) {\n return heapreplace(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.pushpop = function(x) {\n return heappushpop(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.heapify = function() {\n return heapify(this.nodes, this.cmp);\n };\n\n Heap.prototype.updateItem = function(x) {\n return updateItem(this.nodes, x, this.cmp);\n };\n\n Heap.prototype.clear = function() {\n return this.nodes = [];\n };\n\n Heap.prototype.empty = function() {\n return this.nodes.length === 0;\n };\n\n Heap.prototype.size = function() {\n return this.nodes.length;\n };\n\n Heap.prototype.clone = function() {\n var heap;\n heap = new Heap();\n heap.nodes = this.nodes.slice(0);\n return heap;\n };\n\n Heap.prototype.toArray = function() {\n return this.nodes.slice(0);\n };\n\n Heap.prototype.insert = Heap.prototype.push;\n\n Heap.prototype.top = Heap.prototype.peek;\n\n Heap.prototype.front = Heap.prototype.peek;\n\n Heap.prototype.has = Heap.prototype.contains;\n\n Heap.prototype.copy = Heap.prototype.clone;\n\n return Heap;\n\n })();\n\n (function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n return define([], factory);\n } else if (typeof exports === 'object') {\n return module.exports = factory();\n } else {\n return root.Heap = factory();\n }\n })(this, function() {\n return Heap;\n });\n\n}).call(this);\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/heap/lib/heap.js\n ** module id = 149\n ** module chunks = 0\n **/","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar 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 = 150\n ** module chunks = 0\n **/","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\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 = 151\n ** module chunks = 0\n **/","module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/util/support/isBufferBrowser.js\n ** module id = 152\n ** module chunks = 0\n **/","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/inherits/inherits_browser.js\n ** module id = 153\n ** module chunks = 0\n **/","'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 = 154\n ** module chunks = 0\n **/","'use strict';\n\nvar NodeSquare = require('./node-square'),\n NodeHexagonal = require('./node-hexagonal');\n\nvar defaultOptions = {\n fields: 3,\n randomizer: Math.random,\n distance: squareEuclidean,\n iterations: 10,\n learningRate: 0.1,\n gridType: 'rect',\n torus: true,\n method: 'random'\n};\n\nfunction SOM(x, y, options, reload) {\n\n this.x = x;\n this.y = y;\n\n options = options || {};\n this.options = {};\n for (var i in defaultOptions) {\n if (options.hasOwnProperty(i)) {\n this.options[i] = options[i];\n } else {\n this.options[i] = defaultOptions[i];\n }\n }\n\n if (typeof this.options.fields === 'number') {\n this.numWeights = this.options.fields;\n } else if (Array.isArray(this.options.fields)) {\n this.numWeights = this.options.fields.length;\n var converters = getConverters(this.options.fields);\n this.extractor = converters.extractor;\n this.creator = converters.creator;\n } else {\n throw new Error('Invalid fields definition');\n }\n\n if (this.options.gridType === 'rect') {\n this.nodeType = NodeSquare;\n this.gridDim = {\n x: x,\n y: y\n };\n } else {\n this.nodeType = NodeHexagonal;\n var hx = this.x - Math.floor(this.y / 2);\n this.gridDim = {\n x: hx,\n y: this.y,\n z: -(0 - hx - this.y)\n };\n }\n\n this.torus = this.options.torus;\n this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance';\n\n this.distance = this.options.distance;\n\n this.maxDistance = getMaxDistance(this.distance, this.numWeights);\n\n if (reload === true) { // For model loading\n this.done = true;\n return;\n }\n if (!(x > 0 && y > 0)) {\n throw new Error('x and y must be positive');\n }\n\n this.times = {\n findBMU: 0,\n adjust: 0\n };\n\n this.randomizer = this.options.randomizer;\n\n this.iterationCount = 0;\n this.iterations = this.options.iterations;\n\n this.startLearningRate = this.learningRate = this.options.learningRate;\n\n this.mapRadius = Math.floor(Math.max(x, y) / 2);\n\n this.algorithmMethod = this.options.method;\n\n this._initNodes();\n\n this.done = false;\n}\n\nSOM.load = function loadModel(model, distance) {\n if (model.name === 'SOM') {\n var x = model.data.length,\n y = model.data[0].length;\n if (distance) {\n model.options.distance = distance;\n } else if (model.options.distance) {\n model.options.distance = eval('(' + model.options.distance + ')');\n }\n var som = new SOM(x, y, model.options, true);\n som.nodes = new Array(x);\n for (var i = 0; i < x; i++) {\n som.nodes[i] = new Array(y);\n for (var j = 0; j < y; j++) {\n som.nodes[i][j] = new som.nodeType(i, j, model.data[i][j], som);\n }\n }\n return som;\n } else {\n throw new Error('expecting a SOM model');\n }\n};\n\nSOM.prototype.export = function exportModel(includeDistance) {\n if (!this.done) {\n throw new Error('model is not ready yet');\n }\n var model = {\n name: 'SOM'\n };\n model.options = {\n fields: this.options.fields,\n gridType: this.options.gridType,\n torus: this.options.torus\n };\n model.data = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n model.data[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n model.data[i][j] = this.nodes[i][j].weights;\n }\n }\n if (includeDistance) {\n model.options.distance = this.distance.toString();\n }\n return model;\n};\n\nSOM.prototype._initNodes = function initNodes() {\n var now = Date.now(),\n i, j, k;\n this.nodes = new Array(this.x);\n for (i = 0; i < this.x; i++) {\n this.nodes[i] = new Array(this.y);\n for (j = 0; j < this.y; j++) {\n var weights = new Array(this.numWeights);\n for (k = 0; k < this.numWeights; k++) {\n weights[k] = this.randomizer();\n }\n this.nodes[i][j] = new this.nodeType(i, j, weights, this);\n }\n }\n this.times.initNodes = Date.now() - now;\n};\n\nSOM.prototype.setTraining = function setTraining(trainingSet) {\n if (this.trainingSet) {\n throw new Error('training set has already been set');\n }\n var now = Date.now();\n var convertedSet = trainingSet;\n var i, l = trainingSet.length;\n if (this.extractor) {\n convertedSet = new Array(l);\n for (i = 0; i < l; i++) {\n convertedSet[i] = this.extractor(trainingSet[i]);\n }\n }\n this.numIterations = this.iterations * l;\n\n if (this.algorithmMethod === 'random') {\n this.timeConstant = this.numIterations / Math.log(this.mapRadius);\n } else {\n this.timeConstant = l / Math.log(this.mapRadius);\n }\n this.trainingSet = convertedSet;\n this.times.setTraining = Date.now() - now;\n};\n\nSOM.prototype.trainOne = function trainOne() {\n if (this.done) {\n\n return false;\n\n } else if (this.numIterations-- > 0) {\n\n var neighbourhoodRadius,\n trainingValue,\n trainingSetFactor;\n\n if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step\n neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant);\n trainingValue = getRandomValue(this.trainingSet, this.randomizer);\n this._adjust(trainingValue, neighbourhoodRadius);\n this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations);\n } else { // Get next input vector\n trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length);\n neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant);\n trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length];\n this._adjust(trainingValue, neighbourhoodRadius);\n if (((this.iterationCount + 1) % this.trainingSet.length) === 0) {\n this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length));\n }\n }\n\n this.iterationCount++;\n\n return true;\n\n } else {\n\n this.done = true;\n return false;\n\n }\n};\n\nSOM.prototype._adjust = function adjust(trainingValue, neighbourhoodRadius) {\n var now = Date.now(),\n x, y, dist, influence;\n\n var bmu = this._findBestMatchingUnit(trainingValue);\n\n var now2 = Date.now();\n this.times.findBMU += now2 - now;\n\n var radiusLimit = Math.floor(neighbourhoodRadius);\n var xMin = bmu.x - radiusLimit,\n xMax = bmu.x + radiusLimit,\n yMin = bmu.y - radiusLimit,\n yMax = bmu.y + radiusLimit;\n\n for (x = xMin; x <= xMax; x++) {\n var theX = x;\n if (x < 0) {\n theX += this.x;\n } else if (x >= this.x) {\n theX -= this.x;\n }\n for (y = yMin; y <= yMax; y++) {\n var theY = y;\n if (y < 0) {\n theY += this.y;\n } else if (y >= this.y) {\n theY -= this.y;\n }\n\n dist = bmu[this.distanceMethod](this.nodes[theX][theY]);\n\n if (dist < neighbourhoodRadius) {\n influence = Math.exp(-dist / (2 * neighbourhoodRadius));\n this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence);\n }\n\n }\n }\n\n this.times.adjust += (Date.now() - now2);\n\n};\n\nSOM.prototype.train = function train(trainingSet) {\n if (!this.done) {\n this.setTraining(trainingSet);\n while (this.trainOne()) {\n }\n }\n};\n\nSOM.prototype.getConvertedNodes = function getConvertedNodes() {\n var result = new Array(this.x);\n for (var i = 0; i < this.x; i++) {\n result[i] = new Array(this.y);\n for (var j = 0; j < this.y; j++) {\n var node = this.nodes[i][j];\n result[i][j] = this.creator ? this.creator(node.weights) : node.weights;\n }\n }\n return result;\n};\n\nSOM.prototype._findBestMatchingUnit = function findBestMatchingUnit(candidate) {\n\n var bmu,\n lowest = Infinity,\n dist;\n\n for (var i = 0; i < this.x; i++) {\n for (var j = 0; j < this.y; j++) {\n dist = this.distance(this.nodes[i][j].weights, candidate);\n if (dist < lowest) {\n lowest = dist;\n bmu = this.nodes[i][j];\n }\n }\n }\n\n return bmu;\n\n};\n\nSOM.prototype.predict = function predict(data, computePosition) {\n if (typeof data === 'boolean') {\n computePosition = data;\n data = null;\n }\n if (!data) {\n data = this.trainingSet;\n }\n if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset\n var self = this;\n return data.map(function (element) {\n return self._predict(element, computePosition);\n });\n } else { // predict a single element\n return this._predict(data, computePosition);\n }\n};\n\nSOM.prototype._predict = function _predict(element, computePosition) {\n if (!Array.isArray(element)) {\n element = this.extractor(element);\n }\n var bmu = this._findBestMatchingUnit(element);\n var result = [bmu.x, bmu.y];\n if (computePosition) {\n result[2] = bmu.getPosition(element);\n }\n return result;\n};\n\n// As seen in http://www.scholarpedia.org/article/Kohonen_network\nSOM.prototype.getQuantizationError = function getQuantizationError() {\n var fit = this.getFit(),\n l = fit.length,\n sum = 0;\n for (var i = 0; i < l; i++) {\n sum += fit[i];\n }\n return sum / l;\n};\n\nSOM.prototype.getFit = function getFit(dataset) {\n if (!dataset) {\n dataset = this.trainingSet;\n }\n var l = dataset.length,\n bmu,\n result = new Array(l);\n for (var i = 0; i < l; i++) {\n bmu = this._findBestMatchingUnit(dataset[i]);\n result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights));\n }\n return result;\n};\n\nfunction getConverters(fields) {\n var l = fields.length,\n normalizers = new Array(l),\n denormalizers = new Array(l);\n for (var i = 0; i < l; i++) {\n normalizers[i] = getNormalizer(fields[i].range);\n denormalizers[i] = getDenormalizer(fields[i].range);\n }\n return {\n extractor: function extractor(value) {\n var result = new Array(l);\n for (var i = 0; i < l; i++) {\n result[i] = normalizers[i](value[fields[i].name]);\n }\n return result;\n },\n creator: function creator(value) {\n var result = {};\n for (var i = 0; i < l; i++) {\n result[fields[i].name] = denormalizers[i](value[i]);\n }\n return result;\n }\n };\n}\n\nfunction getNormalizer(minMax) {\n return function normalizer(value) {\n return (value - minMax[0]) / (minMax[1] - minMax[0]);\n };\n}\n\nfunction getDenormalizer(minMax) {\n return function denormalizer(value) {\n return (minMax[0] + value * (minMax[1] - minMax[0]));\n };\n}\n\nfunction squareEuclidean(a, b) {\n var d = 0;\n for (var i = 0, ii = a.length; i < ii; i++) {\n d += (a[i] - b[i]) * (a[i] - b[i]);\n }\n return d;\n}\n\nfunction getRandomValue(arr, randomizer) {\n return arr[Math.floor(randomizer() * arr.length)];\n}\n\nfunction getMaxDistance(distance, numWeights) {\n var zero = new Array(numWeights),\n one = new Array(numWeights);\n for (var i = 0; i < numWeights; i++) {\n zero[i] = 0;\n one[i] = 1;\n }\n return distance(zero, one);\n}\n\nmodule.exports = SOM;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-som/src/index.js\n ** module id = 155\n ** module chunks = 0\n **/","function NodeSquare(x, y, weights, som) {\n this.x = x;\n this.y = y;\n this.weights = weights;\n this.som = som;\n this.neighbors = {};\n}\n\nNodeSquare.prototype.adjustWeights = function adjustWeights(target, learningRate, influence) {\n for (var i = 0, ii = this.weights.length; i < ii; i++) {\n this.weights[i] += learningRate * influence * (target[i] - this.weights[i]);\n }\n};\n\nNodeSquare.prototype.getDistance = function getDistance(otherNode) {\n return Math.max(Math.abs(this.x - otherNode.x), Math.abs(this.y - otherNode.y));\n};\n\nNodeSquare.prototype.getDistanceTorus = function getDistanceTorus(otherNode) {\n var distX = Math.abs(this.x - otherNode.x),\n distY = Math.abs(this.y - otherNode.y);\n return Math.max(Math.min(distX, this.som.gridDim.x - distX), Math.min(distY, this.som.gridDim.y - distY));\n};\n\nNodeSquare.prototype.getNeighbors = function getNeighbors(xy) {\n if (!this.neighbors[xy]) {\n this.neighbors[xy] = new Array(2);\n\n // left or bottom neighbor\n var v;\n if (this[xy] > 0) {\n v = this[xy] - 1;\n } else if (this.som.torus) {\n v = this.som.gridDim[xy] - 1\n }\n if (typeof v !== 'undefined') {\n var x, y;\n if (xy === 'x') {\n x = v;\n y = this.y;\n } else {\n x = this.x;\n y = v;\n }\n this.neighbors[xy][0] = this.som.nodes[x][y];\n }\n\n // top or right neighbor\n var w;\n if (this[xy] < (this.som.gridDim[xy] - 1)) {\n w = this[xy] + 1;\n } else if (this.som.torus) {\n w = 0;\n }\n if (typeof w !== 'undefined') {\n if (xy === 'x') {\n x = w;\n y = this.y;\n } else {\n x = this.x;\n y = w;\n }\n this.neighbors[xy][1] = this.som.nodes[x][y];\n }\n }\n return this.neighbors[xy];\n};\n\nNodeSquare.prototype.getPos = function getPos(xy, element) {\n var neighbors = this.getNeighbors(xy),\n distance = this.som.distance,\n bestNeighbor,\n direction;\n if(neighbors[0]) {\n if (neighbors[1]) {\n var dist1 = distance(element, neighbors[0].weights),\n dist2 = distance(element, neighbors[1].weights);\n if(dist1 < dist2) {\n bestNeighbor = neighbors[0];\n direction = -1;\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n } else {\n bestNeighbor = neighbors[0];\n direction = -1;\n }\n } else {\n bestNeighbor = neighbors[1];\n direction = 1;\n }\n var simA = 1 - distance(element, this.weights),\n simB = 1 - distance(element, bestNeighbor.weights);\n var factor = ((simA - simB) / (2 - simA - simB));\n return 0.5 + 0.5 * factor * direction;\n};\n\nNodeSquare.prototype.getPosition = function getPosition(element) {\n return [\n this.getPos('x', element),\n this.getPos('y', element)\n ];\n};\n\nmodule.exports = NodeSquare;\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-som/src/node-square.js\n ** module id = 156\n ** module chunks = 0\n **/","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 = 157\n ** module chunks = 0\n **/","module.exports = require('./feedforwardNeuralNetwork');\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-fnn/src/index.js\n ** module id = 158\n ** module chunks = 0\n **/","\"use strict\";\n\nvar Layer = require(\"./layer\");\nvar Matrix = require(\"ml-matrix\");\n\nclass FeedforwardNeuralNetwork {\n /**\n * Constructor for the FNN (Feedforward Neural Networks) that takes an Array of Numbers,\n * those numbers corresponds to the size of each layer in the FNN, the first and the last number of the array corresponds to the input and the\n * output layer respectively.\n *\n * @constructor\n */\n constructor(X, Y) {\n if (X === true) {\n const model = Y;\n this.layers = model.layers;\n this.inputSize = model.inputSize;\n this.outputSize = model.outputSize;\n } else {\n if (X.length !== Y.length)\n throw new RangeError(\"X and Y must have the same size.\");\n this.X = X;\n this.Y = Y;\n this.inputSize = X[0].length;\n this.outputSize = Y[0].length;\n }\n }\n\n /**\n * Build the Neural Network with an array that represent each hidden layer size.\n *\n * @param {Array} layersSize - Array of sizes of each layer.\n */\n buildNetwork(layersSize) {\n layersSize.push(this.outputSize);\n\n this.layers = new Array(layersSize.length);\n\n for (var i = 0; i < layersSize.length; ++i) {\n var inSize = (i == 0) ? this.inputSize : layersSize[i - 1];\n this.layers[i] = new Layer(inSize, layersSize[i]);\n }\n\n this.layers[this.layers.length - 1].isSigmoid = false;\n }\n\n /**\n * Function that applies a forward propagation over the Neural Network\n * with one case of the dataset.\n * @param {Array} input - case of the dataset.\n * @returns {Array} result of the forward propagation.\n */\n forwardNN(input) {\n var results = input.slice();\n\n for (var i = 0; i < this.layers.length; ++i) {\n results = this.layers[i].forward(results);\n }\n\n return results;\n }\n\n /**\n * Function that makes one iteration (epoch) over the Neural Network with one element\n * of the dataset with corresponding prediction; the other two arguments are the\n * learning rate and the momentum that is the regularization term for the parameters\n * of each perceptron in the Neural Network.\n * @param {Array} data - Element of the dataset.\n * @param {Array} prediction - Prediction over the data object.\n * @param {Number} learningRate\n * @param momentum - the regularization term.\n */\n iteration(data, prediction, learningRate, momentum) {\n var forwardResult = this.forwardNN(data);\n var error = new Array(forwardResult.length);\n\n if (typeof(prediction) === 'number')\n prediction = [prediction];\n\n for (var i = 0; i < error.length; i++) {\n error[i] = prediction[i] - forwardResult[i];\n }\n\n var lengthLayers = this.layers.length;\n\n for (i = 0; i < lengthLayers; ++i) {\n error = this.layers[lengthLayers - 1 - i].train(error, learningRate, momentum);\n }\n }\n\n /**\n * Method that train the neural network with a given training set with corresponding\n * predictions. The options argument has an array of the number of perceptrons that we want in each hidden layer, the\n * number of iterations (default 50) that we want to perform, the learning rate and the momentum that is the\n * regularization term (default 0.1 for both) for the parameters of each perceptron in the Neural Network.\n *\n * options:\n * * hiddenLayers - Array of number with each hidden layer size.\n * * iterations - Number\n * * learningRate - Number\n * * momentum - Number\n *\n * @param {object} options\n */\n train(options) {\n if (options === undefined) options = {};\n\n const trainingSet = this.X;\n const predictions = this.Y;\n\n var hiddenLayers = options.hiddenLayers === undefined ? [10] : options.hiddenLayers;\n var iterations = options.iterations === undefined ? 50 : options.iterations;\n var learningRate = options.learningRate === undefined ? 0.1 : options.learningRate;\n var momentum = options.momentum === undefined ? 0.1 : options.momentum;\n\n this.buildNetwork(hiddenLayers);\n\n for (var i = 0; i < iterations; ++i) {\n for (var j = 0; j < predictions.length; ++j) {\n var index = randomIntegerFromInterval(0, predictions.length - 1);\n this.iteration(trainingSet[index], predictions[index], learningRate, momentum);\n }\n }\n }\n\n /**\n * Function that with a dataset, gives all the predictions for this dataset.\n * @param {Matrix} dataset.\n * @returns {Array} predictions\n */\n predict(dataset) {\n if (dataset[0].length !== this.inputSize)\n throw new RangeError(\"The dataset columns must have the same size of the \" +\n \"input layer\");\n var result = new Array(dataset.length);\n for (var i = 0; i < dataset.length; i++) {\n result[i] = this.forwardNN(dataset[i]);\n }\n\n result = new Matrix(result);\n //return result.columns === 1 ? result.getColumn(0) : result;\n return result;\n \n }\n\n toJSON() {\n return {\n name: 'FNN',\n layers: this.layers,\n inputSize: this.inputSize,\n outputSize: this.outputSize\n };\n }\n\n static load(model) {\n if (model.name !== 'FNN')\n throw new RangeError('Invalid model: ' + model.name);\n return new FeedforwardNeuralNetwork(true, model);\n }\n}\n\nmodule.exports = FeedforwardNeuralNetwork;\n\n/**\n * Function that returns a random number between two numbers (inclusive)\n * @param {number} min - lower bound\n * @param {number} max - upper bound.\n * @returns {number} random number\n */\nfunction randomIntegerFromInterval(min, max) {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-fnn/src/feedforwardNeuralNetwork.js\n ** module id = 159\n ** module chunks = 0\n **/","\"use strict\";\n\nvar Matrix = require(\"ml-matrix\");\n\nclass Layer {\n /**\n * Constructor that creates a layer for the neural network given the number of inputs\n * and outputs.\n * @param inputSize\n * @param outputSize\n * @constructor\n */\n constructor(inputSize, outputSize) {\n this.output = Matrix.zeros(1, outputSize).getRow(0);\n this.input = Matrix.zeros(1, inputSize + 1).getRow(0); //+1 for bias term\n this.deltaWeights = Matrix.zeros(1, (1 + inputSize) * outputSize).getRow(0);\n this.weights = randomInitializeWeights(this.deltaWeights.length, inputSize, outputSize);\n this.isSigmoid = true;\n }\n\n /**\n * Function that performs the forward propagation for the current layer\n * @param {Array} input - output from the previous layer.\n * @returns {Array} output - output for the next layer.\n */\n forward(input) {\n this.input = input.slice();\n this.input.push(1); // bias\n var offs = 0; // offset used to get the current weights in the current perceptron\n this.output = Matrix.zeros(1, this.output.length).getRow(0);\n\n for (var i = 0; i < this.output.length; ++i) {\n for (var j = 0; j < this.input.length; ++j) {\n this.output[i] += this.weights[offs + j] * this.input[j];\n }\n if (this.isSigmoid)\n this.output[i] = sigmoid(this.output[i]);\n\n offs += this.input.length;\n }\n\n return this.output.slice();\n }\n\n /**\n * Function that performs the backpropagation algorithm for the current layer.\n * @param {Array} error - errors from the previous layer.\n * @param {Number} learningRate - Learning rate for the actual layer.\n * @param {Number} momentum - The regularizarion term.\n * @returns {Array} the error for the next layer.\n */\n train(error, learningRate, momentum) {\n var offs = 0;\n var nextError = Matrix.zeros(1, this.input.length).getRow(0);//new Array(this.input.length);\n\n for (var i = 0; i < this.output.length; ++i) {\n var delta = error[i];\n\n if (this.isSigmoid)\n delta *= sigmoidGradient(this.output[i]);\n\n for (var j = 0; j < this.input.length; ++j) {\n var index = offs + j;\n nextError[j] += this.weights[index] * delta;\n\n var deltaWeight = this.input[j] * delta * learningRate;\n this.weights[index] += this.deltaWeights[index] * momentum + deltaWeight;\n this.deltaWeights[index] = deltaWeight;\n }\n\n offs += this.input.length;\n }\n\n return nextError;\n }\n}\n\nmodule.exports = Layer;\n\n/**\n * Function that create a random array of numbers between value depending\n * on the input and output size given the following formula:\n *\n * sqrt(6) / sqrt(l_in + l_out);\n *\n * Taken from the coursera course of machine learning from Andrew Ng,\n * Exercise 4, Page 7 of the exercise PDF.\n *\n * @param numberOfWeights - size of the array.\n * @param inputSize - number of input of the current layer\n * @param outputSize - number of output of the current layer\n * @returns {Array} random array of numbers.\n */\nfunction randomInitializeWeights(numberOfWeights, inputSize, outputSize) {\n var epsilon = 2.449489742783 / Math.sqrt(inputSize + outputSize);\n return Matrix.rand(1, numberOfWeights).mul(2 * epsilon).sub(epsilon).getRow(0);\n}\n\n/**\n * Function that calculates the sigmoid (logistic) function.\n * @param value\n * @returns {number}\n */\nfunction sigmoid(value) {\n return 1.0 / (1 + Math.exp(-value));\n}\n\n/**\n * Function that calculates the derivate of the sigmoid function.\n * @param value\n * @returns {number}\n */\nfunction sigmoidGradient(value) {\n return value * (1 - value);\n}\n\n\n\n/*****************\n ** WEBPACK FOOTER\n ** ./~/ml-fnn/src/layer.js\n ** module id = 160\n ** module chunks = 0\n **/"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///ml/webpack/universalModuleDefinition","webpack:///ml/webpack/bootstrap 61fd2eb3be5b6e4c774d","webpack:///ml/./~/ml-matrix/src/index.js","webpack:///ml/./~/ml-distance-euclidean/euclidean.js","webpack:///ml/./~/ml-stat/index.js","webpack:///ml/./~/ml-matrix/src/matrix.js","webpack:///ml/./~/ml-regression/src/regression/base-regression.js","webpack:///ml/./~/ml-matrix/src/views/base.js","webpack:///ml/./~/ml-regression/src/regression/util.js","webpack:///ml/./~/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-matrix/src/dc/util.js","webpack:///ml/./~/ml-pls/src/utils.js","webpack:///ml/./~/ml-regression/src/regression/simple-linear-regression.js","webpack:///ml/./~/ml-stat/array.js","webpack:///ml/./~/binary-search/index.js","webpack:///ml/./~/ml-array-utils/src/index.js","webpack:///ml/./~/ml-curve-fitting/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-curve-fitting/src/algebra.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/activationFunctions.js","webpack:///ml/./~/ml-fnn/src/utils.js","webpack:///ml/./~/ml-hclust/src/ClusterLeaf.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-naivebayes/src/naiveBayes.js","webpack:///ml/./~/ml-regression/src/regression/polynomial-regression.js","webpack:///ml/./~/ml-savitzky-golay-generalized/~/ml-stat/array.js","webpack:///ml/./~/ml-som/src/node-square.js","webpack:///ml/./~/ml-bit-array/src/index.js","webpack:///ml/./~/ml-cross-validation/src/crossValidation.js","webpack:///ml/./~/ml-distance-matrix/src/index.js","webpack:///ml/./~/ml-fnn/src/FeedForwardNeuralNetwork.js","webpack:///ml/./~/ml-hclust/src/index.js","webpack:///ml/./~/ml-kmeans/src/kmeans.js","webpack:///ml/./~/ml-knn/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-performance/src/index.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/./~/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-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/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-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/dc/svd.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/src/regression/exp-regression.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/power-regression.js","webpack:///ml/./~/ml-regression/src/regression/theil-sen-regression.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","webpack:///ml/./src/index.js"],"names":[],"mappings":"AAAA,cACA,2BACA,uCACA,sCACA,cACA,GACA,oCAEA,SACA,GAAC,mBACD,kBCTA,cAMA,MACA,eAGA,mBACA,GACA,EACA,KAIA,mDAGA,KAGA,OACA,OAIA,IAzBA,iBA4BA,MAGA,iBAA2C,OAAc,EAGzD,qBACA,OACA,8BACA,CACA,gBACA,kBAGA,GAGA,iBACA,YACA,qBAA2B,UAA0B,UACrD,YAAiC,OAAe,EAChD,mBACA,GACA,CAGA,mBAAsD,+CAA+D,EAGrH,MAGA,gCChEA,aAEA,sBACA,0DCHA,aAEA,eACA,WACA,KAAmB,OAAc,OACjC,+BAEA,WACA,GAEA,eACA,sBACA,IAEA,YACA,6BCfA,aAEA,cACA,iCCHA,aAEA,OACA,QACA,WAEA,wBACA,iBACA,IACA,6BACA,gCAEA,iBACA,YACS,gCACT,cACA,wBACA,WAA2B,KAAW,EACtC,oBAGA,4BAES,iEACT,UACA,UACA,eACA,2BACA,0BAEA,+DACA,MAAuB,KAAW,OAClC,oBACA,uBAEA,uDACA,IACA,CACA,0BAEA,yEACA,eACA,EACA,IAEA,YACA,mBACA,GACA,IAEA,SACA,gBACA,EAMA,QACA,+DACA,WAAyB,SAAiB,KAC1C,eAAgC,UAAuB,QACvD,2BAGA,WACA,EAOA,aACA,yBACA,GACA,mCAEA,+DACA,cACA,EACA,IAQA,YACA,OACA,gBACA,SAEA,2BACA,8BACA,sBACA,cACA,EACA,IAOA,gBACA,4BACA,GACA,sCAEA,uDAAuB,SAAe,KACtC,qBAEA,wBACA,EACA,IAQA,eACA,CACA,0BACA,SAEA,iCACA,iCACA,cAAuB,UAAe,KACtC,2BAEA,0BACA,EACA,IACA,EAEA,WACA,gCC5IA,aA8EA,UA5EA,KACA,WACA,IACA,uBACA,WACA,kBAA2B,MAAc,OACzC,yBAEA,GAAS,yBACT,mBAEA,4BAEA,qCACA,EAEA,WACA,iBACA,2BAEA,QAEA,CAEA,WACA,OACA,EAEA,UACA,OACA,EAQA,kBACA,SACA,mBACA,cAAuB,KAAO,EAC9B,2BAEA,YACA,KACA,KACA,KACA,KACA,KACA,KAEA,aAAuB,KAAO,EAC9B,WACA,UACA,gBACA,gBACA,gBACA,IACA,8CAEA,+BAGA,yDAEA,WACA,GACA,SACA,QACA,cAEA,EAEA,oBC5EA,aAEA,QACA,WAEA,mBACA,oBACA,CACA,oBACA,YACA,eACA,EAEA,6BACA,UACA,MACA,EAEA,2BClBA,aAEA,gCACA,OACA,WACA,EACA,qBAEA,UAGA,YACA,gBAEA,KAGA,6BCjBA,aAEA,QAQA,GACA,+BACA,wBACA,YACA,wBAEA,yBAQA,EACA,kCACA,8BACA,YACA,wBAEA,4BASA,EACA,8BACA,MACA,gBAEA,0BACA,6BAEA,+DACA,EASA,EACA,iCACA,MACA,gBAEA,0BACA,0BAEA,4DACA,IAEA,8BACA,mBACA,oBAEA,IAEA,iBACA,oBACA,OAEA,UACA,wBAGA,mDACA,uCAEA,iFACA,oCAEA,IACA,KACA,SAEA,IAEA,kCACA,6CACA,gFACA,OACA,mBACA,6BACA,yGACA,6BAEA,uCAEA,wBACA,qBACA,MAAmB,OAAgB,OACnC,aAEA,SACA,IAEA,sBACA,iCACA,KAAmB,MAAiB,OACpC,aAAuB,OAAoB,UAC3C,gCAGA,WACA,IAEA,yBACA,8BACA,WAAmB,MAAiB,OACpC,aAAuB,OAAoB,UAC3C,kCAGA,WACA,IAEA,oBACA,WACA,IAAmB,MAAiB,KACpC,eAAuB,OAAoB,QAC3C,gBAGA,UACA,qBC7IA,aAEA,UAEA,OACA,SACA,SACA,SACA,UACA,UACA,UACA,UACA,UACA,UAEA,QACA,UACA,MACA,aACA,OACA,QACA,SACA,cACA,aACA,OACA,aACA,kBACA,YACA,WACA,OACA,IAoDA,UAlDA,KACA,mBACA,oBACA,GAEA,qCACA,OAEA,wBACA,OACA,8BAEA,qDAEA,GAAS,8BACT,kDAEA,4BAEA,yDAEA,eACA,IACA,iBAGA,+BACA,cACA,6BACA,YAEA,6BACA,eACA,WACA,UAAuB,QAAmB,OAC1C,YAA2B,SAAmB,OAC9C,iEAIA,iBAAuB,QAAmB,OAC1C,YAA2B,QAAsB,OACjD,sDAIA,WACA,GACA,gBChFA,aAEA,uBACA,kCAEA,uBACA,OACA,+CAGA,IACA,6BAEA,gBACA,SACA,+BAGA,0BACA,4FAEA,0CACA,GAMA,sBAEA,6CACA,KAEA,sBACA,kBAEA,MACA,eACA,OAGA,qBANA,GAeO,IARP,yBACA,gBAEA,UACE,gDACF,YAGA,UAAmB,KACnB,mBAEA,IAEA,kBACA,UACA,UAGA,SAEA,2BACA,OACA,IACA,mBAEA,oBAIA,qBAGM,KACN,gCAQA,WACA,sBCpFA,aAIA,YACA,MACA,2BACA,OACA,QAMA,CAZA,cAaA,2BACA,6BACA,gCACA,mBACA,yBACA,sBACA,iBACA,GACA,SACA,iBACA,cACA,iBAEA,kBAEA,gBACA,GAMA,EACA,6BACA,mDAEA,4EACA,uBACA,QAEA,cAEA,kBACA,SACA,SACA,sBAEA,oCACA,IAEA,WACA,wBACA,2BAEA,SACA,IAEA,2BC9DA,aAEA,0BACA,IACA,+BACA,QACA,4BAEA,IACA,MAIA,OAHA,4BAEA,GAMA,EACA,+BACA,iBACA,KAAmB,IAAU,EAC7B,eAEA,SACA,IAEA,kCACA,iBACA,KAAmB,IAAU,MAC7B,YACA,cAAuB,KAAa,EACpC,cAEA,CACA,OACA,qBCpCA,aAqBA,iBACA,+BACA,IACA,IAQA,CA9BA,UACA,OAMA,GA+BA,UACA,CACA,KAhCA,YACA,sCACA,MAQA,YAuBA,EACA,iBAXA,YACA,sBACA,qCACA,yCACA,WAAY,wCACZ,uBCtCA,aAEA,4BACA,aAGA,iBAEA,oBACA,OACA,OACA,QACA,oBACA,uBACA,yBACA,sBACA,6BACA,4BAEA,cACA,mCAES,UACT,UACA,iBACA,4BAGA,6DACA,KAEA,KACA,KAEA,KAA2B,KAAO,GAClC,WACA,UACA,gBACA,gBAGA,oBAGA,2BACA,6CACA,0CACA,UACA,kDAEA,GAEA,CAEA,SACA,OACA,MACA,oCACA,qBAEA,uBACA,yBAGA,SACA,CAEA,YACA,0BACA,SAEA,YACA,+BACA,KAEA,YACA,OACA,wBACA,qBACA,2CACA,mBACA,sBACA,sCACA,uBACA,EACA,CACA,0BAEA,SACA,EAEA,WACA,sBACA,EAEA,eACA,IACA,sDAEA,mCACA,EACA,EAEA,2BCvGA,aAEA,eACA,UACA,CAMA,CACA,iBACA,WACA,IAAmB,MAAmB,OACtC,SAEA,SACA,EAMA,EACA,iBACA,aACA,OACA,SAAmB,IAAO,EAC1B,iBAEA,UACA,EAMA,EACA,iBACA,aACA,OACA,SAAmB,IAAO,EAC1B,iBAEA,UACA,EAMA,EACA,oBACA,aACA,OACA,QACA,UAAmB,KAAO,GAC1B,mBACA,mBAEA,WACA,KACA,MAEA,EAMA,EACA,4BACA,WACA,MACA,UAAmB,KAAO,EAC1B,UAEA,aACA,CAIA,EACA,SAMA,eACA,2BACA,WACA,MACA,UAAmB,KAAO,EAC1B,UAEA,wBACA,EAQA,EACA,qBACA,WACA,MACA,UAAmB,KAAO,EAC1B,mBAEA,cACA,CAOA,EACA,yBACA,WACA,KACA,OACA,UAAmB,KAAO,GAC1B,gBACA,UAEA,aACA,EAQA,EACA,+BACA,cACA,MACA,wBAEA,iBACA,wBACA,MACA,KAAmB,SAAa,GAChC,WAEA,oBACA,GAMA,EACA,0BACA,WACA,MACA,UAAmB,KAAO,OAC1B,IACA,oDAEA,kBACA,GACA,UACA,CAMA,EACA,gCACA,WACA,IACA,OACA,UAAmB,KAAO,GAC1B,gBACA,SAEA,OACA,yBAEA,sCACA,CAOA,EACA,sBACA,cACA,MACA,wBAEA,YACA,uBACA,SACA,QAEA,sBAEA,GAOA,EACA,wBACA,cACA,uBACA,MACA,OAEA,UAAmB,QAAO,GAC1B,cACA,SAGA,SACA,UAEA,MAEA,EAOA,EACA,iCACA,+BACA,KAEA,2BACA,2CACA,OAOA,EACA,gCACA,WACA,iBACA,SAAe,KAAY,GAC3B,UAEA,OACA,gBACA,WAAe,KAAY,GAC3B,2BACA,kBACA,KACA,qBAEA,iCAGA,OACA,MACA,QAEA,IAEA,yBACA,yBACA,MACA,wBAGA,mBACA,oBACA,eACA,0BAEA,UAAY,eACZ,KAEA,uCACA,qCACA,KAEA,8BACA,yBACA,gBACA,YACA,UAAmB,KAAO,QAC1B,UACA,kBAEA,qBAEA,OACA,YAEA,KACA,MACA,UACA,IAEA,kBACA,SACA,eACA,GACA,UAAe,KAAO,EACtB,WAEA,eACA,MAEA,SAAe,KAAO,OACtB,qBACA,KACA,QAEA,gBACA,UACA,EAEA,KAEA,aACA,SAAe,KAAW,GAC1B,WACA,UACA,OAIA,cACA,KAEA,4BACA,yBACA,oBACA,aAEA,mBACA,YAEA,4DACA,UAAmB,KAAO,QAC1B,cACA,YACA,UACA,EAEA,OACA,UAEA,MACA,IAEA,wBACA,yBACA,uBAEA,kBACA,UAAmB,QAAO,GAC1B,cACA,SACA,aAEA,aACA,SAEA,qBACA,UACA,yBACA,kBACA,GACA,EACA,OAEA,KAEA,wBACA,yBACA,uBACA,uBAEA,KAAmB,QAAO,GAC1B,cACA,SACA,gBAEA,aACA,SAEA,QACA,eACA,aAEA,wCADA,OAIA,6BADA,IAEA,mBAEA,GAEA,uBACA,2BACA,oBACA,UAAmB,KAAO,GAC1B,6BACA,UACA,GAEA,4BACA,kBACA,UAAmB,KAAO,GAC1B,gBACA,UACA,IAEA,yCACA,uCACA,KAEA,gCACA,4BACA,aACA,eAEA,KAAmB,KAAO,QAC1B,cACA,OAEA,eACA,QACA,UACA,EAEA,sBACA,MAEA,sBACA,yBAEA,YACA,EACA,gBAEA,8BACA,UAAmB,KAAO,GAC1B,YACA,IAEA,6BACA,+CACA,4BACA,mBACA,oBACA,OAAmB,KAAO,GAC1B,kBACA,QACA,KAEA,2BACA,SACA,eACA,UACA,cAAmB,KAAO,EAC1B,qBACA,UACA,iBC9dA,6BACA,OAEA,MACA,aAGA,aACA,YACA,4BAGA,0BACA,sBAGA,aACA,YACA,4BAGA,+BAGA,gBACA,kBAGA,GACA,SAGA,UACA,SAIA,aAIA,UACA,oBC1CA,kBAGA,kDACA,iCCJA,aAEA,gBACA,sBACA,gDCJA,aAEA,iBACA,e,sBCHA,aAgSA,iBACA,OACA,SAEA,iBACA,sBACA,SAEA,oBACA,yBACA,mBAEA,oBACA,yBACA,mBA5SA,UAEA,UACA,WACA,gBAEA,gBACA,KACA,KAEA,EAIA,QACA,aAA4B,MAC5B,iBACA,IAYA,2BAXA,8BACA,4BACA,8BACA,oCACA,+BACA,6BACA,iCACA,wCACA,oDAfA,OAmBA,mBACA,0EAAiF,EAGjF,yCAtBA,KAuBA,kDACA,uBACA,qDAA2D,EAE3D,cACA,qDAA2D,EAE3D,WACA,0CAAmD,EAAc,yCAAwC,EAGzG,YAIA,MACA,cACA,gBAEA,mBACA,oBACA,mBAEA,sBACA,2BACA,GAEA,EAGA,iBACA,mBAEA,qBACA,+BACA,cAEA,QACA,eACA,KAEA,WACA,aACA,QAEA,QACA,0BACA,gBACA,cACA,GAEA,WACA,8BACA,OACA,KAKA,cAJA,kBACA,0CAIA,oDACA,kCACA,gBACA,GAEA,mBACA,mBACA,6BACA,6BACA,QAEA,8BACA,oDACA,2BACA,GAEA,CACA,QAEA,cACA,0BACA,YAEA,uBACA,QAEA,oBAGA,yBAEA,cACA,0BACA,YAEA,uBACA,QAEA,oBAGA,yBAEA,sBACA,oCACA,kDACA,2BACA,GACA,CAEA,gBACA,OACA,uBAEA,eACA,eACA,cACA,oBAEA,UACA,wBACA,aACA,kBAEA,uCACA,SACA,cAGA,wBACA,EACA,EAEA,kBACA,OACA,yBAEA,iBACA,eACA,eAEA,iBAAuB,QAAkB,OACzC,8BACA,SAIA,WACA,CAEA,qBACA,eACA,cACA,YAGA,UACA,wBACA,aACA,kBAEA,yBACA,QACA,cAGA,mBACA,UACA,4CACA,SACA,cAEA,qBACA,GAEA,iBACA,OAGA,EACA,EAEA,mBACA,yBACA,aACA,gBACA,GACA,CAEA,WACA,qBAEA,4CAEA,4BACA,cACA,eAEA,cACA,WACA,WAEA,+BACA,4CAEA,0BACA,eACA,cACA,4BAEA,oBAAuB,KAAiB,GACxC,oBACA,WACA,6BACA,WACA,aACA,WACA,EAEA,CAEA,eACA,YAAuB,gBAAuB,OAC9C,yBACA,wBAGA,SACA,QAEA,iBACA,YAAuB,gBAAuB,OAC9C,yBACA,yBAGA,SACA,QAEA,gBACA,YAAuB,gBAAuB,OAC9C,yBACA,wCAGA,SACA,QACA,EAEA,8BC9RA,aAeA,iBACA,WACA,OACA,+CAEA,oCAEA,GACA,gBACA,uBACA,wBACA,2BACA,MAEA,eAEA,OAGA,OACA,6BAAmB,KAAU,GAC7B,uBACA,4BACA,kBACA,iBAEA,uBAKA,YACA,8BAAmB,KAAU,GAC7B,uBACA,MACA,iBACA,iBAEA,UAKA,kCACA,8BACA,wBACA,mEAAmB,KAAU,GAC7B,uBACA,mBACA,kBACA,iBAEA,0BAEA,EAIA,aAAmB,KAAU,GAC7B,uBACA,MACA,oBACA,iBAEA,OAIA,YACA,GAOA,CACA,iBACA,WACA,gBACA,8BACA,yCACA,iBACA,kCAMA,CAtGA,QAEA,KACA,MACA,QAQA,GAwGA,UAbA,eACA,OAAuB,OAEvB,kBACA,4BACA,SAEA,SAGA,wBACA,6CCpHA,aAGA,aACA,0BACA,uBAEA,qBANA,aAQA,mBACA,UACA,KACA,KACA,GAEA,oBACA,UACA,KACA,KACA,oBCZA,aAEA,YA6NA,UACA,CACA,UAzMA,YACA,IACA,0BACA,cACA,kBACA,aAqMA,IAnMA,eACA,yBACA,8BACA,MACA,uCAEA,cACA,sBAEA,KA2LA,SAzLA,eACA,yBACA,8BACA,MACA,4CACA,cACA,sBACA,KAmLA,SAjLA,eACA,yBACA,8BACA,MACA,4CAEA,cAEA,cACA,2BAEA,eAEA,gBACA,oBAEA,GAEA,IAgKA,YA9JA,eACA,WACA,sBACA,KA4JA,UA1JA,eACA,WACA,sBACA,KAwJA,KAtJA,YACA,QACA,iCAEA,8BACA,oCACA,iBACA,gBACA,sBACA,mBACA,OAAuB,KAAU,GACjC,uBAIA,mBACA,sBACA,OAAuB,KAAU,GACjC,mBAKA,OACA,yBACA,OAAmB,KAAU,GAC7B,sBAIA,kBACA,wBACA,aACA,OAAuB,KAAO,GAC9B,mBAIA,UACA,KAgHA,IA9GA,eACA,yBACA,uCACA,6BACA,qBACA,OAAmB,KAAQ,GAC3B,gBAAuB,KAAQ,GAC/B,kCACA,WAGA,WAIA,UACA,KA+FA,IA7FA,eACA,yBACA,uCACA,6BACA,qBACA,OAAmB,KAAQ,GAC3B,gBAAuB,KAAQ,GAC/B,kCACA,WAGA,WAIA,UACA,KA8EA,MArBA,eACA,iBACA,KAoBA,IAlBA,YACA,OACA,sBACA,MACA,WAeA,KA9EA,YACA,IACA,qCACA,6BACA,qBACA,OAAmB,KAAQ,GAC3B,gBAAuB,KAAQ,GAC/B,iCAIA,WACA,KAmEA,IAnDA,YACA,IACA,qCACA,6BACA,qBACA,OAAmB,KAAQ,GAC3B,gBAAuB,KAAQ,GAC/B,gCAGA,WACA,KAyCA,OAvCA,eACA,IACA,uCAEA,6BACA,qBACA,OAAmB,KAAQ,GAC3B,gBAAuB,KAAQ,GAC/B,oCAGA,UACA,KA4BA,IAnEA,YACA,IACA,oCACA,6BACA,qBACA,OAAmB,KAAQ,GAC3B,gBAAuB,KAAQ,GAC/B,gCAIA,WACA,KAwDA,OA5OA,eACA,kBACA,KA2OA,KAzOA,eACA,mBACA,KAwOA,MAlOA,eACA,oBACA,KAiOA,OA/NA,eACA,mBACA,KA8NA,IAxOA,eACA,kBACA,mBCrBA,uBACA,aACA,SACA,IACA,KACA,KAAmB,KAAS,EAC5B,gBACA,eACA,+BAEA,kBACA,iBCXA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,uBAEA,aACA,gBCPA,uBACA,aACA,SACA,IACA,KACA,KACA,KAAmB,KAAS,EAC5B,gBACA,eACA,gBACA,+BAEA,qBACA,iBCbA,uBACA,aACA,SACA,IACA,KAAmB,KAAS,EAC5B,yBACA,yBAEA,cACA,gBCTA,uBACA,aACA,SACA,IACA,KAAmB,KAAS,EAC5B,yBACA,gBAEA,eACA,gBCTA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,sEAEA,WACA,iBCPA,uBACA,aACA,SACA,IACA,KACA,KAAmB,KAAS,EAC5B,gBACA,eACA,gBAEA,qCACA,mBCXA,aAEA,uBACA,WACA,IACA,KAAmB,OAAc,OACjC,yBACA,gBAEA,eACA,gBCVA,yBACA,MACA,WACA,IACA,KAAuB,OAAc,OACrC,iBACA,gBAEA,UACA,OACA,IACA,CAEA,cACA,UACA,KACA,KACA,KAAuB,KAAS,GAChC,WACA,UACA,yBAEA,kCAEA,sBCxBA,aAEA,QAEA,WACA,cAEA,OAWA,eACA,kBACA,4BACA,iCACA,8BACA,0BACA,kCAEA,2BACA,6BAEA,0DACA,4DAEA,gDACA,0BACA,IACA,+BACA,0BACA,IAEA,IAEA,8BACA,0BAKA,uCACA,kCAEA,wCACA,2BACA,UAEA,GAOA,WACA,yCACA,wBACA,8BACA,QACA,EAQA,sBACA,iCACA,oBAEA,aACA,gEACA,UAKA,SACA,qCACA,8CACA,uCACA,SAMA,SACA,OACA,OACA,uBACA,0BACA,+BACA,4BACA,wBACA,kBACA,SAEA,EAOA,eACA,IACA,uCAEA,uDACA,EAEA,EAEA,yBC1HA,aAEA,cACA,uBACA,KAEA,iBACA,iCACA,GAoBA,QACA,MACA,iBACA,uBAEA,aACA,gBACA,gBAEA,YACA,YACA,0BAEA,aACA,iBACA,2BAEA,aACA,+BACA,kDAEA,YACA,uBACA,uBAEA,YACA,oCACA,iCAEA,WACA,yCACA,0CAEA,YACA,iBACA,kBAEA,UACA,sCACA,0DAEA,cACA,8BACA,sCAEA,wBACA,gCACA,6BAEA,qBACA,YACA,qCAEA,sBACA,CACA,WAzEA,eACA,OACA,8BAEA,GACA,4BAEA,GACA,IAmEA,SAjEA,eACA,OACA,kBAEA,iBAEA,OA6DA,6BCvFA,aAEA,QAMA,GAgDA,UACA,CACA,YAlBA,WACA,QAAmB,OAAc,qBACjC,KAAmB,KAAO,OAC1B,gBACA,iBACA,YACA,IAIA,YACA,QACA,WAEA,KAKA,OAnCA,WACA,wBACA,YAAmB,OAAiB,OACpC,cAAuB,OAAoB,UAC3C,oBAGA,UACA,GAOA,EAqBA,OAnDA,WACA,2BACA,MAAmB,OAAiB,OACpC,cAAuB,OAAoB,UAC3C,oBAGA,UACA,GAMA,oBCvBA,aAKA,aACA,QACA,iBACA,gBACA,OACA,YARA,QACA,aASA,gBAEA,6BCdA,aAEA,UAQA,KA4FA,kBAhEA,qBACA,YAAmB,QAAiB,OACpC,yBAAwD,iBAExD,WACA,GASA,EAmDA,gBAlDA,kBACA,gBAGA,wBACA,aACA,OAAmB,KAAO,QAC1B,cACA,WACA,aAAuB,KAAU,GACjC,gBAEA,CAGA,YAAmB,QAAiB,YACpC,OACA,kBAAyB,KAAY,GACrC,4BAEA,GAGA,YAAoB,KAAQ,GAC5B,gBAAuB,KAAU,GACjC,oBAGA,UACA,GAUA,EAYA,0BA7FA,eACA,qBACA,WAAmB,QAAiB,SACpC,cAAuB,SAAiB,YACxC,IACA,sBAEA,YACA,sBAEA,+BACA,gBACA,cACA,EAEA,OACA,GAUA,EAoEA,YAZA,qBACA,YAAmB,QAAoB,OACvC,0BACA,GAGA,SACA,wDCpGA,aAeA,gEAugDA,eACA,oBACA,6BAEA,oCAEA,6BACA,UACA,CAMA,mCAmNA,aACA,2CAEA,UACA,EAEA,gCApuDA,iCACA,6BACA,OACA,KASA,0BACA,MACA,MACA,4BAEA,oEACA,KAA6B,IAAe,EAC5C,cAAoC,IAAqB,EACzD,oBAGA,UACA,EAOA,oBACA,wBACA,UAA2B,MAAoB,OAC/C,gBAEA,UACA,EAOA,uBACA,6BACA,KAA2B,MAAoB,OAC/C,gBAEA,UACA,EAQA,kBACA,mBACA,EAQA,kBACA,6BACA,EAQA,iBACA,6BACA,EASA,mBACA,qBACA,+BACA,KAA2B,IAAU,EACrC,cAA+B,IAAa,EAC5C,cAGA,WACA,EAUA,wBACA,cACA,2BACA,+BACA,KAA2B,IAAU,EACrC,cAA+B,OAAa,EAC5C,sBACA,aAGA,UACA,EASA,kBACA,gBACA,kBACA,wBACA,kBACA,KAA2B,IAAS,EACpC,cAEA,SACA,EASA,mBACA,SACA,sBACA,kBACA,0BACA,kBACA,KAA2B,IAAS,EACpC,gBAEA,UACA,EAQA,gBACA,oBACA,sBACA,eACA,SACA,qBACA,KAA2B,IAAU,EACrC,cAA+B,IAAa,EAC5C,0CAGA,WACA,EAQA,gBACA,oBACA,sBACA,eACA,SACA,qBACA,KAA2B,IAAU,EACrC,cAA+B,IAAa,EAC5C,0CAGA,WACA,EAOA,sBACA,iCACA,EAOA,mBACA,iBACA,kBAKA,WACA,uBACA,OAOA,SACA,IACA,yCAEA,8CACA,YACA,UAA2B,IAAQ,EACnC,cAA+B,IAAQ,EACvC,kBAGA,SACA,KAMA,YACA,sBACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,mCAGA,SACA,EAMA,YACA,sBACA,QAA2B,SAAe,SAC1C,iBACA,mBAA+B,SAAkB,QACjD,uBAEA,EACA,OACA,EAKA,cACA,OACA,cAKA,iBACA,OACA,iBAKA,WACA,uBACA,gBAKA,WACA,yBACA,OAKA,cACA,oBACA,WAA+B,SAAe,KAC9C,cAAmC,KAAQ,EAC3C,kCACA,GAIA,SACA,QACA,CACA,QAUA,MACA,iBACA,8BASA,MACA,iBACA,8BAYA,YACA,MACA,OACA,0EACA,KAA2B,IAAY,EACvC,cAA+B,IAAY,EAC3C,iDAGA,SACA,EAOA,QACA,WAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,iBAGA,SACA,KAMA,MACA,mBACA,EAOA,UACA,yBACA,wBACA,WAA2B,SAAkB,QAC7C,oBAEA,SACA,EAOA,gBACA,+CACA,GAQA,YACA,yBACA,8BACA,aAA2B,SAAkB,QAC7C,mBAEA,UACA,KAQA,cACA,yBACA,2BACA,aAA2B,WAAkB,QAC7C,iBACA,2BACA,iBAEA,SACA,KAOA,aACA,4BACA,wBACA,QAA2B,SAAe,KAC1C,oBAEA,SACA,EAOA,mBACA,qDACA,GAQA,eACA,4BACA,iCACA,aAA2B,SAAe,KAC1C,mBAEA,UACA,KAQA,iBACA,4BACA,8BACA,aAA2B,WAAe,KAC1C,iBACA,2BACA,iBAEA,SACA,KAOA,gBACA,4BACA,aAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,iCAGA,UACA,KAOA,gBACA,4BACA,aAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,iCAGA,UACA,KAOA,gBACA,4BACA,aAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,iCAGA,UACA,KAOA,gBACA,4BACA,aAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,iCAGA,UACA,KAOA,mBACA,+BACA,aAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,iCAGA,UACA,KAOA,mBACA,+BACA,aAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,iCAGA,UACA,KAOA,mBACA,+BACA,aAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,iCAGA,UACA,KAOA,mBACA,+BACA,aAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,iCAGA,UACA,KAQA,YACA,yBACA,aAA2B,SAAkB,QAC7C,+BAEA,SACA,KAQA,eACA,4BACA,aAA2B,SAAe,KAC1C,+BAEA,SACA,KAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,kBACA,iBAIA,UACA,EAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,kBACA,iBACA,QACA,OAIA,SACA,EAMA,MACA,sBACA,KAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,kBACA,iBAIA,UACA,EAMA,WACA,sBACA,GACA,UAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,kBACA,iBACA,QACA,OAIA,SACA,EAOA,UACA,yBACA,wBACA,KAA2B,SAAkB,QAC7C,kBACA,iBAGA,UACA,EAOA,eACA,yBACA,wBACA,QACA,KAA2B,SAAkB,QAC7C,kBACA,iBACA,QAGA,SACA,EAOA,UACA,yBACA,wBACA,KAA2B,SAAkB,QAC7C,kBACA,iBAGA,UACA,EAOA,eACA,yBACA,wBACA,QACA,KAA2B,SAAkB,QAC7C,kBACA,iBACA,QAGA,SACA,EAOA,aACA,4BACA,wBACA,KAA2B,SAAe,KAC1C,kBACA,iBAGA,UACA,EAOA,kBACA,4BACA,wBACA,QACA,KAA2B,SAAe,KAC1C,kBACA,iBACA,QAGA,SACA,EAOA,aACA,4BACA,wBACA,KAA2B,SAAe,KAC1C,kBACA,iBAGA,UACA,EAOA,kBACA,4BACA,wBACA,QACA,KAA2B,SAAe,KAC1C,kBACA,iBACA,QAGA,SACA,EAMA,OACA,mCACA,iBACA,KAA2B,IAAS,EACpC,oBAEA,SACA,EAQA,OACA,OAEA,QADA,gBAEA,MACA,8BAEA,kBAEA,KAMA,OACA,wBACA,IAMA,OACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,kBAGA,SACA,EAMA,gBACA,WACA,IAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,kBACA,gBAGA,SACA,KAOA,OACA,qBACA,wBACA,4BACA,4BAEA,+CACA,IAA2B,MAAoB,OAC/C,cAEA,SACA,EAOA,QACA,gCACA,oBAEA,mBAGA,oGACA,YACA,YAEA,iDAEA,WACA,KAA2B,IAAO,MAClC,YAA+B,KAAO,EACtC,oBAGA,cAA+B,QAAO,OACtC,QACA,KAA+B,KAAO,EACtC,2BAGA,eACA,GACA,CACA,OACA,EAEA,eACA,8CACA,sBACA,aACA,gBACA,aACA,gBACA,cACA,iBACA,cAGA,gBACA,cACA,UACA,cACA,YACA,kBAUA,QALA,cADA,aAOA,KALA,YAMA,KALA,YAMA,QAJA,YARA,IAaA,CAEA,eACA,8CAEA,sBACA,gBACA,gBACA,gBACA,gBACA,iBACA,iBACA,iBACA,iBAEA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cACA,cAEA,iBAEA,uBAEA,kBACA,SACA,wBACA,mBACA,oBACA,yBAGA,kBACA,SACA,mBACA,wBACA,kBACA,mBACA,mBAiBA,KAVA,KANA,YAiBA,oBAnCA,kBAyBA,YAWA,8BA3BA,SAiBA,YAWA,2BAnCA,gBAyBA,YAWA,WAVA,MATA,YAoBA,WAVA,KATA,YAoBA,kCA9BA,UAoBA,YAWA,WAVA,MAVA,YAqBA,WATA,MAVA,IAoBA,CAOA,gBACA,qBAaA,WACA,WACA,yBACA,SAEA,sBACA,mCACA,GAEA,EAOA,wBAQA,aACA,uBAIA,aACA,yBACA,mBACiB,IACjB,sBACA,iBACiB,KACjB,wBACA,iBAGA,4BACA,0BAEA,+BACA,+BAEA,wCACA,wCAEA,qCACA,qCAEA,8CACA,8CAGA,qCACA,4BACA,4BACA,4BACA,4BACA,sCACA,sCAGA,gBACA,WACA,WACA,oBACA,gBACA,gBACA,WACA,WAGA,kCACA,wCACA,iCACA,8BACA,0CACA,kCACA,EACA,YA9FA,YACA,SACA,YACA,UACA,YAEA,+BAA4C,CAAG,MAAK,CAAG,QAAO,CAAG,MAAK,EAKtE,uDAkBA,iBACA,oBACA,aAGA,aA6DA,GAQA,eACA,mBACA,iBACA,KACA,uBAEA,2FACA,WAA2B,WAAe,KAC1C,uCAA+D,MAC/D,mBAEA,SACA,EAWA,kBACA,mBACA,iBACA,KACA,uBAEA,2FACA,WAA2B,WAAkB,QAC7C,yCACA,KACA,MAEA,kBAEA,SACA,EASA,oBACA,gCAEA,kBACA,YACA,YACA,SAEA,qDACA,KAA2B,IAAO,EAClC,eAA+B,KAAO,EACtC,gBAAmC,KAAO,EAC1C,gBAAuC,KAAO,EAC9C,gDAKA,UACA,EAMA,YACA,kEACA,QAA2B,SAAe,KAC1C,cAA+B,SAAkB,QACjD,yBAGA,UACA,EAOA,YACA,gBACA,0BAA2B,SAAe,KAC1C,sCAEA,UACA,KAOA,eACA,gBACA,0BAA2B,SAAkB,QAC7C,4CAEA,UACA,KAUA,mBACA,4BACA,4DACA,KAAkC,KAAa,EAC/C,cAAyC,KAAgB,EACzD,2BAGA,SACA,EASA,oBACA,mBACA,+BACA,2CACA,6BAGA,qFACA,KAA2B,MAAoB,OAC/C,cAAyC,KAAgB,MACzD,uBACA,uDAEA,8BACA,GAEA,OACA,EASA,uBACA,mBACA,4BACA,wCACA,0BAGA,gFACA,UAA2B,MAAoB,OAC/C,cAAsC,KAAa,MACnD,uBACA,6DAEA,6BACA,IAEA,OACA,EASA,oBACA,gCACA,kBACA,gBACA,6BACA,aAA2B,MAAiB,KAC5C,cAA+B,MAAoB,QACnD,2BAGA,SACA,KAQA,eACA,oCACA,qDACA,UAA2B,YAAwB,WACnD,SACA,aAA+B,gBAA2B,OAC1D,gBACA,sBAEA,GACA,OACA,EAMA,QACA,mCACA,WACA,IAA2B,IAAS,EACpC,kBAEA,SACA,EAUA,gBACA,gCACA,KAOA,WACA,gCACA,0BACA,EAOA,cACA,mCACA,6BACA,EAMA,cACA,8BACA,KAMA,iBACA,iCACA,KAUA,uBACA,qCACA,EAWA,mBACA,uCACA,EASA,MACA,oBACA,WACA,KAEA,qCACA,gBACA,gBACA,gBAEA,SACiB,sBAEjB,SACA,gBACA,kCACA,kCACA,wCACA,gBACA,gBAEA,2BACA,KAEA,kCAGA,WACA,aAEA,0DAGA,oBAQA,oBAgBA,kBACA,sCACA,kBACA,mCACA,0CACA,qDAMA,wBAOA;;;;;wBAWA;;;;;;;;;wBAaA;;;;;;;;;;;iBAOA;;;;;gBAWA;;;;;;;;;eAOA;;;;;wBAWA;;;;;;;;;uBAQA;;;;;gCAUA;;;;;;;;;gCAaA;;;;;;;;;;;0BAOA;;;;;yBAEA,qBAgBA,oPAEA,gCACA,0DAAoE,6BACpE,kEAA2E,iCAC3E,kEAA2E,iCAC3E,yDAAkE,cAClE,YAAmB,aAAqB,OACxC,6BACA,uCACA,wCACA,0BAEA,QAEA,IAIA,uBAIA,+NACA,yBACA,GAEA,EAtrDA,2BAurDA,0DAAoE,6BACpE,yDAAkE,YAClE,YAAmB,WAAmB,OACtC,2BACA,yBAEA,UAEA,IAIA,iFACA,UACA,aAAmB,kBAAsB,GACzC,kBAA4B,CAE5B,2BACA,yEACA,oBACA,wBACA,QAEA,2EAAsF,2BACtF,cAAuB,kBAA0B,OACjD,kCACA,wCAEA,kBAAS,KACT,aACA,oBACA,QACA,0BAEA,qEACA,iFACA,iFACA,yEACA,gBAAuB,kBAA0B,OACjD,kCACA,iDACA,iDACA,mCAEA,aACA,CAEA,OAQA,GA5vDA,8BAEA,wCACA,mCACA,6BACA,2CACA,uCACA,uCACA,6CACA,0CACA,2CACA,oECbA,aAKA,aACA,qBACA,iBAGA,0BAEA,WACA,YACA,UACA,iBACA,MACA,oBACA,SAEA,UAAe,KAAU,EACzB,YAGA,gBAEA,MAAe,KAAa,QAE5B,QAAmB,KAAU,EAC7B,kBAGA,WAAmB,KAAU,OAC7B,UACA,mBACA,OACA,KAAuB,KAAU,GACjC,mBAEA,mBACA,EAEA,QACA,SAAuB,KAAU,EACjC,kCACA,UAIA,eACA,QAAuB,KAAa,GACpC,cACA,oBACA,cAGA,SACA,cACA,WAEA,OACA,EAEA,UACA,wBAA2B,KAAU,EACrC,sBAGA,GAEA,SACA,mBACA,kBACA,GAvEA,QAEA,GAuEA,YACA,sBACA,gBACA,OACA,UAAuB,IAAS,EAChC,OACA,YAGA,SACA,QACA,mBACA,YACA,SACA,2BAEA,sDACA,WAAuB,KAAS,EAChC,cAEA,UACA,EACA,6BACA,gBACA,OACA,SACA,0BACA,MAAuB,KAAU,EACjC,gBAA2B,KAAa,EACxC,mBACA,SACiB,SACjB,GAEA,EAIA,QACA,GACA,6BACA,gBACA,OACA,SACA,0BACA,MAAuB,KAAU,EACjC,gBAA2B,KAAa,EACxC,oBACA,SAEA,IAIA,QACA,GACA,8BACA,yBACA,OACA,mBACA,wBAEA,cACA,OAEA,cACA,qBAEA,qCACA,6BAGA,kCACA,gDACA,QACA,cAEA,UAAmB,KAAa,GAChC,eAA2B,KAAa,GACxC,YAA2B,KAAW,GACtC,kCAIA,cAA6B,EAAQ,WACrC,QAAuB,KAAW,GAClC,uBAEA,WAAuB,KAAO,GAC9B,YAA2B,KAAW,GACtC,kCAGA,GACA,OACA,GACA,GAEA,6BC7KA,aAeA,iBACA,CACA,mBACA,qCAEA,uBAWA,CA0DA,oBACA,YACA,MAGA,KAAkB,WAAoB,YACtC,WACA,cAAsB,qBAA8B,IACpD,wDAGA,gBACA,OACA,QACA,MAEA,GAEA,OACA,GAKA,CA6BA,uBACA,WACA,qCACA,IAOA,CACA,iBACA,eAEA,WACA,WACA,QAAmB,QAAc,OACjC,oBACA,kBACA,EAEA,YAEA,oBACA,aACA,WAAc,KAAa,KAC3B,uBACA,WAEA,SAAc,QAAY,OAC1B,0CACA,WAEA,aACA,IA9KA,QACA,WAEA,uBACA,0BAQA,EAkBA,iCACA,yBACA,4BAGA,cAFA,iBAGA,4BAEA,sFACA,gBACA,4BACA,mBAAkB,QAA6B,YAC/C,0BACA,2CAEA,+BACA,6BAEA,aACA,cAAsB,kBAAsB,IAC5C,YACA,+BAGA,mBACA,EAEA,6BACA,EAOA,EACA,gCACA,kDACA,4BAEA,mFAEA,WAAkB,QAAwB,SAC1C,mCAGA,8BACA,GASA,EA0BA,6BACA,OACA,WACA,wBACA,kCAEA,uBAMA,EACA,mBACA,IACA,iDAEA,+CACA,GASA,mBCjIA,aAEA,aACA,qBACA,UAGA,iBAQA,wBACA,CACA,WAEA,4BACA,4BACA,iBACA,KACA,0BAES,aACT,UACA,kBACA,4BAGA,qDACA,qBACA,OACA,SAEA,gBACA,cACA,OAA2B,KAAO,GAClC,YAGA,mBACA,cACA,QACA,UAAuB,KAAO,GAC9B,YAA2B,KAAO,GAClC,gBACA,WAEA,oBAKA,eACA,2BACA,kBAEA,gDACA,wBACA,aACA,GA5CA,QA6CA,kDAEA,IACA,CAEA,YACA,YACA,KAAwB,iBAAwB,OAChD,sDAEA,WACA,GAEA,SACA,QAAmB,KACnB,yCACA,yBACA,cAGA,eACA,yBAEA,SACA,CAEA,YACA,wBACA,KAEA,WACA,wBACA,KAEA,iBACA,QACA,OACA,MACA,MACA,QACA,QACA,OAGA,qBACuB,EAAvB,wBAAqD,OACrD,QACA,GACA,+BACA,4CAEA,GACA,kDAEA,yDAIA,0DACA,WACiB,iCACjB,WAGA,WAEA,SACA,mCAGA,cACA,EAEA,eACA,IACA,oDAEA,qDACA,EACA,EAEA,2BC5JA,aAEA,eACA,UACA,CAMA,CACA,iBACA,WACA,IAAmB,MAAmB,OACtC,SAEA,SACA,EAMA,EACA,iBACA,YACA,aACA,SAAmB,IAAO,EAC1B,iBAEA,UACA,EAMA,EACA,iBACA,WACA,aACA,SAAmB,IAAO,EAC1B,iBAEA,UACA,EAMA,EACA,oBACA,WACA,YACA,cACA,UAAmB,KAAO,GAC1B,mBACA,mBAEA,WACA,KACA,MAEA,EAMA,EACA,4BACA,WACA,MACA,UAAmB,KAAO,EAC1B,UAEA,aACA,CAIA,EACA,SAMA,eACA,2BACA,WACA,MACA,UAAmB,KAAO,EAC1B,UAEA,wBACA,EAQA,EACA,qBACA,WACA,MACA,UAAmB,KAAO,EAC1B,mBAEA,cACA,CAOA,EACA,yBACA,WACA,KACA,OACA,UAAmB,KAAO,GAC1B,gBACA,UAEA,aACA,EAQA,EACA,+BACA,cACA,MACA,qBAEA,iBACA,wBACA,MACA,KAAmB,SAAa,GAChC,WAEA,oBACA,GAMA,EACA,0BACA,WACA,MACA,UAAmB,KAAO,OAC1B,IACA,oDAEA,kBACA,GACA,UACA,CAMA,EACA,gCACA,WACA,IACA,OACA,UAAmB,KAAO,GAC1B,gBACA,SAEA,OACA,yBAEA,sCACA,CAOA,EACA,sBACA,cACA,MACA,qBAEA,YACA,uBACA,SACA,QAEA,sBAEA,GAOA,EACA,wBACA,cACA,uBACA,MACA,OAEA,UAAmB,QAAO,GAC1B,cACA,SAGA,SACA,UAEA,MAEA,EAOA,EACA,iCACA,+BACA,KAEA,2BACA,2CACA,SAEA,yBACA,yBACA,MACA,QACA,eAGA,mBACA,oBACA,eACA,0BAEA,UAAY,eACZ,KAEA,uCACA,qCACA,KAEA,8BACA,yBACA,gBACA,YACA,UAAmB,KAAO,QAC1B,UACA,kBAEA,qBAEA,OACA,YAEA,KACA,MACA,UACA,IAEA,kBACA,SACA,eACA,GACA,UAAe,KAAO,EACtB,WAEA,eACA,MAEA,SAAe,KAAO,OACtB,qBACA,KACA,QAEA,gBACA,UACA,EAEA,KAEA,aACA,SAAe,KAAW,GAC1B,WACA,UACA,OAIA,cACA,KAEA,4BACA,yBACA,oBACA,aAEA,mBACA,YAEA,4DACA,UAAmB,KAAO,QAC1B,cACA,YACA,UACA,EAEA,OACA,UAEA,MACA,IAEA,wBACA,yBACA,uBAEA,kBACA,UAAmB,QAAO,GAC1B,cACA,SACA,aAEA,aACA,SAEA,qBACA,UACA,yBACA,kBACA,GACA,EAEA,OAEA,KAEA,wBACA,yBACA,uBACA,uBAEA,KAAmB,QAAO,GAC1B,cACA,SACA,gBAEA,aACA,SAEA,QACA,eACA,aAEA,wCADA,OAIA,6BADA,IAGA,mBAEA,GAEA,uBACA,2BACA,oBACA,UAAmB,KAAO,GAC1B,6BACA,UACA,GAEA,4BACA,kBACA,UAAmB,KAAO,GAC1B,gBACA,UACA,IAEA,yCACA,uCACA,KAEA,gCACA,4BACA,aACA,eAEA,KAAmB,KAAO,QAC1B,cACA,OAEA,eACA,QACA,UACA,EAEA,sBACA,MAEA,sBACA,yBAEA,YACA,EACA,QAEA,mCACA,UAAmB,KAAO,GAC1B,YACA,IAEA,6BACA,+CACA,4BACA,mBACA,oBACA,OAAmB,KAAO,GAC1B,kBACA,QACA,KAEA,2BACA,SACA,eACA,UACA,cAAmB,KAAO,EAC1B,qBACA,UACA,iBCpcA,mBACA,QACA,SACA,eACA,WACA,OACA,aAEA,yCACA,6BAA6C,SAAQ,GACrD,4CAEA,KAEA,mCACA,wDACA,KAEA,wCACA,yBACA,uBACA,kFACA,KAEA,oCACA,uBACA,gBAGA,WACA,MACA,oBACS,WACT,8BAEA,yBACA,OACA,EACA,WACA,SAEA,WACA,IAEA,0CACA,EAGA,IACA,gCACA,aACS,WACT,WAEA,GACA,yBACA,WACA,UAEA,WACA,IAEA,2CAEA,GACA,uBACA,IAEA,gCACA,yBACA,cACA,SACA,GACA,SACA,QAgBA,MAEA,eAjBA,iBACA,qBACA,YACA,SACA,OAEA,SACA,MAEA,EACA,WACA,OAGA,oBAIA,qBACA,uCACA,KACA,IAEA,mCACA,OACA,iBACA,mBAEA,KAEA,U,mBCzGA,aAsGA,eACA,YACA,MAAmB,WAAgB,OACnC,8BACA,4DAEA,SACA,GAMA,CAjHA,SAMA,IAmKA,UACA,CACA,MApKA,YACA,YACA,KAAmB,QAAgB,OACnC,gEAEA,sBACA,GAOA,EAwJA,IAvJA,eACA,qBACA,WAAmB,QAAiB,OACpC,sBACA,UACA,GAOA,EA4IA,GA3IA,eACA,qBACA,WAAmB,QAAiB,OACpC,sBACA,UACA,GAOA,EAgIA,IA/HA,eACA,qBACA,WAAmB,QAAiB,OACpC,sBACA,UACA,GAMA,EAqHA,IApHA,YACA,qBACA,WAAmB,QAAgB,OACnC,gBACA,UACA,GAOA,EAyGA,OAxGA,eACA,UAGA,OAFA,YACA,GASA,EA6FA,OA5FA,kBACA,YACA,cACA,iBACA,SAEA,WACA,IACA,EAMA,iBA+EA,GACA,kBAjEA,YACA,sBACA,YACA,OAAmB,KAAS,GAC5B,YAEA,wCACA,GAMA,EAqDA,YApDA,YACA,YACA,MAAmB,WAAgB,OACnC,8BACA,qCAEA,SACA,GAMA,EAwCA,eAvCA,YACA,sBACA,WACA,OAAmB,KAAS,GAC5B,YAEA,uCACA,GAMA,EA2BA,QA1BA,YACA,eACA,OACA,MAAmB,QAAgB,YACnC,qEACA,eAAuB,EAAQ,UAC/B,6BAEA,wBACA,KACA,OACA,uBCzKA,aA4GA,iBACA,mBACA,uBAEA,mDAEA,iBACA,iDACA,IAEA,cACA,WACA,gBAAmB,QAAgB,OACnC,eAEA,uBACA,IAEA,mCACA,2BACA,WACA,GACA,yBACA,WACA,GACA,yBACA,WACA,GACA,yBACA,WACA,GAEA,aACA,gBACA,0BACA,OAAmB,QAA4B,OAC/C,0CAEA,QAhJA,UAEA,IACA,WAWA,IACA,oCACA,iCACA,EAcA,EACA,qCACA,MACA,eACA,sBACA,kBACA,mBACA,aACA,WAAe,KAAO,GACtB,YAEA,sBACA,WAEA,yBAAoC,EAAQ,MAC5C,sBAGA,0BACA,GAEA,iBACA,GAYA,EACA,iCACA,MACA,eACA,sBACA,sBACA,gBACA,OAAmB,KAAO,GAC1B,YAGA,4BAEA,IACA,MACA,YACA,uCACA,mBACA,kBACA,eACA,aACA,IAGA,8BACA,kBAGA,OAAe,QAAkB,YACjC,eACA,IACA,SAAuB,QAAkB,OACzC,+BAGA,6BACA,GAEA,iBACA,KA0CA,0BC3IA,aAsBA,UArBA,aACA,WACA,yBAAoC,+BAGpC,uBAAmB,KAAY,EAC/B,gBAAuB,MAAQ,GAC/B,yBAKA,gBAAmB,KAAY,EAC/B,mBAA2B,KAAY,EACvC,qBAIA,UACA,qBC7BA,aAEA,UAEA,OACA,QACA,SACA,YAEA,QAcA,gBACA,OACA,gBAEA,sBACA,gCACA,gCACA,oCACA,6BACA,yBACA,mCACA,2CAEA,mBAA2B,uBAA2B,IACtD,mCAEA,wEACA,GAEA,yDACA,0DAEA,8DAEA,oEAEA,gEACA,iEACA,+CACA,qBAGA,OAOA,oBACA,oCACA,oBAGA,wBACA,WACA,gCACA,mBACA,gCACA,oCACA,4BAIA,0BAAuB,uBAA8B,SACrD,wBACA,gCACA,gCACA,oBACA,gCACA,oCACA,4BAKA,sCACA,sDACA,cACA,mBACA,gCACA,oCACA,4BAEA,cAOA,aACA,kBACA,6BAEA,cACA,0CAEA,4BAEA,eAAuB,aAAqB,aAC5C,qBACA,+BAEA,GAOA,cACA,YACA,MAAuB,gBAAuB,SAE9C,6BAIA,uCACA,IASA,0BACA,YAAuB,QAA0B,SACjD,sCAIA,SACA,4BAAuC,EAAQ,WAC/C,gCACA,wCACA,GAEA,QAAmB,gBAAuB,SAC1C,kBAEA,QAOA,YACA,kBACA,wBACA,wBACA,OAAuB,QAAmB,OAC1C,gDAGA,UACA,GAMA,SACA,YACA,OACA,wBACA,6BACA,6BACA,iCACA,+BACA,gCACA,2BACA,8BAGA,YAAuB,gBAAuB,SAC9C,gCAGA,eACA,GAOA,gBACA,IACA,sCAGA,iEACA,GACA,EAEA,8BCrNA,eACA,UAGA,sBCJA,aA0BA,6BACA,kCACA,+CACA,gDACA,wCACA,iBAUA,CACA,0BACA,QACA,UACA,EACA,cACA,qCACA,gCACA,UACA,gBAEA,SAkBA,CApEA,UACA,QACA,UACA,aAEA,WACA,eACA,cACA,KACA,iCACA,+BAaA,IA8FA,UAhDA,kBACA,cAA8B,aAE9B,2CACA,oBAGA,sEACA,yBACA,0BAOA,oBACA,wBACA,IACA,UACA,qEACA,mBACA,MACA,6EAKA,yCAlBA,mBAEA,mEAGA,eAcA,+CAGA,2BACA,cACA,oCAEA,WACA,UACA,EACA,cACA,qCACA,UACA,gBAEA,uCAEA,sBCrHA,aAEA,Y,sBCFA,aAEA,6BACA,yDCHA,aAcA,iBACA,0BACA,uCAEA,YAAY,MACZ,sCACA,mBACA,QAAgB,MAChB,oDAGA,UACA,GA4BA,CACA,iBACA,yCACA,SACA,0BACA,cAAgB,MAChB,sEAEA,UACA,GAQA,CACA,iBACA,8BACA,QACA,0BACA,cAAgB,MAChB,4EAEA,UACA,GAMA,CACA,oBACA,IACA,mCAEA,iBACA,mBAGA,gBACA,SACA,SACA,SAEA,6BAEA,0BAGA,kFACA,oCACA,oCACA,+CACA,kCAEA,uDAGA,iBACA,0BAEA,GAMA,CACA,qBACA,IACA,mCAEA,iBACA,mBAGA,gBACA,SACA,SAEA,SAIA,6BAEA,0BAGA,kFACA,oCAEA,sEACA,uCACA,+CACA,kCAIA,uDACA,iBACA,0BACA,GAIA,CAqNA,kBACA,WACA,UACA,gBACA,QAEA,YAEA,cAIA,mBACA,aACA,UACA,SACA,GACA,gCAAoB,MACpB,eACA,cACA,WACA,WAKA,aACA,gCAAwB,MACxB,mBACA,iBACA,aACA,eAOA,GACA,KAEA,QAIA,gBACA,aACA,OAAmB,KAAc,GACjC,mBACA,iBACA,UACA,WAGA,IACA,QAAe,KAAc,GAC7B,aAEA,MACA,aAA4B,EAAO,MACnC,YACA,kBACA,gBAIA,UACA,gEACA,IACA,IAIA,CA9bA,SACA,iBACA,aASA,GAqbA,qCACA,gCAvMA,kBACA,WAEA,kBACA,mBAGA,gBACA,SACA,SACA,cAEA,yBACA,uBAGA,sDACA,sBACA,kBACA,kBACA,kBACA,8BACA,aAAa,MACb,sBACA,eACA,wBAEA,yBACA,gBACA,8BAEA,qBACA,gBACA,mBAEA,0BACA,qBACA,qBAGA,uCACA,iDACA,UAEA,eACA,aAAa,MACb,8CAGA,WAEA,GAOA,EA8IA,oCACA,8BA9IA,kBACA,WAEA,kBACA,mBAGA,gBACA,SACA,SACA,cAEA,gBACA,wBACA,cAAY,MACZ,eAIA,wBAIA,sDACA,sBACA,kBACA,kBACA,kBACA,8BACA,aAAa,MACb,sBACA,wBACA,yBAEA,yBACA,6BACA,+BAEA,qBACA,6BACA,kBAEA,0BACA,qBACA,qBAGA,oDACA,UAEA,eACA,aAAa,MACb,8CAGA,WAEA,GAMA,EAgFA,2BACA,6BACA,gCA5PA,kBACA,WAEA,kBACA,mBAGA,oBACA,SACA,SACA,MACA,QACA,gBAGgB,EAFhB,SACA,GACA,gBAAgC,KAChC,iBAEA,qCACA,iBACA,iBACA,MACA,qBACA,mBACA,sBACA,IAGA,0BACA,IACA,YAAyB,qCAGzB,kBAAyB,yCAEzB,QAEA,OACA,GASA,EA8MA,U,wBAtSA,kBACA,WAEA,kBACA,mBAGA,oBACA,SACA,SACA,MACA,QACA,gBAGgB,EAFhB,SACA,GACA,gBAAgC,KAChC,iBAEA,qCACA,iBACA,iBACA,MACA,qBACA,mBACA,sBACA,IAGA,yBACA,IACA,YAAyB,qCAGzB,kBAAyB,yCAEzB,QAEA,OAEA,sBC1MA,aAEA,UACA,UACA,WACA,WACA,WACA,UAEA,qBACA,CACA,sBACA,UAUA,UACA,QACA,mBACA,YACA,UACA,GAOA,sBANA,qBACA,oBACA,qBACA,+BACA,kBACA,EAGA,cAAkC,aAElC,SACA,eACA,oBACA,iBAEA,QACA,mBAIA,8CAHA,OAIA,UACA,4CAEA,oCAGA,UACA,oBACA,qDACA,qCACA,GAAS,KACT,oBACA,oBACA,CACA,8BACA,+BAGA,6BAEA,iCACA,qBACA,mBAA2B,QAA2B,OACtD,qCAEA,UACA,EACA,CAOA,gBACA,IACA,0DACA,uBACA,GAOA,YACA,iBAEA,SACA,8BACA,YACA,4BAIA,sBACA,EAMA,uBACA,YACA,KAAuB,YAAmB,OAC1C,gBAEA,6BACA,GAMA,wBACA,iBACA,0BAAuB,QAAsB,OAC7C,mBAEA,SACA,GAMA,kBACA,aACA,CAMA,iBACA,aACA,CAMA,wBACA,iCACA,IAMA,cACA,eACA,WAMA,SACA,OACA,MACA,kBACA,kBACA,iBACA,kBACA,cACA,SAEA,EAEA,eACA,qBACA,uBAEA,eAEA,gBACA,YACA,+BACA,mBACA,mBACA,eACA,YAA+B,QAAmB,OAClD,QACA,iGAGA,gBACA,mBACA,GACA,CAEA,OACA,GAEA,iCACA,oBACA,+BACA,6BAAuB,YAAmB,OAC1C,gBAEA,oCACA,SACA,EAEA,8BCtNA,aAEA,eAEA,OAUA,mBACA,MACA,8CACA,uBAEA,+DACA,eACA,aAEA,IAEA,WACA,eAA2B,KAAU,GACrC,gBAA+B,KAAa,GAC5C,aACA,YACA,eAIS,UACT,eACA,mBAEA,2GAA2B,QAAc,EACzC,mBAAmC,KAAa,GAChD,aACA,YACA,eAIA,KAEA,CACA,+BAEA,kCAGA,wDACA,mBACA,eAEA,kBACA,KAEA,WACA,QACA,KACA,KAAuB,QAAkB,OACzC,mBACA,aACA,YACA,YACA,cAEA,aACA,MACA,KAEA,OACA,KAGA,cACA,YACA,YAEA,gBACA,wBACA,qBACA,2BACA,2BAEA,eAAuB,KAAO,GAC9B,kBACA,iBAEA,qBACA,qBAGA,cACA,aACA,oBACA,EAkBA,cACA,IACA,mCAEA,8BACA,6CAAsD,CAEtD,gCACA,KAKA,UACA,sBACA,eACA,WACA,cAAuB,KAAO,EAC9B,4BACA,4BAEA,YACA,SAAmB,KAAO,EAC1B,yCAEA,UACA,GAKA,UACA,sBACA,eACA,WACA,cAAuB,KAAO,EAC9B,4BACA,4BAEA,YACA,SAAmB,KAAO,EAC1B,yCAEA,UACA,GAEA,mBACA,GACA,6BACA,mDACA,8CACA,8CAEA,OACA,MACA,MACA,MACA,MAEA,yBACA,qBAEA,YAAiD,MAAc,UAC/D,uBACA,IAEA,aAEA,yBACA,qBAEA,QACA,OAEA,WACA,YAEA,gBACA,uCACA,0BAEA,OACA,SACA,eACA,eACA,mBACA,mBAEA,GACA,EAEA,QACA,KACA,eACA,iBACA,0BACA,yBACA,0BACA,yBACA,gCACA,mCACA,wCACA,mCACA,iBACA,mCACA,yCACA,aAEA,6BClOA,mBACA,cACA,+BCFA,aAEA,qCACA,4BACA,wBACA,0BACA,qBACA,uBACA,MACA,gCAEA,KACA,6BACA,4CCbA,CA4EA,uBACA,YACA,KACA,WAA0B,SAC1B,yBACA,oBACA,IAGA,4BACA,IAEA,uBACA,QACA,YACA,gDACA,0EAGA,WACA,MAGA,EAIA,EACA,GAEA,iBACA,QACA,SACA,sBAAwB,OACxB,SAGA,SACA,IAEA,0BACA,YACA,OAAgB,OAEhB,0EAEA,UACA,GAOA,CACA,qBACA,kBACA,qBACA,UAAkB,OAAM,KACxB,iBACA,mBAAsB,OACtB,oCAEA,GACA,OACA,GAyBA,CArKA,SACA,QAEA,QACA,YACA,aACA,aACA,GA+JA,UA5JA,kBACA,OAAuB,SAEvB,8DACA,iCAGA,yFACA,+FACA,iDACA,iCACA,oFACA,iCACA,2CACA,0BAGA,0KAEA,4BACA,SACA,gBACA,8BACA,eACA,EACA,MACA,sDAGA,wBAIA,yBAAgB,MAAO,KACvB,qBACA,eACA,WACA,KAAuB,KAAgB,GACvC,mBACA,2BAEA,GACA,mBACA,mBAGA,2BACA,2BACA,0BACA,4BAEA,GAEA,eACA,aAAyB,QAAO,KAChC,IACA,aAAuB,KAAgB,GACvC,yBACA,IACA,2BACA,4BACA,EACA,OACA,sBC1EA,aAEA,QACA,OACA,QAEA,KACA,YACA,aACA,aACA,MACA,gBASA,aA2DA,UA1DA,kBACA,OAAuB,OACvB,8DACA,iCACA,8GACA,iCACA,oFACA,iCAEA,2EAGA,MAFA,GAGA,0BAA+B,iBAG/B,qCAEA,iEACA,mBACA,mBACA,oBAGA,KACA,qBAGA,OACA,+CACA,yBACA,KAAuB,QAAc,OACrC,gBAA2B,YAAiB,OAC5C,eACA,oCAGA,eACA,+BACA,qBACA,aACA,eACA,CACA,8BACA,eAAsB,mBAA0B,QAChD,IACA,aAAuB,QAAc,OACrC,6BACA,aACA,EAEA,OACA,2BAA6B,iBAG7B,YACA,kDC7EA,aAgBA,qBAEA,qBACA,SAEA,IACA,WACA,WACA,gDACA,KAEA,kBAIA,MACA,kEACK,kDACL,qCACA,wCACA,yBACA,yBACA,OACA,sBAGA,gCACA,6CACA,wBACA,GACA,IAEK,OACL,eACA,6CACA,gBACA,GACA,SACA,eAEA,GAEA,4BACA,wDAEA,yCAEA,4DAEA,YACA,OAGA,iBAFA,mBAGA,qBAGA,uCACA,SACA,SAGA,gCAEA,+BACA,+BAEA,iEAEA,qDAEA,qCAEA,YAEA,kBACA,QA4QA,yBACA,aACA,eACA,WACA,KAAmB,IAAO,EAC1B,4BACA,iCAEA,aACA,sBACA,iBACA,MAA2B,KAAO,EAClC,yBAEA,aACA,EACA,qBACA,QACA,SAA2B,KAAO,EAClC,2BAEA,WACA,EAEA,GAEA,yBACA,mBACA,wBACA,GACA,EAEA,2BACA,mBACA,uBACA,GACA,EAEA,6BACA,WACA,UAAkC,SAAQ,EAC1C,2BAEA,UACA,GAEA,4BACA,2BACA,SAEA,4BACA,iBACA,WACA,KAAmB,IAAgB,EACnC,SACA,OAEA,aACA,GAhaA,mCACA,sCAEA,oBACA,QACA,kBACA,gBACA,2BACA,gBACA,aACA,OACA,gBACA,UAgFA,iCACA,uBACA,kBACA,uBACA,OACA,gCACS,uBACT,kEAEA,gCACA,4BACA,aAAuB,IAAO,MAC9B,oBACA,aAA2B,IAAO,EAClC,0DAEA,IACA,OACA,IACA,iBAEA,0BAEA,gCACA,UACA,qBAEA,oCACA,MAEA,cACA,qBACA,6BACA,4BAEA,uBACA,MAAmB,SAAY,MAC/B,sBACA,aAAuB,SAAY,EACnC,kCAEA,OACA,OACA,sCAEA,YACA,GAEA,mCACA,YACA,UACA,4BACA,KAAe,SAAY,EAC3B,iCACA,KAAmB,SAAY,MAC/B,kBACA,kBAAuB,SAAqB,WAC5C,cAEA,sDACA,KAEA,iCACA,GAEA,qCACA,SACA,4BAEA,gDACA,QACA,QACA,eACA,sBACA,KAAmB,IAAO,EAC1B,0BAGA,uCAEA,oBACA,iEAEA,2BAEA,4BACA,oCACA,GAEA,iCACA,SAEA,KAEK,mCAEL,IACA,GACA,EAEA,EAmBA,MAlBA,qFACA,qDACA,2BACA,+EAEA,oEACA,yCACA,sEACA,uBACA,GACA,wJAIA,gBAEA,mBAIA,CAIA,YAHA,YAKA,mCACA,YACA,YAEA,gCAEA,WACA,6BAEA,oBACA,WACA,WACA,WACA,WAEA,SAAkB,MAAW,OAC7B,QACA,MACA,aACS,UACT,aAEA,KAAsB,MAAW,OACjC,QACA,EACA,aACa,UACb,aAGA,4CAEA,OACA,qBACA,yDAGA,GACA,CAEA,+BAEA,IAEA,+BACA,UACA,0BACA,QAGA,eAEA,0CACA,sBACA,KAAmB,SAAY,MAC/B,iBACA,aAAuB,WAAY,EACnC,oBACA,kDAEA,OACA,OACA,IAEA,+CAEA,WAEA,WAEmB,EAHnB,EAGA,SAA+B,EAC/B,cAAuB,SAAY,EACnC,6CACA,KACA,MACA,kBAKA,UAEA,IAEA,mCACA,IACA,wBACA,IAEA,MACA,WAEA,4EACA,OACA,6BACA,qBACA,EACA,EACA,wBAEA,IAEA,oCACA,eACA,sBAEA,qCACA,YACA,SACA,wBAEA,IACA,CAEA,EACA,6CACA,gBACA,aACA,SACA,IAAmB,IAAO,EAC1B,SAEA,YACA,GAEA,gCACA,CACA,WAEA,yBACA,eAEA,KAAmB,EADnB,IAC0B,EAC1B,mCACA,wCAEA,gBACA,IA8DA,e,kDCtIA,kCACA,aACA,2CAEA,UACA,GAnSA,wCAEA,OACA,iBAA2C,KAC3C,mBACA,SACA,EAEA,6DADA,UAGA,qBACA,SACA,MACA,SACA,aACA,yCACA,qBAA2B,IAAU,EACrC,cAA+B,MAAa,EAC5C,WACA,kDACA,GACA,oCAIA,GACA,wCAEA,UAEA,eACA,WACA,eACA,gBACA,oBACA,CAEA,oBACA,oBACA,gBAAwD,gBACxD,cAAuB,IAAS,EAChC,cAEA,SACA,EAEA,QACA,cACA,KAEA,YACA,oBACA,gBAAuB,SAAe,SACtC,iBACA,mBAA2B,SAAkB,QAC7C,uBAEA,EACA,OACA,EAEA,WACA,yBACA,OAEA,cACA,qBAEA,YACA,0CACA,wBACA,EAIA,GADA,QAEA,GACA,CAEA,kBACA,sBACA,IAEA,WACA,uBACA,OAEA,SACA,yCACA,EAEA,WACA,uDACA,GACA,0CAEA,sCAEA,GACA,IAEA,QACA,kBACA,mBAEA,kGACA,SAEA,kBACA,uCACA,qCACA,YACA,6BAEA,IACA,EACA,GACA,CACA,GACA,CAEA,oBACA,cACA,YACA,YACA,SAEA,wBACA,oCAEA,oDACA,qCACA,gCACA,IACA,EACA,GACA,EACA,GACA,CAEA,kBACA,yCACA,SACA,0BACA,oBACA,SACA,wDACA,OACA,IACA,2BAEA,0BAIA,OACA,iBACA,sBACA,IAEA,cACA,cACA,oBACA,WACA,WACA,SACA,uCACA,aACA,OACA,OACA,GACA,IACA,EACA,IAAgB,iBAChB,SAEA,gBACA,wBACA,2BACA,+BAEA,IACA,IACA,EAEA,2BAEA,iBACA,uDAEA,eAIA,sBASA;;;;;CAPA,uBAcA;;;;;wBAUA;;;;;;;;iBAOA;;;;;gBAOA;;;;;eAOA;;;;;EAcA,oPAEA,mBACA,qBAAmB,aAAqB,OACxC,wEAA0F,6BAC1F,oFAAsG,iCACtG,oFAAsG,iCAEtG,+DAA+E,cAE/E,MAEA,GAEA,uBAMA,+NACA,yBACA,GAAC,GAED,iBACA,mBAAmB,WAAmB,OACtC,oEAAsF,6BACtF,2DAA2E,YAE3E,uBC5RA,aA4BA,aACA,qBAAmC,YAEnC,sDACA,sBACA,CAMA,CAtCA,UACA,gBAEA,MACA,GACA,MACA,eACA,GACA,yBACA,kBACA,iBACA,OAeA,cAaA,gCACA,kBACA,uBAEA,sDACA,2BAEA,sDACA,iBACA,qBACA,mBACA,8BACA,mBACA,cAAuB,UAAY,EACnC,2BAEA,0BAEA,cAAuB,aAAY,OACnC,mBACA,MAAuB,UAAY,EACnC,kBAEA,iCACA,OAAuB,UAAY,EACnC,yFAEA,IACA,CACA,aAEA,SACA,UACA,OAEA,yCACA,SACA,yBACA,eACA,cAAmB,KAAO,GAC1B,YAEA,aACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,KAEA,+DACA,QACA,KAAmB,KAAO,GAC1B,gDACA,6FACA,QACA,gDACA,+CACA,UACA,UACA,gBACA,sCACA,iCAEA,uBACA,iDAEA,0BAEA,8CACA,UACA,sCACA,SACA,MACA,MACA,QACA,yBACA,gBACA,6BACA,yEACA,yEACA,mBACA,2CACA,6CACA,QACA,CAEA,CACA,KACA,UAEA,KACA,CACA,sBACA,8BAGA,6CAGA,kCACA,mBACA,cAAuB,UAAY,OACnC,YACA,aAA2B,KAAO,GAClC,0CACA,GACA,CAMA,IACA,OACA,MACA,eACA,wBAAe,UAAY,EAC3B,kCACA,0BACA,gBACA,yBACA,iCAIA,YACA,UACA,aACA,mBAIA,QACA,WAOA,EACA,kCACA,uBACA,kBACA,CAOA,EACA,+BACA,kDACA,4FACA,+BAEA,uBAEA,EAOA,EACA,oCAEA,0BACA,4BAEA,kBACA,2CAEA,SAAmB,YAAmB,OACtC,sBAGA,gBAAmB,UAAY,EAC/B,6EAGA,SACA,GAUA,EACA,gDACA,eACA,UAAe,UAAY,EAC3B,0CAEA,UACA,GAQA,EACA,8BACA,sBACA,6BAEA,sBAEA,EAMA,EACA,qCACA,kDACA,+HACA,0GACA,iBAMA,EACA,kBACA,MACA,gBACA,2BACA,eACA,sCACA,kBAEA,kBACA,iBACA,2BACA,kBACA,oBAEA,oBACA,cACA,KACA,cACA,YACA,EAKA,EACA,6BACA,kDACA,qDACA,8BAAoC,eACpC,kBACA,gBACA,OACA,uCAGA,oBACA,mBACA,6BAEA,SACA,GAEA,uCACA,iCACA,gDACA,WAAmB,OAAqB,OACxC,6EAEA,WACA,KAEA,2BC1UA,aAQA,iBAAiD,mBAA0C,yBAA4D,oCAEvJ,CAGA,iBACA,OACA,QACA,SACA,eACA,6BACA,CAEA,CA2DA,cACA,oDACA,8BACA,eACA,eACA,eAEA,IAKA,cACA,iBACA,WACA,YACA,oBACA,wBACA,wBACA,wBACA,eACA,GAnGA,qCACA,CACC,WAED,gBAAiC,mBAA2C,YAAgB,WAAkB,OAAO,WAA2B,qBAAwD,kBAAgC,kCAAuD,6CAA6D,GAAE,0BAAyD,4BAAqE,cAA6D,IAAoB,EAAG,CAAE,OAKljB,eAWA,cACA,wEAEA,UAEA,+BACA,aACA,GAEA,cACA,KACA,yBACA,eACA,iBACA,gBACA,gBACA,aAA2B,KAAU,GACrC,yFAEA,IACA,iBAA2B,KAAU,GACrC,OAEA,KAKK,GACL,KACA,4BACA,UACA,oCACA,CAKK,GACL,KACA,2BACA,2BACA,eACK,GACL,KACA,uBACA,aACA,0CAEA,YACA,OAGA,KACA,EAAC,IAED,gBAWA,OACA,MACA,SAWA,oCCtGA,WACA,CASA,0BAgBA,QACA,SAAgB,OAAc,OAC9B,cAEA,WACA,EAGA,IArBA,8BAEA,UAMA,aAIA,uCAoBA,uBACA,OACA,oBAEA,qBACA,CAGA,eAlBA,CACA,kEAGA,yEACA,kDACA,EAGA,EASC,+BCrDD,+BCAA,UACA,WACA,6CAEA,yBAOA,qBACA,WACA,IAEA,KACA,GAEA,EACA,CAYA,6BACA,IACA,OACA,cAEA,GACA,cAEA,GACA,qBAEA,+BACA,iBAEA,WACA,kBACA,GACA,mBAEA,SAGA,kDACA,EAOA,uBACA,OACA,eAEA,WACA,wBACA,GAOA,oBACA,QACA,SACA,eAEA,SACA,SACA,cACA,SACA,WAEA,QAEA,GACA,EAcA,uBACA,IACA,UACA,eAEA,SACA,SACA,WACA,IACA,EAOA,uBACA,IACA,UACA,eAEA,cACA,iDACA,WAEA,KACA,EAOA,oBACA,oBACA,OACA,cAEA,gBACA,CACA,mCAAsD,kBAAmC,cAA0B,aACnH,UACA,GAAK,cACL,UACA,kBAAqC,WAAW,GAChD,WACA,qBAEA,WACA,GAQA,uBACA,IACA,OACA,cAEA,iBACA,KAGA,yBACA,aACA,GAOA,uBACA,iBACA,MACA,cAEA,iBACA,QACA,aAEA,cACA,gBACA,gBAAoC,WAAW,GAC/C,WACA,aAEA,uBACA,SAOA,uBACA,gCACA,MACA,cAEA,oBACA,2BACA,QACA,aAEA,wBACA,eACA,gBAAsC,WAAW,GACjD,WACA,IACA,8BACA,OACA,sBAGA,UACA,GACA,WACA,IACA,2BAAkD,wBAAsC,mBACxF,iBAEA,WACA,GAEA,0BACA,WACA,OACA,cAEA,SACA,WACA,aACA,QACA,gBACA,QACA,MACA,GACA,QACA,CACA,KACA,eACA,EAEA,uBACA,iBACA,OACA,cAEA,SACA,UACA,SACA,YACA,KACA,UACA,WACA,0BAEA,cACA,OACA,WAEA,gBACA,eACA,GAEA,cACA,gBAiBA,mBACA,UACA,QAEA,gBAnBA,UAEA,cAEA,cAEA,cAEA,iBAEA,eAEA,gBAEA,iCAMA,8BACA,IAEA,6BACA,2BACA,IAEA,8BACA,mBACA,EAEA,oCACA,QACA,0BAEA,mCACA,8BACA,IAEA,mCACA,8BACA,IAEA,iCACA,2BACA,IAEA,sCACA,8BACA,IAEA,+BACA,aACA,QAEA,+BACA,OACA,sBAEA,8BACA,mBACA,MAEA,+BACA,IACA,iBACA,8BACA,GACA,EAEA,iCACA,yBACA,EAEA,mCAEA,mCAEA,qCAEA,mCAEA,wCAEA,MAEA,EAEA,mBAEA,iFAMA,GAAG,iBACH,OACA,EAEA,EAAC,+BCtXD,aAoGA,cACA,wBACA,WAAkB,QAAyB,SAC3C,mBAGA,eAAe,QAAmB,SAClC,cAAsB,WAAsB,SAC5C,qBAIA,UACA,GASA,CAxHA,cAUA,MA0MA,UACA,CACA,mBA3MA,eACA,IACA,qCAGA,yFACA,YAEA,OACA,KAAkB,WAAkB,cACpC,UACA,eAAsB,KAAgB,KACtC,gBAGA,WACA,GACA,IAEA,OACA,GAcA,EA0KA,wBAzKA,eACA,IACA,qCAGA,qFACA,iBACA,MAAmB,QAA6B,OAChD,kBAGA,WAAc,QAAkB,WAChC,cAAsB,QAAgB,KACtC,oBACA,qBAIA,UACA,GAWA,EA4IA,wBA3IA,YACA,kCACA,WACA,KAAkB,WAA2B,SAC7C,cAAsB,QAAwB,SAC9C,iBACA,MAIA,SACA,GASA,sBAwHA,EACA,mBAjGA,YACA,kCACA,WACA,KAAkB,QAAmB,SACrC,cAAsB,WAAsB,SAC5C,iBACA,MAIA,SACA,GAUA,sBA6EA,EACA,gBA7EA,eACA,QACA,iBACA,WACA,MAEA,QACA,MAGA,mCACA,WAEA,OAAmB,QAAgB,QACnC,IACA,aAAuB,QAA2B,SAClD,oBAEA,WACA,EAEA,OACA,GAQA,EAgDA,MA/CA,eACA,IACA,OACA,QAGA,YAEA,oBACA,UACA,OACA,wBACA,yCACA,0BACA,UAAwB,aACxB,+BAIA,0BACA,UACA,QAAwB,aACxB,mBAKA,YACA,sCACA,UACA,QAAwB,aACxB,mBAIA,SACA,qBC5LA,aAqDA,yBACA,yBA8BA,mBACA,GAEA,UA/BA,sBACA,MAGA,MADA,WAGA,cACA,+BAGA,MACA,SAEA,aACA,aACA,UACA,MAEA,KACA,KACA,KACA,KACA,KAEA,KACA,KAEA,cAKA,gBAEA,qBACA,aAEA,kBACA,GAEA,UACA,QAEA,SACA,OACA,MACA,EAEA,aACA,qBACA,UAGA,mBAEA,OACA,MAEA,MACA,SACA,UACA,IACS,WACT,SACA,MAGA,kBACA,cACA,EAEA,OACA,GAWA,CACA,yBACA,UAEA,sBACA,+BAGA,MACA,MAHA,WAMA,OACA,SAEA,cACA,aACA,OACA,SACA,MACA,EAEA,SAGA,KAEA,KACA,KAEA,cACA,2BACA,+CAEA,IACA,KACA,KAGA,yBACA,GAEA,UACA,QAEA,SACA,OACA,MACA,KACA,CAEA,IACA,SACA,GAGA,8BACA,OAEA,QACA,MAEA,MACA,SACA,UACA,IAEA,WACA,MACA,EAEA,KAEA,OACA,GAUA,CACA,sBACA,0CACA,GAEA,uBAnOA,iBACA,oBACA,iBACA,wBAGA,oBACA,kBACA,4BAEA,iEAEA,uCACA,6BACA,yBAEA,0EACA,2BACA,yBAGA,2CACA,SACA,QACA,MACA,MACA,EAEA,0CACA,uCACA,yBAEA,kDACA,0BAEA,+EAEA,qDAEA,2BACA,EAWA,EAiLA,W,mBC7PA,aAEA,MASA,WACA,kBACA,yBACA,QACA,WAAmB,OAAiB,OACpC,uBAEA,QACA,KAhBA,WAOA,kBCRA,CACA,uBAAe,EAAS,UACxB,WACA,IACA,EACA,QACA,EAEA,SACA,EAEA,U,eCbA,aACA,QACA,MACA,SAEA,0BACA,aA4BA,WACA,UACA,EACA,WACA,qBACA,WAA2B,EAAS,OACpC,aACA,SACA,QACA,QACA,QACA,CAAS,KACT,CACA,gBACA,GACA,EACA,YACA,oBACA,KACA,GACA,sBACA,MACA,qBACA,cACA,QACA,QACA,UACa,MACb,YACA,SAEA,aACA,cACA,SACA,QACA,QAEA,CACA,CACA,OACA,EAEA,UAtE8B,YAC9B,oBACA,YACA,YACA,cACA,MAGmB,QAAnB,MAA0B,EAC1B,YACA,iBACA,EAIA,SAAe,KAAO,EACtB,gBAIA,UAAe,QAAc,OAC7B,qBACA,UACA,aACA,GAGA,KA4CA,8BACA,QACA,eACA,aAEK,gBACL,6BACA,QACA,YACA,SACA,WAGA,6BAEA,8BCxFA,aACA,OAMA,iBACA,oBACA,uBAEA,mDACA,uBAEA,uEACA,cAEA,CAMA,eACA,eACA,IAAuB,gBAAwB,OAC/C,cAA2B,gBAAwB,OACnD,4BACA,qBAIA,eACA,EAMA,kBACA,WACA,IAAuB,gBAAwB,OAC/C,cAA2B,gBAAwB,OACnD,sBAGA,SACA,EACA,EAEA,4BCpDA,CACA,QACA,OAwDA,IA0cA,E,QAxcA,gDAEA,QAKA,KACA,oCAAwB,aACxB,gBAKA,QAEA,cACA,aACA,qBACA,iBACA,WACA,WACA,iBAGA,OAVA,2BAWA,aAEA,0EACA,uBACA,cAEA,EAEA,MAEA,uDACA,QACA,yCACA,oCACA,YAGA,gDAEA,aACA,SACA,SACA,SACA,SACA,SACA,SACA,SACA,SACA,SAOA,MAzDA,2BA0DA,kBACA,SAAwB,MACxB,aACA,OACA,EAGA,IACA,gBAAgB,aAChB,KACA,sBAIA,cACA,OAEA,SAEA,iCAIA,mCACA,wBACA,GAGA,0BAMA,oDACA,0DAIA,yBACA,iBACA,6FACA,IAIA,OAEA,IADA,UAIA,8BACA,QAGA,MAGA,cACA,kBACA,GAEA,MAIA,IAHA,2DAQA,mDAWA,oBACA,iBAAoB,aACpB,kBAEA,qBAEA,aAAoB,aACpB,6DAIA,iCAIA,oDAEA,cAGA,mCACA,kFAEA,sBACA,iBAA4B,aAC5B,kBAGA,iBACA,0BAEA,6BAGA,sDACA,IAGA,qFAEA,QAEA,WACA,MACA,MACA,MACA,MAEA,iDACA,0DAGA,EAEA,IADA,0BAGA,SACA,iCAEA,UACA,qDACA,WAKA,eACA,GACA,4DACA,2DAIA,GAEA,IADA,0BAGA,QACA,kCAEA,IACA,gBACA,QAIA,WAKA,+DAEA,4BACA,6BACA,GAEA,gDACA,0DA+BA,EAAgB,SAChB,GAEA,oCAyBA,WACA,aAEA,mCAEA,uBAEA,iCAEA,SAAuB,GAAM,QAE7B,qCACA,0BAGA,KACA,wBAEA,IAIA,wDACA,UAAgC,MAChC,uBAIA,OACA,wBAEA,2DACA,UAAgC,MAChC,uBAGA,EAGA,WAEA,GAEA,OAEA,GAGA,sCAYA,sBAGA,kBACA,gCAIA,uEACA,KAEA,EAEA,sDAoCA,WACA,aAEA,UAMA,wBAGA,qBAEA,gCAIA,kCAIA,yBAIA,mDAEA,oBAIA,6DAGA,yCAGA,YAAgB,sCAEhB,GAIA,oBCpgBA,aAEA,0BACA,YACA,sBACA,iBACA,kBACA,cACA,oBACA,aACA,mBACA,iBACA,iBACA,cACA,qBACA,kBACA,qBACA,qBACA,gBACA,iBACA,yBACA,sBACA,oBACA,mBACA,wBACA,wBACA,qBACA,mBACA,kBACA,iBACA,kBACA,eACA,eACA,gBACA,+BACA,iBACA,iBACA,kBACA,iBACA,qBACA,gCACA,gBACA,kBACA,gBACA,cACA,iCC7CA,uBACA,CAGU,UAFV,MACA,SACA,IAAkB,EAClB,mDAEA,aACA,gBCRA,uBACA,aACA,SACA,IACA,KACA,KAAmB,KAAS,EAC5B,yBACA,QACA,KACA,OAGA,gBACA,gBCbA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,wBAEA,oBACA,iBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,mCAEA,UACA,iBCPA,uBACA,aACA,SACA,IACA,KAAmB,KAAS,EAC5B,wBACA,OACA,MAGA,SACA,iBCXA,uBACA,CAGU,UAFV,MACA,SACA,IAAkB,EAClB,8DAEA,eACA,oBCRA,aAEA,cAEA,uBACA,cACA,iBCNA,uBACA,CAGU,UAFV,MACA,SACA,IAAkB,EAClB,oDAEA,cACA,gBCRA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,wBAEA,UACA,iBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,uBAEA,aACA,gBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,yBAEA,aACA,gBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,wBAEA,yBACA,iBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,cAEA,SACA,iBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,mCAEA,UACA,iBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,sFAEA,SACA,iBCPA,uBACA,aACA,SACA,IACA,KAAmB,KAAS,EAC5B,wCACA,yCAEA,kBACA,gBCTA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,oCAEA,WACA,iBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,4BAEA,UACA,iBCPA,uBACA,aACA,SACA,IACA,KACA,KAAmB,KAAS,EAC5B,gBACA,eACA,gBAEA,mBACA,iBCXA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,6DAEA,YACA,iBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,oCAEA,SACA,iBCPA,uBACA,CAGU,UAFV,MACA,SACA,IAAkB,EAClB,uBAEA,UACA,iBCRA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,wBAEA,yBACA,iBCPA,yBACA,CAGU,UAFV,MACA,UACA,IAAkB,EAClB,qCAEA,wBACA,iBCRA,uBACA,CAGU,UAFV,MACA,SACA,IAAkB,EAClB,iCAEA,SACA,iBCRA,uBACA,CAGU,UAFV,MACA,SACA,IAAkB,EAClB,iCAEA,SACA,iBCRA,uBACA,CAGU,UAFV,MACA,SACA,IAAkB,EAClB,uCAEA,aACA,gBCRA,uBACA,aACA,SACA,IACA,KAAmB,KAAS,EAC5B,yBACA,yBAEA,cACA,gBCTA,uBACA,aACA,SACA,IACA,KAAmB,KAAS,EAC5B,yBACA,yBAEA,cACA,gBCTA,uBACA,aACA,SACA,IACA,KAAmB,KAAS,EAC5B,yBACA,gBAEA,aACA,gBCTA,uBACA,CAGU,UAFV,MACA,SACA,IAAkB,EAClB,uCAEA,UACA,iBCRA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,8DAEA,YACA,qBCPA,YAEA,yBACA,IACA,iBAEA,gBACA,UACA,KACA,KACA,KAAuB,KAAS,GAChC,WACA,UACA,yBAEA,+BAEA,kBCjBA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,sEAEA,WACA,iBCPA,uBACA,aACA,SACA,IAAmB,IAAS,EAC5B,6CAEA,UACA,qBCPA,aAEA,eACA,oBACA,cACA,sBACA,iBACA,oBACA,gBACA,iBACA,sBACA,kCCXA,YAEA,uBACA,cACA,qBCJA,YAEA,uBACA,cACA,qBCJA,YAEA,uBACA,cACA,qBCJA,YAEA,uBACA,cACA,qBCJA,YAEA,uBACA,cACA,qBCJA,aAEA,WACA,cAEA,uBACA,mBACA,aAEA,cACA,mBACA,WAAiB,QAAe,OAChC,kBACA,gBAGA,eACA,sBCjBA,YAEA,uBACA,cACA,qBCJA,aAEA,YAEA,iBACA,eACA,OAEA,wCACA,6BACA,GACA,CAEA,eACA,IACA,uCAGA,uDACA,EACA,EAEA,6BCtBA,UACA,YAEA,MAEA,aAEA,CAGA,oEACA,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,YACA,eACA,SACA,YAEA,MACA,KAGA,kCCrFA,aAaA,oBACA,QACA,aAAmB,QAAqB,OACxC,gBAAuB,WAAqB,OAC5C,sBACA,oBAEA,UACA,GAQA,CACA,oBACA,aACA,KAAmB,QAAqB,OACxC,gBAAuB,WAAqB,OAC5C,sBACA,oBAEA,UACA,GAQA,CACA,oBACA,YACA,KAAmB,QAAqB,OACxC,gBAAuB,QAAqB,OAC5C,uBACA,6BACA,OAQA,CACA,oBAEA,+BACA,WAAmB,QAAqB,OACxC,gBAAuB,QAAqB,OAC5C,uCAEA,eACA,GAQA,CACA,oBACA,gBACA,sCACA,QAEA,kBACA,WACA,GAEA,kBACA,eACA,OACA,2BAEA,eACA,wBACA,SACA,SAEA,yBAEA,GAEA,CApGA,SACA,QACA,SAQA,OA2FA,SACA,QACA,SAUA,qBA+HA,UA9HA,eACA,WAA8B,aAC9B,cAEA,UACA,2BACA,UACA,iBAAsB,GAAQ,QAC9B,cACA,eAA2B,KAAS,GACpC,qCAEA,IACA,CAIA,IACA,mCACA,UACA,iBACA,EACA,UACA,mBACA,EACA,UACA,kBACA,EACA,UACA,mBACA,EACA,UACA,eACA,EACA,MACA,6BAGA,uCACA,+CAEA,iDACA,OAAmB,QAAqB,OACxC,mBACA,WACA,QACA,SAEA,eAEA,CACA,MACA,kBAAuB,QAAiB,OACxC,mBAA+B,QAAiB,YAChD,QACA,sBACA,eACA,WACA,uBACA,mBAAmC,QAAsB,OACzD,6BACA,KACA,oBACA,eACA,WACA,uBACA,mBAAmC,QAAsB,OACzD,6BACA,KACA,8BACA,QACA,2BAGA,yBAEA,qBACA,GAGA,0BACA,gBACA,WAEA,EADA,gBAEA,OACA,mBAA2B,WAAiB,OAC5C,qCAEA,QACA,kBACA,eACA,kCAEA,QACA,kBACA,gBACA,mBACA,EAEA,UACA,EACA,WAEA,cAAwB,WAAuB,YAC/C,OACA,uBACA,qBACA,kBACA,eACA,KAA4B,YAA2B,OACvD,yBACA,0BAEA,0BACA,2CAEA,yCAEA,mBACA,WACA,GACA,CACA,WACA,qBChPA,aAaA,oBACA,QACA,aAAmB,QAAqB,OACxC,gBAAuB,YAAqB,OAC5C,qBACA,oBAEA,UACA,GAQA,CACA,oBACA,aACA,KAAmB,QAAqB,OACxC,gBAAuB,YAAqB,OAC5C,qBACA,oBAEA,UACA,GAQA,CACA,oBACA,YACA,KAAmB,QAAqB,OACxC,gBAAuB,QAAqB,OAC5C,sBACA,6BACA,OAQA,CACA,oBACA,YACA,KACA,KACA,KACA,KAAmB,QAAqB,OACxC,gBACA,cAEA,cAAmB,QAAqB,OACxC,gBACA,cAEA,iBACA,cACA,cACA,cACA,sBACA,IAQA,CACA,oBACA,YACA,KACA,KACA,KACA,KAAmB,QAAqB,OACxC,gBACA,cAEA,cAAmB,QAAqB,OACxC,gBACA,cAEA,iBACA,cACA,cACA,cACA,6DACA,OASA,CACA,qBACA,YACA,GACA,IAGA,kBACA,WAAmB,WAAyB,OAC5C,qBACA,4BACA,WAAmB,WAAyB,OAC5C,qBAEA,gBACmB,KAAnB,SAAkC,YAClC,IACA,aAAuB,QAAe,OACtC,UACA,sBACA,oBACA,KACA,aAAuB,QAAe,OACtC,sBACA,YACA,gBACA,YACA,QAEA,GACA,OACA,GAEA,CAaA,qBACA,YACA,KACA,KAAmB,QAAkB,OACrC,gBAAuB,SAAkB,OACzC,uCACA,QAEA,eACA,EAOA,CAhLA,SACA,QACA,SAQA,OA0IA,MACA,QAUA,UAwIA,UAtHA,eACA,kBACA,OACA,qBACA,gBACA,QACA,mCACA,UACA,iBACA,EACA,UACA,mBACA,EACA,UACA,kBACA,EACA,UACA,mBACA,EACA,UACA,eACA,EACA,MACA,6BAGA,uCACA,+CACA,0CACA,yBACA,0BACA,mBAAqB,QAAmB,OACxC,4BACA,wBAGA,kCACA,kBAGA,UAFA,MACA,gBAEA,IACA,KACA,aAAuB,QAAiB,YACxC,IACA,aAA2B,YAAoB,OAC/C,mBAAqC,YAAoB,OACzD,gFAGA,OACA,QACA,MAEA,GACA,OACA,EACA,sEACA,yEAEA,wCACA,+DACA,WACA,sDACA,6DAEA,uCACA,CACA,KACA,eACA,UACA,2BACA,eAA6B,WAA2B,OACxD,eACA,cAA4B,WAA0B,YACtD,IACA,aAAgC,WAA0B,OAC1D,UACA,8EACA,0BACA,KACA,QACA,MAEA,GACA,YACA,oBACA,kBACA,MACA,4BACA,sBACA,kBAEA,yBACA,6BACA,mBAA2B,QAAkB,OAC7C,uCACA,uCACA,wCAEA,wBACA,6BACA,mBAA2B,QAAkB,OAC7C,uCACA,uCACA,wCAEA,mCACA,oCACA,cACA,YACA,wBACA,GACA,cACA,EACA,OACA,sBCvSA,aAEA,aAEA,UACA,OACA,GAeA,UAbA,KACA,eACA,UAAkC,YAClC,gBACA,+BACA,KAEA,aACA,cACA,4BACA,QACA,gBCnBA,aAEA,QACA,QACA,WACA,QACA,GAoBA,UAlBA,KACA,eACA,UAAkC,YAElC,iBACA,uBACA,sBACA,KAEA,aACA,WACA,KAAuB,OAAc,OACrC,gBAEA,oDACA,OACA,gBCxBA,aAEA,QACA,OACA,oBACA,GAkBA,UAhBA,KACA,eACA,UAAkC,YAClC,gBACA,sBACA,QAEA,aACA,WACA,KAAuB,OAAc,OACrC,gBAEA,uCACA,SACA,gBCrBA,aAEA,QACA,OACA,SACA,GAoBA,UAlBA,KACA,eACA,UAAkC,YAClC,gBACA,oBACA,MAEA,aACA,WACA,yBACA,WAAuB,MAAU,KACjC,8DACA,kCAEA,cACA,EACA,oBCvBA,aAEA,aAEA,UACA,OACA,GAaA,UAXA,KACA,eACA,UAAkC,YAClC,gBACA,KAEA,aACA,qCACA,OACA,oBCjBA,aAEA,UAEA,KACA,OACA,GAeA,UAbA,KACA,eACA,UAAkC,YAClC,gBACA,+BACA,KAEA,aACA,cACA,4BACA,QACA,gBCnBA,aAaA,UAXA,KACA,aACA,+BACA,UACA,KAAuB,KAAS,IAChC,uBAEA,WACA,EACA,oBCXA,aAEA,UAEA,KACA,OACA,GAcA,UAZA,KACA,eACA,UAAkC,YAClC,gBACA,KAEA,aACA,cACA,4BACA,MACA,oBClBA,aAEA,aAEA,UACA,UACA,GAaA,UAXA,KACA,eACA,UAAkC,YAClC,mBACA,QAEA,aACA,4CACA,SACA,oBCjBA,aAEA,aAEA,UACA,UACA,GAcA,UAZA,KACA,eACA,UAAkC,YAClC,mBACA,QAEA,aACA,cACA,wBACA,SACA,oBClBA,aAcA,wBACA,eACA,iBACA,iBACA,mBACA,WACA,EAMA,CAxBA,UACA,aAUA,YAcA,+BACA,eACA,0CACA,WACA,QACA,wCACA,GAOA,EACA,0CACA,0CACA,OACA,UACA,SACA,OAEA,EAEA,MAAmB,OAAiB,OACpC,4EACA,2BAGA,kBAAmB,oBAA2B,OAC9C,wBAGA,sEACA,KAEA,6BC9DA,aAEA,cAQA,OAkEA,SAjEA,aACA,gBACA,oBAEA,MAAmB,KAAO,IAC1B,aAEA,aACA,GASA,EAiDA,cAhDA,gBACA,cAGA,uCAEA,YAEA,aAAuB,eACvB,MAAuB,OAAiB,SACxC,oBACA,yBACA,aAGA,gBAEA,MAEA,eAA2B,QAAO,OAClC,KAA8B,eAC9B,cAA+B,UAAiB,YAGhD,KAAuC,6BACvC,cAAmC,KAAO,KAC1C,wBACA,wBACA,aACA,UAKA,4CACA,iBAAiD,UAEjD,IAEA,WACA,KAEA,CAEA,qBACA,qBC1EA,aAWA;;;;;;;;;EAGA,kBACA,UACA,YACA,gBACA,iBACA,kBACA,EAEA,kBAEA,sBAGA,cACA,OACA,GAEA,SACA,eAEA,KACA,6BAGA,4BACA,yBACA,IAEA,2BACA,sBACA,mCACA,oCAEA,IACA,GAGA,QAzBA,uCAkDA,kBAvBA,gBAGA,IACA,sBACA,SAGA,UACA,wBACA,SAEA,OAEA,SAZA,SAaA,KAGA,MACA,4BAKA,cACA,uCACA,4CACA,wCACA,QACA,EAEA,0BACA,mBAEA,IACA,gBAGA,iBACA,gCACA,eAEA,gBAEA,GAEA,qBACA,MACA,GAEA,SACA,qCAIA,mDACA,aAEA,yBACA,YAEA,YAEA,GAEA,0BACA,gBAGA,IACA,gBAGA,kBACA,SAGA,iBAEA,gCACA,eAEA,gBAEA,GAEA,gBACA,mBAKA,IACA,IACA,GACA,GACA,GAEA,SACA,WAGA,YAEA,mBACA,IACA,eAKA,cAHA,eAIA,kBACA,mBACA,OAEA,yBACA,QAEA,iCACA,SAEA,IACA,GAEA,IArCA,IACA,GAEA,0BAmCA,gBACA,8BAIA,uBAEA,yCACA,mBAEA,qBAQA,YACA,kCAMA,iBACA,OACA,gBACA,aACA,YAGA,uBAZA,iBACA,OACA,WAEA,IAUA,IA5FA,UA8FA,MAEA,cACA,GAEA,iCACA,gBASA,mBASA,aACA,eACA,OAEA,KAEA,cAbA,sBACA,KACA,MAHA,GAIA,GACA,GAEA,UAOuB,QAAuB,WAC9C,qBACA,gBAEA,eAIA,uBAEA,sBACA,gDACA,WAKA,aACA,mBACa,KACb,kBAEA,oBACA,OAEA,QAIA,SAEA,gCACA,WAGA,0CACA,iBACA,QAEA,SAEA,KACA,cAGA,KAEA,IAtEA,IACA,GAEA,YACA,eAA0B,WAAc,EAGxC,GAgEA,UAAuB,KAAc,OACrC,gBAIA,YACA,YAEA,MAEA,SAAmB,4BAAkD,YACrE,iBACA,kDAGA,WACA,GAEA,+BACA,gBACA,OACA,WAEA,qCACA,CAEA,gBACA,OACA,WAEA,2BACA,CAEA,oDACA,GACA,CAGA,CAEA,aACA,MACA,8BACA,EAEA,YACA,iBAEA,mBAEA,qCACA,EAEA,gBAEA,oBAEA,kBAGA,YACA,yCACA,gBAEA,IACA,CAEA,iBACA,qBACA,EAEA,oBACA,wBAGA,UAAuB,KAAS,EAChC,4BAGA,qBACA,MAQA,kBAPA,qBACA,6CACA,iBAEA,kBAEA,KAGA,iBACA,kBAEA,iBACA,qBACA,MAEA,sBAEA,wBAEA,QAEA,4BACA,kBAEA,gDACA,qBACA,kBAEA,KAIA,OAEA,MACA,CAEA,sBAEA,wBACA,uBACA,yBAEA,MAEA,sBAGA,KAEA,aAEA,qBACA,0BAEA,OACA,QACA,GAEA,SACA,qBACA,0BACA,oBACA,SAEA,GAGA,IACA,sCACA,qBACA,KAIA,OAEA,MACA,CACA,GAEA,cAEA,WACA,gCC3cA,aAcA,eACA,CACA,kBACA,gBACA,iBAEA,QAWA,CA7BA,YAEA,aACA,WAQA,IAmBA,kCACA,eACA,qDACA,4CAEA,cACA,KACA,cACA,KAAkB,OAA2B,SAC7C,IACA,wBACA,cACA,IAKA,qBACA,eAAc,QAAmB,SACjC,gBAGA,+BACA,UAAc,OAA2B,SACzC,iBAGA,uBACA,eAAc,QAAuB,SACrC,UAGA,oCACA,cACA,eACA,EAOA,EACA,+BACA,mBACA,WAAkB,OAAoB,SACtC,oCAGA,WACA,EAMA,EACA,2CACA,sCACA,iBACA,aACA,MACA,oBAEA,KAAkB,QAA2B,SAC7C,UAGA,SAAc,OAA0B,YACxC,iBACA,YACA,OACA,QACA,MAEA,GAEA,OACA,GAMA,EACA,kBACA,IACA,yCAEA,+CACA,EAIA,EACA,6BACA,OACA,WACA,kBACA,cACA,eAEA,Q,mBCtIA,aAKA,aACA,qBACA,iBAEA,sBACA,MACA,8BAGA,iCACA,MACA,gBACA,GACA,YAEA,UAAe,KAAe,OAC9B,WACA,OACA,SAAmB,KAAO,QAC1B,WACA,OACA,SAAuB,KAAO,GAC9B,mBAEA,oCACA,WACA,EAEA,kBAEA,OACA,sCACA,UAAuB,KAAe,EACtC,gBAEA,CAEA,KACA,mBAGA,0CACA,GA7CA,WAEA,OA6CA,YACA,4BACA,aACA,CACA,mBACA,iBAEA,cACA,MAEA,iBACA,kBAGA,2CACA,aACA,cAEA,UAAmB,KAAe,EAClC,YAAuB,KAAW,QAClC,QAA2B,KAAO,GAClC,kCAEA,sBACA,GAGA,UAA+B,EAAQ,MACvC,YAAuB,KAAW,QAClC,WAA+B,KAAe,EAC9C,kCAEA,sBACA,GAGA,OACA,GACA,GAEA,6BCzFA,aAYA,iBACA,cAA8B,aAC9B,qBACA,oBAEA,yBACA,QACA,2BAGA,2CACA,oBACA,YACA,aACA,OACA,GAGA,SADA,MAIA,QAFA,oBAKA,iBACA,QAAmB,KAAO,GAC1B,YAAuB,KAAO,GAC9B,0BAGA,eACA,eACA,GAAK,KACL,iBACA,YACA,WAAmB,KAAO,GAC1B,YAAuB,KAAO,GAC9B,0BAGA,eACA,kBACA,GAEA,QACA,UACA,UACA,UACA,GAoCA,uBAEA,oBACA,MAEA,UAAe,KAAO,GACtB,qBAGA,cAAmB,EAAO,UAC1B,QACA,KACA,KAAmB,KAAO,GAC1B,qBAGA,QACA,wBACA,MAAuB,KAAO,GAC9B,qBACA,eACA,aAES,MACT,QAAuB,KAAO,GAC9B,aACA,iBAGA,iBACA,gBACA,IACA,WAGA,cACA,UACA,eACA,MAAuB,KAAO,GAC9B,YAGA,SAAuB,KAAO,QAC9B,WACA,eACA,wBACA,SAA+B,SAAY,EAC3C,uBACA,uBAEA,UACA,EAEA,QACA,KAAuB,KAAO,GAC9B,aACA,iBAGA,kBACA,OAAuB,KAAO,GAC9B,mBAGA,WAAuB,KAAO,QAC9B,WACA,UACA,OAA2B,UAAY,EACvC,iCAEA,oBACA,eACA,CACA,CACA,QACA,EAEA,QAAe,QAAW,OAC1B,wBACA,eACA,WACA,UACA,QAAuB,MAAQ,GAC/B,yBAGA,UAAuB,MAAQ,QAC/B,QACA,KAA2B,MAAQ,GACnC,6BAEA,WAA2B,MAAQ,GACnC,uBAEA,GACA,CAEA,QAAmB,MAAQ,GAC3B,kBAEA,CAEA,QAAe,KAAO,GACtB,qBACA,iBAGA,iBACA,QACA,EAEA,uBAEA,6BACA,qBACA,GAEA,UAAe,KAAO,GACtB,iBAGA,aAEA,SACA,KACA,iBAEA,WAAe,KAAO,QACtB,iDACA,SACA,MACA,2BAGA,KAGA,cACA,IACA,IACA,OAEA,SACA,2BACA,cACA,GACA,WAGA,sBACA,wBACA,aACA,YACA,UAA+B,KAAO,GACtC,aAGA,WAEA,SACA,OACA,KACA,MACA,YACA,MACA,KACA,QAA+B,MAAQ,GACvC,YACA,MACA,MACA,YACA,UACA,eACA,iBACA,aACA,SACA,mBACA,+BAEA,QAA+B,KAAO,GACtC,kBACA,iCACA,+BAIA,0BACA,aACA,aAEA,EACA,2BACA,GACA,SACA,UACA,CAEA,QAAe,QAAW,OAC1B,QACA,SACA,UAAuB,KAAO,GAC9B,YACA,QACA,SAIA,aACA,iBACA,WACA,MAAuB,KAAO,GAC9B,eACA,sBACA,eAGA,EACA,EAEA,uBAEA,QACA,QACA,iBACA,GAEA,aAAqB,SAAe,OACpC,QACA,KAAmB,OAAW,GAC9B,4BAGA,cACA,QACA,KAA0B,OAAQ,GAClC,yBACA,iBAGA,qBACA,IACA,eAGA,eACA,WAEA,MAAuB,MAAO,QAC9B,QACA,KAA8B,OAAQ,GACtC,uBAGA,YACA,MAA2B,OAAW,GACtC,uBAEA,GAEA,QAAuB,MAAW,QAClC,QACA,KAA8B,OAAQ,GACtC,uBAGA,YACA,MAA2B,OAAW,GACtC,uBAEA,GAEA,cACA,oBACA,EACA,CAEA,QAAe,KAAO,GACtB,YAAmB,KAAO,GAC1B,0BAIA,YAAsB,SAAc,EACpC,yBACA,WAA2B,MAAW,GACtC,sBAGA,UAAuB,OAAW,QAClC,QACA,KAA2B,OAAW,GACtC,uBAGA,+BACA,MAA2B,OAAW,GACtC,uBAEA,GACA,CAEA,EAEA,0BACA,WACA,KACA,QACA,iBACA,OACA,KACA,KACA,KACA,KACA,KACA,KACA,KACA,0BACA,YACA,MAEA,UAAe,KAAQ,GACvB,oBACA,oBACA,WAGA,oBAAoC,MAAQ,GAC5C,yBAIA,kBACA,QACA,MACA,iDACA,KACA,WAEA,gCAGA,MAGA,aACA,eACA,iBACA,WACA,EACA,QACS,oBACT,6BACA,mCACA,WACA,yBACA,iBACA,iCACA,aAEA,UACA,uBACA,eACA,gBACA,GACA,qBAEA,aACA,SACA,eACA,4BACA,UACA,SACA,yBACA,QACA,OAEA,SAA+B,KAAQ,GACvC,iBACA,iCACA,gCAGA,UAA2B,MAAQ,GACnC,kBACA,gCACA,gCAGA,UAA6B,OAAW,GACxC,kBACA,gCACA,gCAEA,EACA,kBACA,aACA,YACA,WAGA,OACA,KACA,CAAS,KACT,cACA,OACA,KACA,KACA,oBACA,4BAGA,YACA,SACA,MAA6B,OAAQ,GACrC,iBAEA,kDACA,eACA,iBACA,EAEA,IACA,oBACA,WACA,SACA,kBACA,OACA,SAEA,wBACA,OAAiC,OAAQ,GACzC,iBAEA,OACA,YACA,KAGA,OAEA,SACA,MACA,eACA,UACA,SACA,wCACA,2BACA,kBACA,yCACA,QACA,OACA,OACA,OAGA,uIAGA,QAGA,eAA2B,MAAQ,GACnC,kBACA,QACA,iBAIA,UAAuB,UAAY,eAEnC,MACA,kBACA,kBACA,wBACA,wCACA,IACA,aACA,OACA,OAIA,KAIA,QAjBA,oCAkBA,IACA,WAGA,WACA,SACA,QAEA,6BAGA,qBAJqB,OAKrB,SACA,SACA,SACA,OACA,OAEA,MAA+B,MAAQ,GACvC,+BACA,IACA,qBACA,iCAGA,mBACA,gCAGA,UAA+B,qBAAyB,GACxD,mCACA,GACA,sBACA,gCAGA,gBACA,gCAGA,UAAiC,OAAW,GAC5C,mCACA,GACA,sBACA,gCAGA,gBACA,gCAEA,EAEA,CACA,CAEA,IAIA,kBAAoB,EAAQ,MAC5B,cACA,UAEA,IACA,cACA,cACA,QAA2B,EAAQ,WACnC,mBACA,MACA,KAA2B,OAAQ,GACnC,2BAGA,OACA,YACA,MAEA,cACA,GACA,qCAEA,yBACA,eACA,yCACA,qBACA,cACA,qEAGA,uBACA,KACA,kBAAmC,OAAQ,GAC3C,iBAIA,EACS,SACT,eAEA,2CACA,kCACA,2CAEA,6CACA,sBACA,mBAGA,iBACA,aACA,QAA2B,EAAQ,WACnC,QACA,KACA,KAA2B,OAAQ,GACnC,8BACA,yBAGA,qBAEA,GACA,YACA,MACA,MAEA,cACA,GACA,6BACA,oBACA,iBAEA,kBACA,eACA,gDACA,oBACA,WACA,gFAEA,mDACA,oBACA,iBACA,sCACA,wDACA,oDAEA,oDACA,sBACA,mBAIA,wDACA,MACA,kBAAmC,OAAQ,GAC3C,+BACA,eAIA,EAIA,QAAe,KAAQ,GACvB,kBACA,UAAuB,MAAQ,GAC/B,uBAKA,cAAoB,MAAU,GAC9B,YAAqB,OAAW,QAChC,QACA,KAAyB,mBAAwB,IACjD,2BAEA,eACA,EAEA,GAEA,wBACA,QACA,gCACA,WACA,YACA,6BAEA,YACA,YACA,6BAEA,KAvwBA,cACA,YACA,UACA,iBAEA,oBACA,CAGA,oBAmDA,YACA,sBACA,aACA,CACA,4BACA,aACA,CACA,yBACA,yBACA,wBAEA,SACA,CACA,sBACA,aACA,UACA,UACA,eACA,OACA,UAAmB,KAAO,QAC1B,QAAuB,KAAO,GAC9B,gBAEA,gBACA,IACA,yBACa,IACb,2BAEA,IACA,OACA,GACA,GA6qBA,6BC3wBA,aAMA,aACA,qBACA,iBAEA,mBAEA,WACA,aACA,UACA,iBACA,aAEA,UAAe,KAAO,QACtB,QACA,SAAmB,MAAO,GAC1B,mBAEA,eACA,KACA,kBAEA,OAAuB,MAAO,GAC9B,gBAEA,kBACA,QAA2B,KAAO,QAClC,QACA,KAA2B,MAAO,GAClC,yBAEA,qBACA,OAA2B,MAAO,GAClC,yBAEA,GACA,CACA,SACA,EAEA,SACA,aACA,GA7CA,WACA,eAEA,WA4CA,YACA,kBACA,iBAEA,cACA,QAEA,iBACA,mBAEA,6CACA,6BAGA,qCACA,aACA,aACA,iBAEA,UAAmB,KAAO,GAC1B,YAAuB,KAAW,QAClC,QACA,KAA2B,MAAO,GAClC,0BAEA,qBACA,OAA2B,MAAO,GAClC,0BAEA,GAEA,WAAuB,EAAQ,WAC/B,QAAuB,KAAW,GAClC,4BAEA,WAAuB,KAAO,GAC9B,YAA2B,KAAW,GACtC,kCAGA,GAEA,iCACA,EACA,uBACA,mBACA,UAAuB,IAAa,EACpC,OACA,kBAGA,SACA,QACA,6BACA,YACA,OACA,mBACA,MACA,UAAmB,KAAO,EAC1B,YAAuB,KAAO,EAC9B,mBACA,SACiB,SACjB,cAEA,IAIA,QACA,GACA,wBACA,YACA,OACA,UACA,mBACA,aAEA,aAA6B,EAAQ,WACrC,QAAuB,KAAU,EACjC,gBAEA,iBACA,KAAuB,MAAa,GACpC,sBACA,QACA,KAA+B,MAAU,EACzC,0BAGA,qBAEA,OAA+B,MAAU,EACzC,0BAEA,GAEA,CACA,OACA,GACA,GAEA,6BCvJA,aAQA,iBACA,qBACA,oBAEA,qBAEA,OAEA,iBACA,WACA,uBAEA,UACA,2CACA,6CACA,sBAEA,cACA,MACA,WACA,UAiBA,iBAhBA,SAEA,qBACS,8FACT,OACA,kBACA,WACA,QACA,aACA,MACA,MACA,EAEA,4BAIA,gBACA,cACA,YACA,aAEA,qBACA,gCAEA,mCACA,8BAEA,2BAAyC,OAAS,QAClD,UACA,YACA,KAAuB,MAAO,GAC9B,4BAEA,mBACA,KACA,0BAEA,QAA2B,MAAO,GAClC,oBAEA,gBACA,CACA,YACA,GAEA,WAAuB,KAAO,QAC9B,sBACA,QACA,KAA2B,MAAO,GAClC,2BAEA,sBACA,OAA2B,MAAO,GAClC,2BAEA,GACA,eACA,GAEA,WACA,UAAuB,MAAO,GAC9B,uBAIA,aACA,YACA,QAA2B,KAAO,GAClC,wBAEA,mBACA,KACA,yBAEA,WAA+B,KAAO,GACtC,gBAEA,cACA,CACA,eACA,wBACA,WAA+B,KAAO,GACtC,YAEA,YAA+B,KAAO,GACtC,eAAmC,KAAO,GAC1C,2BAGA,cAA+B,KAAO,GACtC,0BACA,SAAmC,KAAO,GAC1C,uBAGA,GACA,IACA,aAA+B,KAAO,GACtC,mBAGA,GACA,CAEA,sBACA,MACA,mBAEA,QACA,cAEA,QACA,sBAEA,aAEA,KACA,QAAqB,MAAQ,QAC7B,QAAuB,KAAO,GAC9B,gBAEA,aACA,CACA,WAAyB,EAAQ,MACjC,mBACA,WAA+B,KAAQ,QACvC,QACA,KAA+B,MAAO,GACtC,2BAEA,sBACA,OAA+B,MAAO,GACtC,2BAEA,GACA,QAA2B,MAAO,GAClC,wBAEA,4BACA,OAA2B,QAAW,EACtC,gBAEA,CAAa,KACb,QAA2B,KAAO,GAClC,gBAEA,aACA,CAEA,CAEA,IACA,aAAuB,EAAQ,WAC/B,WACA,qBAA+B,KAAO,QACtC,QACA,QAAmC,KAAO,GAC1C,2BAEA,wBACA,UAAmC,KAAO,GAC1C,2BAEA,GAEA,QAAuB,KAAO,GAC9B,gBAEA,aACA,CAGA,eACA,KACA,iBACA,UACA,WAAuB,GAAS,QAIhC,OAHA,mEAIA,QACA,EACA,KAEA,YACA,KACS,MACT,WAA4B,MAAS,SAIrC,GAHA,mDAIA,8CACA,QACA,EACA,KAEA,MACA,MACa,UACb,KAEA,MACA,KAEA,GAEA,QAEA,KACA,WACA,cACA,YACA,QAA+B,MAAQ,GACvC,oBACA,cACA,SACA,UACA,QACA,kBACA,qBAEA,IACA,UAAmC,KAAO,GAC1C,mCACA,4CACA,cAIA,GACA,KACA,QACA,cACA,YACA,KAA2B,MAAO,GAClC,oBACA,cACA,SACA,UACA,aACA,iBACA,IACA,UAAmC,KAAO,GAC1C,mCACA,4CACA,cAIA,GACA,KACA,QACA,qIACA,kBACA,eACA,eACA,aACA,aACA,8BACA,eACA,OACA,WACA,6BACA,IACA,WAEA,cAEA,wBACA,SACA,MAA2B,SAAW,OACtC,YACA,UACA,SACA,QACA,cAEA,uBACA,2BACA,gBACA,qBACA,GACA,UAAmC,KAAO,GAC1C,mCACA,4CACA,cAGA,cACA,UACA,SACA,UACA,yBACA,gCACA,eACA,qBACA,aACA,SAAmC,KAAO,GAC1C,mCACA,4CACA,cAGA,EACA,UACA,KACA,GACA,KACA,QACA,IACA,oCACA,EACA,WAAmC,MAAS,GAC5C,wBAIA,YACA,oBAGA,eACA,iBACA,YACA,aACA,SAAmC,KAAO,GAC1C,kBACA,uBACA,eAGA,gBACA,SAAmC,KAAO,GAC1C,kBACA,uBACA,eAGA,GAEA,QACA,EACA,KACA,KAGA,EAEA,OACA,QACA,MACA,MACA,EAEA,QACA,UACA,UACA,UACA,UACA,GArYA,WACA,WACA,QACA,eAEA,iBAkYA,YACA,gBACA,iDACA,EACA,aACA,eACA,EACA,YACA,wBACA,yCACA,MACA,UACA,aAAsC,UAAQ,GAC9C,YACA,IAGA,WACA,GACA,gBACA,aACA,CAEA,iBACA,yDACA,EACA,2BACA,wBACA,uBAEA,SACA,CACA,4BACA,wBACA,uBAEA,SACA,CACA,sBACA,oBACA,EACA,oBAEA,aAEA,oBACA,qBACA,IAEA,UAAmB,KAAW,GAC9B,sCACA,GAEA,WAIA,gBACA,UAEA,gCACA,UACA,WACA,qBACA,UAEA,UAAmB,KAAW,GAC9B,YAAuB,KAAW,QAClC,QACA,KAA2B,KAAW,GACtC,2BAEA,eACA,EAGA,WACA,KAjCA,GAkCA,+BACA,0BACA,IACA,oBACA,aACA,UACA,gBACA,gBACA,0BACA,WAEA,UAAmB,KAAW,GAC9B,YAAuB,KAAW,GAClC,qCACA,qBAEA,IAKA,cAEA,QACA,gBACA,mBACA,OAEA,UAAmB,KAAW,GAC9B,YAAuB,KAAW,QAClC,QACA,KAA2B,KAAW,GACtC,2BAEA,eACA,EAGA,OACA,GACA,GAEA,6BCjgBA,aAUA,cACA,yBACA,kBACA,MASA,CAeA,iBACA,yBACA,qBACA,wDACA,IAvCA,WAEA,WACA,SACA,UACA,SACA,eAeA,gBASA,EACA,8CACA,UACA,OAQA,UACA,8BACA,eACA,KAEA,UACA,4BACA,MACA,0BACA,MACA,kBACA,MACA,mBACA,MACA,yBACA,OACA,WACA,QACA,eC3DA,oBACA,oCACA,+BCJA,aAEA,WAkBA,UAhBA,eACA,iBACA,gBACA,eACA,CAEA,WACA,sCACA,GACA,IAEA,OACA,+BACA,OACA,oBClBA,aAEA,WAiBA,UAfA,eACA,eACA,kBACA,QAEA,WACA,2CACA,GACA,IAEA,SACA,yCACA,EACA,oBCjBA,aAEA,WAiBA,UAfA,eACA,eACA,kBACA,QAEA,WACA,wCACA,GACA,IAEA,SACA,sCACA,EACA,oBCjBA,aAEA,WAkBA,UAhBA,eACA,iBACA,aACA,kBACA,CAEA,WACA,mCACA,GACA,IAEA,SACA,iCACA,EACA,oBClBA,aAEA,QACA,UAoBA,UAlBA,eACA,oBACA,2BACA,oCACA,2BACA,0BACA,MAEA,YACA,iEACA,IACA,IAEA,SACA,8DACA,GACA,oBCrBA,aAEA,QACA,UAoBA,UAlBA,eACA,0BACA,wBACA,yBACA,iBACA,mBACA,EAEA,YACA,2DACA,IACA,IAEA,SACA,yDACA,EACA,oBCrBA,aAEA,WAiBA,UAfA,eACA,eACA,qBACA,KAEA,WACA,4BACA,GACA,IAEA,SACA,0BACA,EACA,oBCjBA,aAEA,aAEA,UACA,kBACA,EACA,sBAYA,iBAyCA,UAxCA,gBACA,QACA,kCACA,6CACA,yCAEA,qBACA,KAGA,wCACA,aAAuB,UAAwB,OAC/C,eACA,QACA,QACA,MAGK,YAGL,wCACA,aAAuB,UAAwB,OAC/C,eACA,QACA,QACA,MAIA,yBAGA,0DACA,MAEA,IAEA,mBCxDA,aACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,8BAEA,SACA,EAEA,EACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,4BAEA,SACA,EAEA,EACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,mBAEA,WACA,EAEA,EACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,mBAEA,WACA,EAEA,EACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,mBAEA,WACA,EAEA,EACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,mBAEA,WACA,EAEA,EACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,6BAEA,kCACA,EAEA,EACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,6BAEA,kCACA,EAEA,EACA,YACA,mBACA,eACA,aAAmB,IAAO,EAC1B,6BAEA,oCACA,EAEA,EACA,YACA,mBACA,eACA,aAAmB,IAAO,EAC1B,6BAEA,oCACA,EAEA,EACA,UACA,mBACA,eACA,aAAmB,IAAO,EAC1B,2BAEA,kDACA,EAEA,EACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,yBAEA,eACA,EAEA,EACA,SACA,mBACA,eACA,aAAmB,IAAO,EAC1B,yBAEA,eACA,EAEA,EACA,eACA,mBACA,sBACA,GACA,oBCzIA,aAOA,kBACA,cACA,YAEA,6BACA,iCAEA,iBACA,WAEA,8BACA,6BACA,kBAEA,sBACA,aACA,aACA,OAAmB,KAAe,QAClC,gBAEA,2BACA,kCACA,aAEA,kCACA,iCACA,mCACA,mBAEA,oBAEA,2BACA,kCACA,iBAEA,sBACA,kCACA,uBACA,uBACA,EAEA,WAEA,2CACA,oBAEA,UACA,UACA,UACA,kBACA,GAvDA,QACA,WAEA,YAsDA,sCACA,iBAEA,uBACA,SAAmB,UAAoB,eACvC,+BACA,8BAEA,cACA,kBACA,IACA,yBAEA,YAGA,YACA,EAEA,eAJA,G,mBC1EA,aAwMA,iBACA,YACA,KAAmB,QAAiB,KACpC,gBAEA,UACA,GAOA,CACA,cACA,YACA,MACA,YAAkB,WAAkB,UACpC,WACA,OACA,QACA,MAGA,UACA,IA/NA,QACA,WAEA,OACA,mBACA,YACA,UACA,iBACA,sBACA,sBACA,sBACA,kCACA,iBACA,GAAS,KACT,mBACA,4BAEA,0FACA,cACA,qBACA,sBAEA,gCACA,cACA,qBACA,sBACA,GACA,CAeA,UACA,eAEA,iBACA,cACA,oDAGA,mBACA,UACA,iBAGA,sBACA,UAEA,QACA,WACA,cACA,WAEA,8BACA,4BAEA,SACA,iBACA,kBACA,kBACA,kBACA,kBACA,UACA,WAEA,wBACA,eACA,kBAEA,iCACA,0BAEA,2BACA,0BACA,kBAEA,qCACA,YACA,kBACA,QACA,cACA,mBACA,kBACA,gBACA,GAEA,IACA,kBACA,kCACA,aACA,cACA,WACA,WACA,WAEA,2BACA,kCACA,wBACA,qBACA,gDAEA,8BACA,oBACA,oBACA,oBACA,oBAEA,eACA,GACA,IAEA,CACA,mCACA,kCACA,kCACA,kCACA,kCACA,2BAKA,iBACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,gCACA,uFACA,EAOA,YACA,sBACA,qDACA,6BACA,+DACA,OACA,EAMA,uBACA,aACA,GAEA,SACA,OACA,MACA,eACA,eACA,mBACA,mBACA,mBACA,iBAEA,IAOA,gBACA,IACA,0DACA,sBACA,GACA,EAEA,UAOA,mBC5LA,aAEA,aACA,qBACA,WAEA,iBAOA,qBACA,CACA,WAEA,iBACA,YACA,KACA,0BAES,aACT,UACA,kBACA,4BAEA,mEACA,OAA2B,KAAO,GAClC,wBAGA,wBACA,kCACA,yBACA,YAnBA,QAoBA,kDAEA,IACA,CAEA,YACA,+BACA,EAEA,SACA,QAAmB,qCACnB,eACA,yBAEA,SACA,CAEA,YACA,mDACA,OAEA,WACA,OACA,iCAAyE,kBAEzE,KAAkC,6BAAgD,qBAGlF,KAEA,eACA,IACA,6CAEA,8CACA,EACA,EAGA,6BCtFA,aAEA,UACA,OAEA,OAEA,KACA,QACA,eACA,WACA,iBAIA,uBACA,iBACA,sBACA,IACA,QACA,sBACA,qBACA,0BACA,iCACA,iDAEA,kBACA,0BAES,aACT,WAAsC,YAEtC,oCACA,6BACA,UACA,kCAEA,6BACA,gBACA,sBACA,iCACA,0BAEA,MACA,mDAEA,IACA,CAEA,aACA,+DACA,EAEA,SACA,QACA,MACA,mCACA,kBACA,uBACA,8BAEA,2BACA,0BAEA,SACA,EAEA,gBACA,IACA,sDAEA,mCACA,GACA,EAEA,6BC3EA,aAqLA,iBACA,eACA,WAAmB,QAAY,OAC/B,gCAEA,UACA,GAQA,CACA,iBACA,gCACA,KApMA,UACA,UACA,+BAEA,MACA,OAGA,GACA,kBASA,sBACA,CACA,QACA,6CACA,4BACA,SACA,cACA,aAEA,OACA,oBAGA,kBAAsC,aACtC,kBACA,WACA,uBACA,UAEA,4BAEA,OACA,mDAGA,KAUA,aACA,8BACA,wCAGA,kBACA,aAGA,aACA,kEAEA,6CACA,0BAGA,6CACA,sCACA,0BAEA,8BACA,yBAEA,4BACA,+BACA,+BAEA,qBACA,mBACA,mBAEA,wBACA,OAEA,KAAuB,cAAiB,WACxC,eACA,cAA2B,SAAY,KACvC,oCACA,qBACA,IAEA,IAEA,6BACA,CACA,8BACA,+BAGA,qCACA,qCACA,6CACA,IACA,CAEA,qBACA,WAAmB,KAAkB,KACrC,oBAGA,OAEA,aACA,2BAEA,4FAEA,OAEA,KAAmB,MAAmB,KACtC,qBACA,MAAuB,MAAY,KACnC,qFACA,GAGA,IAEA,aACA,eACA,SAEA,MACA,KAEA,KAAuB,WAAiB,MACxC,gBAA2B,iBAAqB,GAChD,+DACA,GAIA,WACA,GAEA,SACA,QACA,MACA,uBACA,wBAEA,0BACA,0BAEA,SACA,EAEA,gBACA,IACA,0CAEA,0CACA,GAEA,EAEA,UASA,oBCzKA,aAEA,aACA,qBAEA,WAEA,iBAQA,wBACA,CACA,WAEA,iBACA,YACA,KACA,0BAES,aACT,UACA,kBACA,4BAGA,0EACA,+CACA,UACA,IAfA,QAgBA,kDAEA,IACA,CAEA,YACA,+BACA,EAEA,SACA,QAAmB,2CACnB,eACA,yBAEA,SACA,CAEA,YACA,0CACA,CAEA,WAEA,OACA,iCAAyE,aAEzE,IAAkC,6BAAgD,gBAElF,IAEA,eACA,IACA,mDAEA,oDACA,EACA,EAEA,6BC9EA,aAEA,aACA,qBACA,WAEA,iBAOA,qBACA,CACA,WAEA,iBACA,YACA,kBACA,uBACA,8BACA,6BAEA,eACA,oCAES,UACT,UACA,kBACA,4BAEA,gFACA,OAA2B,KAAO,GAClC,uBACA,wBAGA,yBACA,2CACA,qBACA,OAzBA,QA0BA,kDAEA,IACA,CAEA,YACA,+BACA,EAEA,SACA,QAAmB,uCACnB,eACA,yBAEA,SACA,CAEA,YACA,8CACA,EAEA,WACA,OACA,iCAAyE,kBAEzE,IAAkC,6BAAgD,qBAElF,IAEA,eACA,IACA,+CAEA,gDACA,EACA,EAEA,6BCpFA,aAEA,UACA,UACA,gCAEA,iBAUA,qBACA,OACA,OACA,QAEA,qBACA,wBACA,8BAA2C,0BAClC,aAET,UACA,kBACA,4BAGA,kEACA,OACA,aAA2B,KAAS,KACpC,iBAAoC,KAAS,KAC7C,aACA,wCAIA,gBACA,YAEA,aACA,eAA2B,KAAS,KACpC,sBAGA,eACA,oBACA,2CACA,UACA,kDAEA,IAEA,CAEA,SACA,OACA,MACA,gCACA,qBAEA,uBACA,yBAGA,SACA,CAEA,YACA,0BACA,SAEA,YACA,+BACA,KAEA,YACA,QACA,wBACA,qBACA,4CACA,mBACA,sBACA,sCACA,wBACA,EACA,CACA,2BAEA,SACA,GAEA,WACA,sBACA,EAEA,eACA,IACA,kDAEA,yCACA,EACA,EAEA,6BC3GA,aAEA,cACA,iCCHA,aAoBA,iBACA,CACA,4BAEA,aACA,gBACA,gBAEA,cACA,KACA,aACA,MAAmB,KAAU,GAC7B,YAAuB,KAAU,GACjC,mBAGA,WACA,EAAK,SACL,oBACA,OACA,MAAmB,KAAU,QAC7B,YACA,KAAuB,KAAU,GACjC,oBAEA,YACA,EACK,SACL,oBACA,OACA,MAAmB,KAAU,QAC7B,YACA,KAAuB,KAAU,GACjC,oBAEA,YACA,EAEA,sBAEA,2BACA,IAEA,oBACA,8BACA,UAAmB,KAAO,GAC1B,yBAEA,WACA,IAEA,oBACA,CACA,yBAEA,gBACA,cACA,iBACA,0BACA,gBAEA,OAAmB,KAAU,QAC7B,sBACA,KAAuB,KAAU,GACjC,sBACA,QACA,UAEA,UACA,qBAEA,iBAEA,EACA,OACA,IAqIA,qBACA,CACA,4BAEA,GACA,yBACA,oBACS,EACT,wBAGA,gBACA,UACA,UACA,OAEA,wBACA,mBAEA,aACA,cACA,OAAmB,KAAU,GAC7B,kBAEA,WAAmB,KAAU,GAC7B,YAAuB,MAAU,QACjC,QACA,KAA2B,KAAU,GACrC,4CAEA,SACA,cACA,cACA,EAEA,CAAK,gBACL,cACA,OAAmB,KAAU,GAC7B,kBAEA,WAAmB,KAAU,GAC7B,YAAuB,MAAU,QACjC,QACA,KAA2B,KAAU,GACrC,4CAEA,SACA,cACA,cACA,EAEA,CACA,sBAGA,2BACA,IA4BA,qBACA,iBACA,wCACA,qBACA,OAEA,qBACA,UACA,WACA,SACA,aAEA,OACA,gBACA,OAAmB,KAAO,GAC1B,yBAIA,eAAe,KAAO,QACtB,WACA,mBAAoC,UAAQ,GAC5C,0BAEA,GACA,OACA,IAEA,qBACA,+BACA,YACA,SACA,aAEA,OACA,gBACA,OAAmB,KAAO,GAC1B,yBAIA,eAAe,KAAO,QACtB,WACA,UACA,mBAA0C,UAAQ,GAClD,0BACA,wBAGA,IACA,OACA,IA4BA,qBACA,CACA,4BAEA,aACA,iBACA,sBACA,sBAEA,aACA,cACA,OAAmB,KAAU,GAC7B,YAEA,SAAmB,KAAU,GAC7B,eACA,UACA,OAAuB,KAAU,GACjC,oBAGA,EAAK,gBACL,cACA,OAAmB,KAAU,GAC7B,YAEA,SAAmB,KAAU,GAC7B,eACA,UACA,OAAuB,KAAU,GACjC,oBAGA,EACA,sBAGA,mCACA,OACA,sBAAsC,UAAQ,GAC9C,aAGA,SACA,IAcA,2BACA,QACA,kBACA,IACA,4BAEA,aACA,UACA,OAEA,wBACA,mBAEA,aACA,cACA,OAAmB,KAAU,GAC7B,kBAEA,WAAmB,KAAU,GAC7B,YAAuB,MAAU,QACjC,QACA,KAA2B,KAAU,GACrC,mDAEA,mBACA,iBACA,EAEA,CAAK,gBACL,cACA,OAAmB,KAAU,GAC7B,kBAEA,WAAmB,KAAU,GAC7B,YAAuB,MAAU,QACjC,QACA,KAA2B,KAAU,GACrC,mDAEA,mBACA,iBACA,EAEA,CACA,sBAGA,2BACA,IAhfA,SAEA,IAgfA,UACA,CACA,QAhfA,eACA,CACA,4BAEA,cACA,QACA,gBACA,UAAmB,KAAQ,GAC3B,gBAAuB,KAAQ,GAC/B,wCAGA,WACA,SAoeA,oBACA,WACA,EACA,OAxZA,YACA,+BACA,gBAEA,OAAmB,QAAU,QAC7B,UACA,eAAuB,KAAU,GACjC,mBAEA,OACA,iBACA,cACA,QAEA,2CAEA,GACA,OACA,KAuYA,KArYA,YACA,WACA,gBACA,gBACA,OACA,UAAe,KAAU,QACzB,kBACA,OAAuB,KAAU,GACjC,YAEA,eACA,OAEA,SAAmB,KAAU,QAC7B,0BACA,KACA,SAEA,qBACA,WACA,EAEA,KAEA,aACA,SAAmB,KAAW,GAC9B,YACA,WACA,OAIA,cACA,GACA,OACA,KAmWA,SAjWA,eACA,0BACA,oBACA,uBACA,gBAEA,OAAmB,KAAO,QAC1B,iBACA,KAAuB,QAAO,GAC9B,sBACA,WACA,aAGA,aACA,SACA,uBAEA,SACA,yBACA,kBACA,GACA,EACA,aAEA,EACA,OACA,KAuUA,SArUA,eACA,0BACA,oBACA,0BACA,gBAEA,OAAmB,KAAO,QAC1B,iBACA,KAAuB,QAAO,GAC9B,sBACA,WACA,gBAEA,aACA,SAEA,SACA,eACA,aAEA,wCADA,OAGA,6BADA,IAEA,wBAEA,CACA,OACA,KA2SA,cAzSA,YACA,eACA,sBACA,gBACA,iBAEA,OAAmB,KAAO,GAC1B,mBAEA,SACA,KAgSA,WA9RA,eACA,qBACA,aA6RA,GACA,YAlOA,YACA,UACA,eACA,gBACA,UACA,gBACA,UAEA,YACA,WAAe,KAAU,GACzB,kBAEA,WAAe,KAAU,GACzB,YAAmB,MAAU,QAC7B,YACA,aAA8C,UAAO,GACrD,2BAEA,WACA,aACA,cACA,EAEA,OACA,aA2MA,UACA,eACA,GACA,iBAvJA,eACA,UACA,UACA,iBACA,0BACA,gBAEA,OAAmB,KAAU,QAC7B,YACA,UAEA,KAAuB,KAAU,QACjC,sBACA,UAEA,eACA,QACA,UACA,EAEA,sBACA,IAEA,OACA,kBAgIA,GACA,mBAjFA,qBACA,QACA,kBACA,oBACA,aAAwC,UAAQ,GAChD,YACA,kBAEA,qBACA,0BACA,qBAwEA,qBCrgBA,oBAEA,mBAEA,2BACA,oBAEA,EATA,YAWA,kBACA,0BAEA,mCACA,+EACA,KAEA,wCACA,0BACA,yBACA,wBACA,sHACA,MAEA,kCACA,iBACA,yEAEA,U,mBC7BA,aAIA,eACA,UACA,EAJA,YAMA,iBACA,YACA,WAAmB,MAAmB,OACtC,eAAuB,UAAsB,OAC7C,yBAGA,WACA,IAEA,iBACA,WACA,WAAmB,MAAmB,OACtC,eAAuB,UAAsB,OAC7C,yBAGA,WACA,IAEA,oBACA,WACA,aACA,YAAmB,OAAmB,OACtC,gBAAuB,WAAsB,OAC7C,2BACA,6BAGA,WACA,KACA,MAEA,KAEA,uBACA,CACA,0BAEA,cACA,OACA,eACA,UAAmB,KAAQ,GAC3B,gBAAuB,KAAQ,GAC/B,sCAGA,UACA,IAEA,oBACA,CACA,0BAEA,YACA,eACA,gBAEA,aACA,KACA,aACA,MAAmB,KAAU,GAC7B,YAAuB,KAAU,GACjC,kBAGA,WACA,EAAK,SACL,mBACA,OACA,MAAmB,KAAU,QAC7B,YACA,KAAuB,KAAU,GACjC,mBAEA,YACA,EACK,SACL,mBACA,OACA,MAAmB,KAAU,QAC7B,YACA,KAAuB,KAAU,GACjC,mBAEA,YACA,EAEA,sBAEA,2BACA,KAEA,mBACA,CACA,0BAEA,YACA,eACA,aAEA,OACA,UACA,UAAmB,KAAU,GAC7B,YAAuB,KAAU,GACjC,kBAGK,YACL,mBACA,OAAmB,KAAU,GAC7B,gBACA,KAAuB,KAAU,GACjC,mBAGK,YACL,mBACA,OAAmB,KAAU,GAC7B,gBACA,KAAuB,KAAU,GACjC,mBAIA,yBAEA,2BACA,KAEA,uBACA,CACA,0BAEA,YACA,eACA,aAEA,OACA,UACA,UAAmB,KAAU,GAC7B,YAAuB,KAAU,GACjC,kBAGK,YACL,mBACA,OAAmB,KAAU,GAC7B,gBACA,KAAuB,KAAU,GACjC,mBAGK,YACL,mBACA,OAAmB,KAAU,GAC7B,gBACA,KAAuB,KAAU,GACjC,mBAIA,yBAEA,2BACA,KAEA,oCACA,qCACA,UAAmB,KAAO,GAC1B,yBAEA,WACA,KAEA,2BACA,CACA,yBAEA,mBACA,YACA,iBACA,yBACA,gBAEA,OAAmB,KAAU,QAC7B,sBACA,KAAuB,KAAU,GACjC,oBACA,QACA,UAEA,UACA,qBAEA,iBAEA,EACA,OACA,KAEA,oBACA,4BACA,gBAEA,OAAmB,QAAU,QAC7B,UACA,cAAuB,KAAU,EACjC,kBAEA,YACA,aACA,cACA,QAEA,2CAEA,GACA,OACA,KAEA,kBACA,SACA,eACA,gBACA,OACA,UAAe,KAAU,QACzB,kBACA,MAAuB,KAAU,EACjC,YAEA,eACA,MAEA,SAAmB,KAAU,OAC7B,yBACA,KACA,SAEA,oBACA,WACA,EAEA,KAEA,aACA,SAAmB,KAAW,GAC9B,YACA,WACA,OAIA,cACA,GACA,OACA,KAEA,wBACA,yBACA,wBACA,qBACA,gBAEA,OAAmB,KAAO,QAC1B,iBACA,KAAuB,QAAO,GAC9B,qBACA,WACA,aAGA,aACA,SACA,uBAEA,QACA,yBACA,kBACA,GACA,EACA,aAEA,EACA,OACA,KAEA,wBACA,yBACA,wBACA,uBACA,gBAEA,OAAmB,KAAO,QAC1B,iBACA,KAAuB,QAAO,GAC9B,qBACA,WACA,gBAEA,aACA,SAEA,QACA,eACA,aAEA,wCADA,OAGA,6BADA,IAEA,wBAEA,CACA,OACA,KAEA,2BACA,aACA,8BACA,SACA,gBACA,iBAEA,MAAmB,KAAO,GAC1B,mBAEA,SACA,KAEA,0BACA,2BACA,IAEA,0BACA,CACA,4BAEA,GACA,wBACA,kBACS,EACT,sBAGA,oBACA,SACA,UACA,OAEA,uBACA,mBAEA,aACA,cACA,OAAmB,KAAU,GAC7B,kBAEA,WAAmB,KAAU,GAC7B,YAAuB,MAAU,QACjC,QACA,KAA2B,KAAU,GACrC,0CAEA,SACA,aACA,cACA,EAEA,CAAK,gBACL,cACA,OAAmB,KAAU,GAC7B,kBAEA,WAAmB,KAAU,GAC7B,YAAuB,MAAU,QACjC,QACA,KAA2B,KAAU,GACrC,0CAEA,SACA,aACA,cACA,EAEA,CACA,sBAGA,2BACA,KAEA,yBACA,cACA,+BACA,oBACA,SACA,eACA,UAEA,YACA,WAAe,KAAU,GACzB,kBAEA,WAAe,KAAU,GACzB,YAAmB,MAAU,QAC7B,YACA,aAA8C,UAAO,GACrD,2BAEA,WACA,aACA,cACA,EAEA,OACA,KAEA,0BACA,oBACA,wDACA,mCACA,QAEA,yBACA,aACA,UACA,OACA,aAEA,OACA,gBACA,OAAmB,KAAO,GAC1B,wBAIA,eAAe,KAAO,QACtB,WACA,mBAAoC,UAAQ,GAC5C,wBAEA,GACA,OACA,KAEA,8BACA,+CACA,WACA,OACA,aAEA,OACA,gBACA,OAAmB,KAAO,GAC1B,wBAIA,eAAe,KAAO,QACtB,WACA,SACA,mBAA0C,UAAQ,GAClD,wBACA,uBAGA,IACA,OACA,KAEA,gCACA,eACA,QACA,iBACA,yBACA,gBAEA,OAAmB,KAAU,QAC7B,YACA,UAEA,KAAuB,KAAU,QACjC,qBACA,SAEA,eACA,QACA,UACA,EAEA,sBACA,IAEA,OACA,KAEA,+BACA,CACA,4BAEA,YACA,iBACA,qBACA,sBAEA,aACA,cACA,OAAmB,KAAU,GAC7B,YAEA,SAAmB,KAAU,GAC7B,cACA,SACA,OAAuB,KAAU,GACjC,oBAGA,EAAK,gBACL,cACA,OAAmB,KAAU,GAC7B,YAEA,SAAmB,KAAU,GAC7B,cACA,SACA,OAAuB,KAAU,GACjC,oBAGA,EACA,sBAGA,kCACA,MACA,sBAAsC,UAAQ,GAC9C,aAGA,SACA,KAEA,wCACA,QACA,4BACA,oBACA,YAAwC,UAAQ,GAChD,WACA,gBAEA,qBACA,uCACA,KAEA,wCACA,QACA,4BACA,IACA,4BAEA,YACA,UACA,OAEA,uBACA,mBAEA,aACA,cACA,OAAmB,KAAU,GAC7B,kBAEA,WAAmB,KAAU,GAC7B,YAAuB,MAAU,QACjC,QACA,KAA2B,KAAU,GACrC,gDAEA,mBACA,iBACA,EAEA,CAAK,gBACL,cACA,OAAmB,KAAU,GAC7B,kBAEA,WAAmB,KAAU,GAC7B,YAAuB,MAAU,QACjC,QACA,KAA2B,KAAU,GACrC,gDAEA,mBACA,iBACA,EAEA,CACA,sBAGA,2BACA,kBCrlBA,aACA,4BACA,WACA,YACA,aAEA,gBACA,KAAmB,QAAW,GAC9B,WACA,YAEA,aAGA,gBACA,KAAmB,QAAW,GAC9B,WACA,kBAEA,gBACA,uBACA,mBACA,kBAGA,aACA,kBAGA,IACA,KACA,UACA,wBACA,0BAIA,MAUA,CACA,yBACA,gBACA,kBAGA,oGAEA,kFACA,IAQA,CACA,MACA,WACA,eACA,WACA,SACA,KAWA,YAmBA,UACA,CACA,KApBA,uBACA,kBACA,OACA,oBACA,eAEA,YACA,eACA,IAEA,kCACA,iBACA,IAEA,qCACA,uCACA,mBAKA,gBCpHA,UAEA,aACA,MACA,kBACA,KAAiB,IAAO,EACxB,SAEA,QACA,iBCTA,aACA,mCACA,YACA,eCHA,CAWA,YACA,iBACA,mCACA,YACA,iBACA,oCACA,CAoBA,cACA,SAEA,gCAGA,qBACA,qBACA,yBAEA,MAEA,cACA,EAAK,UACL,IAEA,wBACA,EAAS,UAET,wBACA,EACA,CAGA,EACA,cACA,SAEA,iCAGA,sBACA,uBACA,0BAEA,OAEA,WACA,GAAK,UACL,IAEA,qBACA,GAAS,UAGT,qBACA,GACA,CAIA,EAMA,YACA,KAGA,KACA,SACA,oBAEA,QAEA,KACA,QAEA,KAEA,YACA,KAGA,aACA,GAEA,oBACA,WACA,QACA,GACA,WACA,IACA,WAGA,UACA,QACA,MACA,IACA,KACA,QACA,KAgBA,kBACA,UACA,cACA,GAWA,eAhKA,SAOA,WACA,iBASA,IACA,IACA,8BAEA,WAEA,CAAK,UACL,IACA,CACA,IACA,IACA,gCAEA,aAEA,CAAK,UACL,IACA,CACA,CAAC,KAqDD,GACA,OACA,MACA,SAyCA,wBACA,+BACA,MACA,8BAAuB,eAAsB,OAC7C,wBAGA,sBACA,oBACA,MAEA,EAEA,EAKA,2BACA,0BACA,QACA,mBACA,cACA,UACA,WACA,WAAqB,GACrB,eAIA,SACA,kBACA,WACA,UACA,qBACA,yBACA,WAEA,qBACA,iBACA,qCAEA,iBAA2B,YAC3B,mBACA,iBACA,mCACA,mBAA4B,OAAU,gBCnLtC,WAEA,8CACA,UACA,wCACA,aACA,OACA,EACA,cACA,YAGA,kBAGA,eACA,UACA,mBACA,gBACA,yBACA,2BACA,CACA,eCtBA,qBACA,WACA,oBACA,2BACA,2BACA,8B,kBCLA,eAmBA,CAyGA,iBAEA,QACA,CACA,gBAGA,mDACA,8CACA,OAEA,kBACG,GAEH,iBAGA,2BACA,uCACA,sBACA,qCACA,yCACA,eACA,OAmCA,iBACA,iBAEA,UACA,gCACA,2BAEA,IAEA,GAGA,cACA,OACA,IAGA,eACA,IAEA,qCACA,IACA,MAEA,GACA,GAGA,qBAGA,OACA,eACA,UAEA,yBAEA,0DACA,sBACA,cACA,kBAEA,KACA,EAGA,cACA,OACA,SAIA,uBACA,UAEA,UACA,2CAKA,QACA,gCACA,wCAIA,qBACA,WACA,6BACA,wCACA,UACA,OACA,yDAEA,gBACA,uDAEA,cACA,cAEA,GAEA,iBAGA,mBACA,MACA,MAIA,qBACA,6BACA,sBACA,GAGA,OACA,4CAIA,QACA,6CAIA,QACA,gBAGA,0BACA,iCAGA,MACA,eACA,kDAEA,gCAIA,wBAEA,OACA,cACA,kBAEA,uBACA,0BACA,GAGA,WAEA,eACA,IAGA,kBACA,OACA,kCACA,uBACA,iDACA,iBACA,4BACA,0BACA,SACA,WACA,qBACA,aACA,qBAEA,cACA,sBACA,eAGA,eACA,6CACA,IAGA,2BACA,QACA,kBAAmC,UAAO,KAC1C,SACA,2BACA,GAEA,mBAGA,kCACA,UACA,8BACA,GAEA,OACA,GACA,GAGA,8BACA,WACA,iDAAyD,UACzD,QACA,OACA,oCAEA,oCAGA,cACA,+BAGA,kBACA,gBAEA,KACA,KACA,mCACA,mBAEA,wBAEA,IACA,qBACA,qCACA,YACA,EAAW,qBAEX,0CACA,aACA,EAAW,QAIX,mCAGA,mBACA,iBACA,eAEA,yBACA,aACA,0DACA,oBAEA,6BACA,uBACA,wBACA,uBAEA,UAEA,gBACA,GAGA,qBACA,QACA,8BACA,OACA,2BACA,gDACA,CAAG,EAEH,SACA,UACA,kBACA,OACA,YACA,SACA,OAGA,qCACA,EAIA,CACA,eACA,sBACA,IAGA,eACA,OACA,qBAGA,eACA,OACA,WAQA,eACA,OACA,oBAGA,eACA,OACA,oBAQA,eACA,YACA,QAGA,eACA,gBACA,2BAGA,eACA,4BACA,UAGA,eACA,gBACA,yBAGA,eACA,WACA,8CACA,QAGA,eACA,OACA,sBAeA,eACA,uCACA,IAGA,eACA,8CACA,IAOA,aACA,WACA,gBACA,kBACA,wCACA,oDACA,IAGA,CAiCA,kBACA,gDACA,IApjBA,kBACA,qBACA,YACA,QACA,UAAmB,eAAsB,OACzC,yBAEA,qBACA,IAEA,YACA,KACA,gBACA,yCACA,oBACA,oBACA,WACA,uBACA,4BACA,UACA,QACA,0BACA,MAAS,UACT,OACA,YACA,CACA,cAEA,KACA,SAAuB,OAAS,WAChC,oBACA,QAEA,SAGA,UACA,GAKA,EACA,2BAEA,SACA,0BACA,sCACA,UAGA,YACA,oBAGA,OACA,OAeA,iBAdA,QACA,MACA,iCACO,WACP,+BAEA,kBAEA,IACA,KACA,sBACA,UAEA,GAIA,GACA,UACA,uBACA,OACA,2BACA,UACA,kBACA,+CACA,UACA,qBACA,yBACA,2CACA,GACA,CACA,wBAGA,YACA,GAUA,EAyBA,UAGA,EACA,EAgBA,+LACA,EAUA,mIAiRA,aAKA,eAKA,YAKA,oBAHA,YACA,OACA,WAMA,cAKA,cAKA,WAHA,YACA,OACA,qBAMA,iBAKA,cAKA,cAKA,YAMA,aAKA,gBAUA,cARA,YACA,OACA,YACA,sBACA,qBACA,qBACA,qBACA,wBAGA,kBAYA,GAGA,8EAWA,gBACA,6CACA,WAeA,EACA,kBAEA,yBAEA,uBAEA,2BACA,UACA,OACA,uBAEA,WACA,0CCrkBA,GAGA,aACA,OACA,KAAC,IAED,GAEA,0CACA,OAAC,SAED,CACA,4BACA,OAI4C,CAE5C,6BClBA,aACA,wBACA,iBACA,kBACA,cACA,iBACA,mBACA,qBACA,YAGA,IACA,QAEA,gBACA,sBACA,0BACA,uBACA,WACA,YACA,kBACA,qBACA,sBACA,qBACA,WAGA,GACA,gBAEA,mBACA,qBACA,YACA,gBAGA,IACA,eACA,UAGA,IACA,cAEA,WACA,oBAA2B,GAC3B,YACA,YACA,mBACA,QAGA,IACA,kBAEA,gBACA,YAGA,IACA,oBAEA,aACA","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"," \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\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 = 169);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 61fd2eb3be5b6e4c774d","'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","'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 = 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 diff --git a/package.json b/package.json index 8e3f4a6..0f1d469 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ml", - "version": "1.4.0", + "version": "2.0.0", "description": "Machine learning tools", "main": "src/index.js", "scripts": {