diff --git a/lib/umap-js.js b/lib/umap-js.js index b10dcb7..30bc435 100644 --- a/lib/umap-js.js +++ b/lib/umap-js.js @@ -91,7 +91,7 @@ return /******/ (function(modules) { // webpackBootstrap /******/ /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 5); +/******/ return __webpack_require__(__webpack_require__.s = 4); /******/ }) /************************************************************************/ /******/ ([ @@ -100,22 +100,6 @@ return /******/ (function(modules) { // webpackBootstrap "use strict"; - -const toString = Object.prototype.toString; - -function isAnyArray(object) { - return toString.call(object).endsWith('Array]'); -} - -module.exports = isAnyArray; - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); @@ -256,7 +240,7 @@ exports.reshape2d = reshape2d; /***/ }), -/* 2 */ +/* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -282,7 +266,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.smallestFlagged = exports.deheapSort = exports.buildCandidates = exports.uncheckedHeapPush = exports.heapPush = exports.rejectionSample = exports.makeHeap = void 0; -var utils = __importStar(__webpack_require__(1)); +var utils = __importStar(__webpack_require__(0)); function makeHeap(nPoints, size) { var makeArrays = function (fillValue) { return utils.empty(nPoints).map(function () { @@ -476,7 +460,7 @@ exports.smallestFlagged = smallestFlagged; /***/ }), -/* 3 */ +/* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -530,7 +514,7 @@ var __values = (this && this.__values) || function(o) { var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCSR = exports.normalize = exports.eliminateZeros = exports.multiplyScalar = exports.maximum = exports.subtract = exports.add = exports.pairwiseMultiply = exports.identity = exports.transpose = exports.SparseMatrix = void 0; -var utils = __importStar(__webpack_require__(1)); +var utils = __importStar(__webpack_require__(0)); var SparseMatrix = (function () { function SparseMatrix(rows, cols, values, dims) { this.entries = new Map(); @@ -829,7 +813,7 @@ exports.getCSR = getCSR; /***/ }), -/* 4 */ +/* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -886,7 +870,7 @@ var __values = (this && this.__values) || function(o) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.searchFlatTree = exports.makeLeafArray = exports.makeForest = exports.FlatTree = void 0; -var utils = __importStar(__webpack_require__(1)); +var utils = __importStar(__webpack_require__(0)); var FlatTree = (function () { function FlatTree(hyperplanes, offsets, children, indices) { this.hyperplanes = hyperplanes; @@ -1098,18 +1082,18 @@ exports.searchFlatTree = searchFlatTree; /***/ }), -/* 5 */ +/* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -var umap_1 = __webpack_require__(6); +var umap_1 = __webpack_require__(5); Object.defineProperty(exports, "UMAP", { enumerable: true, get: function () { return umap_1.UMAP; } }); /***/ }), -/* 6 */ +/* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -1194,12 +1178,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.initTransform = exports.resetLocalConnectivity = exports.fastIntersection = exports.findABParams = exports.cosine = exports.euclidean = exports.UMAP = void 0; -var heap = __importStar(__webpack_require__(2)); -var matrix = __importStar(__webpack_require__(3)); -var nnDescent = __importStar(__webpack_require__(7)); -var tree = __importStar(__webpack_require__(4)); -var utils = __importStar(__webpack_require__(1)); -var ml_levenberg_marquardt_1 = __importDefault(__webpack_require__(8)); +var heap = __importStar(__webpack_require__(1)); +var matrix = __importStar(__webpack_require__(2)); +var nnDescent = __importStar(__webpack_require__(6)); +var tree = __importStar(__webpack_require__(3)); +var utils = __importStar(__webpack_require__(0)); +var ml_levenberg_marquardt_1 = __importDefault(__webpack_require__(7)); var SMOOTH_K_TOLERANCE = 1e-5; var MIN_K_DIST_SCALE = 1e-3; var UMAP = (function () { @@ -1881,7 +1865,7 @@ exports.initTransform = initTransform; /***/ }), -/* 7 */ +/* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -1918,10 +1902,10 @@ var __values = (this && this.__values) || function(o) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.initializeSearch = exports.makeInitializedNNSearch = exports.makeInitializations = exports.makeNNDescent = void 0; -var heap = __importStar(__webpack_require__(2)); -var matrix = __importStar(__webpack_require__(3)); -var tree = __importStar(__webpack_require__(4)); -var utils = __importStar(__webpack_require__(1)); +var heap = __importStar(__webpack_require__(1)); +var matrix = __importStar(__webpack_require__(2)); +var tree = __importStar(__webpack_require__(3)); +var utils = __importStar(__webpack_require__(0)); function makeNNDescent(distanceFn, random) { return function nNDescent(data, leafArray, nNeighbors, nIters, maxCandidates, delta, rho, rpTreeInit) { if (nIters === void 0) { nIters = 10; } @@ -2079,12 +2063,19 @@ exports.initializeSearch = initializeSearch; /***/ }), -/* 8 */ +/* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); +// CONCATENATED MODULE: ./node_modules/is-any-array/src/index.js +const src_toString = Object.prototype.toString; + +function isAnyArray(object) { + return src_toString.call(object).endsWith('Array]'); +} + // CONCATENATED MODULE: ./node_modules/ml-levenberg-marquardt/src/errorCalculation.js /** * Calculate current error @@ -2097,33 +2088,39 @@ __webpack_require__.r(__webpack_exports__); function errorCalculation( data, parameters, - parameterizedFunction + parameterizedFunction, ) { - var error = 0; + let error = 0; const func = parameterizedFunction(parameters); - for (var i = 0; i < data.x.length; i++) { + for (let i = 0; i < data.x.length; i++) { error += Math.abs(data.y[i] - func(data.x[i])); } return error; } -// EXTERNAL MODULE: ./node_modules/is-any-array/src/index.js -var src = __webpack_require__(0); -var src_default = /*#__PURE__*/__webpack_require__.n(src); +// CONCATENATED MODULE: ./node_modules/ml-array-rescale/node_modules/is-any-array/src/index.js +const is_any_array_src_toString = Object.prototype.toString; + +function src_isAnyArray(object) { + return is_any_array_src_toString.call(object).endsWith('Array]'); +} -// CONCATENATED MODULE: ./node_modules/ml-array-max/lib-es6/index.js +// CONCATENATED MODULE: ./node_modules/ml-array-max/node_modules/is-any-array/src/index.js +const node_modules_is_any_array_src_toString = Object.prototype.toString; + +function is_any_array_src_isAnyArray(object) { + return node_modules_is_any_array_src_toString.call(object).endsWith('Array]'); +} +// CONCATENATED MODULE: ./node_modules/ml-array-max/lib-es6/index.js -/** - * Computes the maximum of the given values - * @param {Array} input - * @return {number} - */ function lib_es6_max(input) { - if (!src_default()(input)) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!is_any_array_src_isAnyArray(input)) { throw new TypeError('input must be an array'); } @@ -2131,9 +2128,22 @@ function lib_es6_max(input) { throw new TypeError('input must not be empty'); } - var maxValue = input[0]; + var _options$fromIndex = options.fromIndex, + fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex, + _options$toIndex = options.toIndex, + toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex; + + if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) { + throw new Error('fromIndex must be a positive integer smaller than length'); + } + + if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) { + throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length'); + } + + var maxValue = input[fromIndex]; - for (var i = 1; i < input.length; i++) { + for (var i = fromIndex + 1; i < toIndex; i++) { if (input[i] > maxValue) maxValue = input[i]; } @@ -2142,17 +2152,20 @@ function lib_es6_max(input) { /* harmony default export */ var lib_es6 = (lib_es6_max); -// CONCATENATED MODULE: ./node_modules/ml-array-min/lib-es6/index.js +// CONCATENATED MODULE: ./node_modules/ml-array-min/node_modules/is-any-array/src/index.js +const ml_array_min_node_modules_is_any_array_src_toString = Object.prototype.toString; + +function node_modules_is_any_array_src_isAnyArray(object) { + return ml_array_min_node_modules_is_any_array_src_toString.call(object).endsWith('Array]'); +} +// CONCATENATED MODULE: ./node_modules/ml-array-min/lib-es6/index.js -/** - * Computes the minimum of the given values - * @param {Array} input - * @return {number} - */ function lib_es6_min(input) { - if (!src_default()(input)) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!node_modules_is_any_array_src_isAnyArray(input)) { throw new TypeError('input must be an array'); } @@ -2160,9 +2173,22 @@ function lib_es6_min(input) { throw new TypeError('input must not be empty'); } - var minValue = input[0]; + var _options$fromIndex = options.fromIndex, + fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex, + _options$toIndex = options.toIndex, + toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex; + + if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) { + throw new Error('fromIndex must be a positive integer smaller than length'); + } + + if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) { + throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length'); + } + + var minValue = input[fromIndex]; - for (var i = 1; i < input.length; i++) { + for (var i = fromIndex + 1; i < toIndex; i++) { if (input[i] < minValue) minValue = input[i]; } @@ -2179,7 +2205,7 @@ function lib_es6_min(input) { function rescale(input) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (!src_default()(input)) { + if (!src_isAnyArray(input)) { throw new TypeError('input must be an array'); } else if (input.length === 0) { throw new TypeError('input must not be empty'); @@ -2188,7 +2214,7 @@ function rescale(input) { var output; if (options.output !== undefined) { - if (!src_default()(options.output)) { + if (!src_isAnyArray(options.output)) { throw new TypeError('output option must be an array if specified'); } @@ -2224,505 +2250,146 @@ function rescale(input) { /* harmony default export */ var ml_array_rescale_lib_es6 = (rescale); -// CONCATENATED MODULE: ./node_modules/ml-matrix/src/util.js -/** - * @private - * Check that a row index is not out of bounds - * @param {Matrix} matrix - * @param {number} index - * @param {boolean} [outer] - */ -function checkRowIndex(matrix, index, outer) { - let max = outer ? matrix.rows : matrix.rows - 1; - if (index < 0 || index > max) { - throw new RangeError('Row index out of range'); - } +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/inspect.js +const indent = ' '.repeat(2); +const indentData = ' '.repeat(4); + +function inspectMatrix() { + return inspectMatrixWithOptions(this); } -/** - * @private - * Check that a column index is not out of bounds - * @param {Matrix} matrix - * @param {number} index - * @param {boolean} [outer] - */ -function checkColumnIndex(matrix, index, outer) { - let max = outer ? matrix.columns : matrix.columns - 1; - if (index < 0 || index > max) { - throw new RangeError('Column index out of range'); - } +function inspectMatrixWithOptions(matrix, options = {}) { + const { maxRows = 15, maxColumns = 10, maxNumSize = 8 } = options; + return `${matrix.constructor.name} { +${indent}[ +${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize)} +${indent}] +${indent}rows: ${matrix.rows} +${indent}columns: ${matrix.columns} +}`; } -/** - * @private - * Check that the provided vector is an array with the right length - * @param {Matrix} matrix - * @param {Array|Matrix} vector - * @return {Array} - * @throws {RangeError} - */ -function checkRowVector(matrix, vector) { - if (vector.to1DArray) { - vector = vector.to1DArray(); +function inspectData(matrix, maxRows, maxColumns, maxNumSize) { + const { rows, columns } = matrix; + const maxI = Math.min(rows, maxRows); + const maxJ = Math.min(columns, maxColumns); + const result = []; + for (let i = 0; i < maxI; i++) { + let line = []; + for (let j = 0; j < maxJ; j++) { + line.push(formatNumber(matrix.get(i, j), maxNumSize)); + } + result.push(`${line.join(' ')}`); } - if (vector.length !== matrix.columns) { - throw new RangeError( - 'vector size must be the same as the number of columns', - ); + if (maxJ !== columns) { + result[result.length - 1] += ` ... ${columns - maxColumns} more columns`; } - return vector; + if (maxI !== rows) { + result.push(`... ${rows - maxRows} more rows`); + } + return result.join(`\n${indentData}`); } -/** - * @private - * Check that the provided vector is an array with the right length - * @param {Matrix} matrix - * @param {Array|Matrix} vector - * @return {Array} - * @throws {RangeError} - */ -function checkColumnVector(matrix, vector) { - if (vector.to1DArray) { - vector = vector.to1DArray(); +function formatNumber(num, maxNumSize) { + const numStr = String(num); + if (numStr.length <= maxNumSize) { + return numStr.padEnd(maxNumSize, ' '); } - if (vector.length !== matrix.rows) { - throw new RangeError('vector size must be the same as the number of rows'); + const precise = num.toPrecision(maxNumSize - 2); + if (precise.length <= maxNumSize) { + return precise; } - return vector; + const exponential = num.toExponential(maxNumSize - 2); + const eIndex = exponential.indexOf('e'); + const e = exponential.slice(eIndex); + return exponential.slice(0, maxNumSize - e.length) + e; } -function checkIndices(matrix, rowIndices, columnIndices) { - return { - row: checkRowIndices(matrix, rowIndices), - column: checkColumnIndices(matrix, columnIndices), +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/mathOperations.js +function installMathOperations(AbstractMatrix, Matrix) { + AbstractMatrix.prototype.add = function add(value) { + if (typeof value === 'number') return this.addS(value); + return this.addM(value); }; -} -function checkRowIndices(matrix, rowIndices) { - if (typeof rowIndices !== 'object') { - throw new TypeError('unexpected type for row indices'); - } + AbstractMatrix.prototype.addS = function addS(value) { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + value); + } + } + return this; + }; - let rowOut = rowIndices.some((r) => { - return r < 0 || r >= matrix.rows; - }); + AbstractMatrix.prototype.addM = function addM(matrix) { + matrix = Matrix.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) + matrix.get(i, j)); + } + } + return this; + }; - if (rowOut) { - throw new RangeError('row indices are out of range'); - } + AbstractMatrix.add = function add(matrix, value) { + const newMatrix = new Matrix(matrix); + return newMatrix.add(value); + }; - if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); + AbstractMatrix.prototype.sub = function sub(value) { + if (typeof value === 'number') return this.subS(value); + return this.subM(value); + }; - return rowIndices; -} + AbstractMatrix.prototype.subS = function subS(value) { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - value); + } + } + return this; + }; -function checkColumnIndices(matrix, columnIndices) { - if (typeof columnIndices !== 'object') { - throw new TypeError('unexpected type for column indices'); - } + AbstractMatrix.prototype.subM = function subM(matrix) { + matrix = Matrix.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) - matrix.get(i, j)); + } + } + return this; + }; - let columnOut = columnIndices.some((c) => { - return c < 0 || c >= matrix.columns; - }); + AbstractMatrix.sub = function sub(matrix, value) { + const newMatrix = new Matrix(matrix); + return newMatrix.sub(value); + }; + AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub; + AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS; + AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM; + AbstractMatrix.subtract = AbstractMatrix.sub; - if (columnOut) { - throw new RangeError('column indices are out of range'); - } - if (!Array.isArray(columnIndices)) columnIndices = Array.from(columnIndices); + AbstractMatrix.prototype.mul = function mul(value) { + if (typeof value === 'number') return this.mulS(value); + return this.mulM(value); + }; - return columnIndices; -} - -function checkRange(matrix, startRow, endRow, startColumn, endColumn) { - if (arguments.length !== 5) { - throw new RangeError('expected 4 arguments'); - } - checkNumber('startRow', startRow); - checkNumber('endRow', endRow); - checkNumber('startColumn', startColumn); - checkNumber('endColumn', endColumn); - if ( - startRow > endRow || - startColumn > endColumn || - startRow < 0 || - startRow >= matrix.rows || - endRow < 0 || - endRow >= matrix.rows || - startColumn < 0 || - startColumn >= matrix.columns || - endColumn < 0 || - endColumn >= matrix.columns - ) { - throw new RangeError('Submatrix indices are out of range'); - } -} - -function newArray(length, value = 0) { - let array = []; - for (let i = 0; i < length; i++) { - array.push(value); - } - return array; -} - -function checkNumber(name, value) { - if (typeof value !== 'number') { - throw new TypeError(`${name} must be a number`); - } -} - -// CONCATENATED MODULE: ./node_modules/ml-matrix/src/stat.js - - -function sumByRow(matrix) { - let sum = newArray(matrix.rows); - for (let i = 0; i < matrix.rows; ++i) { - for (let j = 0; j < matrix.columns; ++j) { - sum[i] += matrix.get(i, j); - } - } - return sum; -} - -function sumByColumn(matrix) { - let sum = newArray(matrix.columns); - for (let i = 0; i < matrix.rows; ++i) { - for (let j = 0; j < matrix.columns; ++j) { - sum[j] += matrix.get(i, j); - } - } - return sum; -} - -function sumAll(matrix) { - let v = 0; - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - v += matrix.get(i, j); - } - } - return v; -} - -function productByRow(matrix) { - let sum = newArray(matrix.rows, 1); - for (let i = 0; i < matrix.rows; ++i) { - for (let j = 0; j < matrix.columns; ++j) { - sum[i] *= matrix.get(i, j); - } - } - return sum; -} - -function productByColumn(matrix) { - let sum = newArray(matrix.columns, 1); - for (let i = 0; i < matrix.rows; ++i) { - for (let j = 0; j < matrix.columns; ++j) { - sum[j] *= matrix.get(i, j); - } - } - return sum; -} - -function productAll(matrix) { - let v = 1; - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - v *= matrix.get(i, j); - } - } - return v; -} - -function varianceByRow(matrix, unbiased, mean) { - const rows = matrix.rows; - const cols = matrix.columns; - const variance = []; - - for (let i = 0; i < rows; i++) { - let sum1 = 0; - let sum2 = 0; - let x = 0; - for (let j = 0; j < cols; j++) { - x = matrix.get(i, j) - mean[i]; - sum1 += x; - sum2 += x * x; - } - if (unbiased) { - variance.push((sum2 - (sum1 * sum1) / cols) / (cols - 1)); - } else { - variance.push((sum2 - (sum1 * sum1) / cols) / cols); - } - } - return variance; -} - -function varianceByColumn(matrix, unbiased, mean) { - const rows = matrix.rows; - const cols = matrix.columns; - const variance = []; - - for (let j = 0; j < cols; j++) { - let sum1 = 0; - let sum2 = 0; - let x = 0; - for (let i = 0; i < rows; i++) { - x = matrix.get(i, j) - mean[j]; - sum1 += x; - sum2 += x * x; - } - if (unbiased) { - variance.push((sum2 - (sum1 * sum1) / rows) / (rows - 1)); - } else { - variance.push((sum2 - (sum1 * sum1) / rows) / rows); - } - } - return variance; -} - -function varianceAll(matrix, unbiased, mean) { - const rows = matrix.rows; - const cols = matrix.columns; - const size = rows * cols; - - let sum1 = 0; - let sum2 = 0; - let x = 0; - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - x = matrix.get(i, j) - mean; - sum1 += x; - sum2 += x * x; - } - } - if (unbiased) { - return (sum2 - (sum1 * sum1) / size) / (size - 1); - } else { - return (sum2 - (sum1 * sum1) / size) / size; - } -} - -function centerByRow(matrix, mean) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) - mean[i]); - } - } -} - -function centerByColumn(matrix, mean) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) - mean[j]); - } - } -} - -function centerAll(matrix, mean) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) - mean); - } - } -} - -function getScaleByRow(matrix) { - const scale = []; - for (let i = 0; i < matrix.rows; i++) { - let sum = 0; - for (let j = 0; j < matrix.columns; j++) { - sum += Math.pow(matrix.get(i, j), 2) / (matrix.columns - 1); - } - scale.push(Math.sqrt(sum)); - } - return scale; -} - -function scaleByRow(matrix, scale) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) / scale[i]); - } - } -} - -function getScaleByColumn(matrix) { - const scale = []; - for (let j = 0; j < matrix.columns; j++) { - let sum = 0; - for (let i = 0; i < matrix.rows; i++) { - sum += Math.pow(matrix.get(i, j), 2) / (matrix.rows - 1); - } - scale.push(Math.sqrt(sum)); - } - return scale; -} - -function scaleByColumn(matrix, scale) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) / scale[j]); - } - } -} - -function getScaleAll(matrix) { - const divider = matrix.size - 1; - let sum = 0; - for (let j = 0; j < matrix.columns; j++) { - for (let i = 0; i < matrix.rows; i++) { - sum += Math.pow(matrix.get(i, j), 2) / divider; - } - } - return Math.sqrt(sum); -} - -function scaleAll(matrix, scale) { - for (let i = 0; i < matrix.rows; i++) { - for (let j = 0; j < matrix.columns; j++) { - matrix.set(i, j, matrix.get(i, j) / scale); - } - } -} - -// CONCATENATED MODULE: ./node_modules/ml-matrix/src/inspect.js -function inspectMatrix() { - const indent = ' '.repeat(2); - const indentData = ' '.repeat(4); - return `${this.constructor.name} { -${indent}[ -${indentData}${inspectData(this, indentData)} -${indent}] -${indent}rows: ${this.rows} -${indent}columns: ${this.columns} -}`; -} - -const maxRows = 15; -const maxColumns = 10; -const maxNumSize = 8; - -function inspectData(matrix, indent) { - const { rows, columns } = matrix; - const maxI = Math.min(rows, maxRows); - const maxJ = Math.min(columns, maxColumns); - const result = []; - for (let i = 0; i < maxI; i++) { - let line = []; - for (let j = 0; j < maxJ; j++) { - line.push(formatNumber(matrix.get(i, j))); - } - result.push(`${line.join(' ')}`); - } - if (maxJ !== columns) { - result[result.length - 1] += ` ... ${columns - maxColumns} more columns`; - } - if (maxI !== rows) { - result.push(`... ${rows - maxRows} more rows`); - } - return result.join(`\n${indent}`); -} - -function formatNumber(num) { - const numStr = String(num); - if (numStr.length <= maxNumSize) { - return numStr.padEnd(maxNumSize, ' '); - } - const precise = num.toPrecision(maxNumSize - 2); - if (precise.length <= maxNumSize) { - return precise; - } - const exponential = num.toExponential(maxNumSize - 2); - const eIndex = exponential.indexOf('e'); - const e = exponential.substring(eIndex); - return exponential.substring(0, maxNumSize - e.length) + e; -} - -// CONCATENATED MODULE: ./node_modules/ml-matrix/src/mathOperations.js -function installMathOperations(AbstractMatrix, Matrix) { - AbstractMatrix.prototype.add = function add(value) { - if (typeof value === 'number') return this.addS(value); - return this.addM(value); - }; - - AbstractMatrix.prototype.addS = function addS(value) { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) + value); - } - } - return this; - }; - - AbstractMatrix.prototype.addM = function addM(matrix) { - matrix = Matrix.checkMatrix(matrix); - if (this.rows !== matrix.rows || - this.columns !== matrix.columns) { - throw new RangeError('Matrices dimensions must be equal'); - } - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) + matrix.get(i, j)); - } - } - return this; - }; - - AbstractMatrix.add = function add(matrix, value) { - const newMatrix = new Matrix(matrix); - return newMatrix.add(value); - }; - - AbstractMatrix.prototype.sub = function sub(value) { - if (typeof value === 'number') return this.subS(value); - return this.subM(value); - }; - - AbstractMatrix.prototype.subS = function subS(value) { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) - value); - } - } - return this; - }; - - AbstractMatrix.prototype.subM = function subM(matrix) { - matrix = Matrix.checkMatrix(matrix); - if (this.rows !== matrix.rows || - this.columns !== matrix.columns) { - throw new RangeError('Matrices dimensions must be equal'); - } - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) - matrix.get(i, j)); - } - } - return this; - }; - - AbstractMatrix.sub = function sub(matrix, value) { - const newMatrix = new Matrix(matrix); - return newMatrix.sub(value); - }; - AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub; - AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS; - AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM; - AbstractMatrix.subtract = AbstractMatrix.sub; - - AbstractMatrix.prototype.mul = function mul(value) { - if (typeof value === 'number') return this.mulS(value); - return this.mulM(value); - }; - - AbstractMatrix.prototype.mulS = function mulS(value) { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, this.get(i, j) * value); - } - } - return this; - }; + AbstractMatrix.prototype.mulS = function mulS(value) { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, this.get(i, j) * value); + } + } + return this; + }; AbstractMatrix.prototype.mulM = function mulM(matrix) { matrix = Matrix.checkMatrix(matrix); @@ -3284,183 +2951,550 @@ function installMathOperations(AbstractMatrix, Matrix) { return this; }; - AbstractMatrix.log1p = function log1p(matrix) { + AbstractMatrix.log1p = function log1p(matrix) { + const newMatrix = new Matrix(matrix); + return newMatrix.log1p(); + }; + + AbstractMatrix.prototype.log10 = function log10() { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, Math.log10(this.get(i, j))); + } + } + return this; + }; + + AbstractMatrix.log10 = function log10(matrix) { + const newMatrix = new Matrix(matrix); + return newMatrix.log10(); + }; + + AbstractMatrix.prototype.log2 = function log2() { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, Math.log2(this.get(i, j))); + } + } + return this; + }; + + AbstractMatrix.log2 = function log2(matrix) { + const newMatrix = new Matrix(matrix); + return newMatrix.log2(); + }; + + AbstractMatrix.prototype.round = function round() { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, Math.round(this.get(i, j))); + } + } + return this; + }; + + AbstractMatrix.round = function round(matrix) { + const newMatrix = new Matrix(matrix); + return newMatrix.round(); + }; + + AbstractMatrix.prototype.sign = function sign() { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, Math.sign(this.get(i, j))); + } + } + return this; + }; + + AbstractMatrix.sign = function sign(matrix) { + const newMatrix = new Matrix(matrix); + return newMatrix.sign(); + }; + + AbstractMatrix.prototype.sin = function sin() { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, Math.sin(this.get(i, j))); + } + } + return this; + }; + + AbstractMatrix.sin = function sin(matrix) { + const newMatrix = new Matrix(matrix); + return newMatrix.sin(); + }; + + AbstractMatrix.prototype.sinh = function sinh() { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, Math.sinh(this.get(i, j))); + } + } + return this; + }; + + AbstractMatrix.sinh = function sinh(matrix) { + const newMatrix = new Matrix(matrix); + return newMatrix.sinh(); + }; + + AbstractMatrix.prototype.sqrt = function sqrt() { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, Math.sqrt(this.get(i, j))); + } + } + return this; + }; + + AbstractMatrix.sqrt = function sqrt(matrix) { + const newMatrix = new Matrix(matrix); + return newMatrix.sqrt(); + }; + + AbstractMatrix.prototype.tan = function tan() { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.columns; j++) { + this.set(i, j, Math.tan(this.get(i, j))); + } + } + return this; + }; + + AbstractMatrix.tan = function tan(matrix) { const newMatrix = new Matrix(matrix); - return newMatrix.log1p(); + return newMatrix.tan(); }; - AbstractMatrix.prototype.log10 = function log10() { + AbstractMatrix.prototype.tanh = function tanh() { for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.log10(this.get(i, j))); + this.set(i, j, Math.tanh(this.get(i, j))); } } return this; }; - AbstractMatrix.log10 = function log10(matrix) { + AbstractMatrix.tanh = function tanh(matrix) { const newMatrix = new Matrix(matrix); - return newMatrix.log10(); + return newMatrix.tanh(); }; - AbstractMatrix.prototype.log2 = function log2() { + AbstractMatrix.prototype.trunc = function trunc() { for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.log2(this.get(i, j))); + this.set(i, j, Math.trunc(this.get(i, j))); } } return this; }; - AbstractMatrix.log2 = function log2(matrix) { + AbstractMatrix.trunc = function trunc(matrix) { const newMatrix = new Matrix(matrix); - return newMatrix.log2(); + return newMatrix.trunc(); }; - AbstractMatrix.prototype.round = function round() { + AbstractMatrix.pow = function pow(matrix, arg0) { + const newMatrix = new Matrix(matrix); + return newMatrix.pow(arg0); + }; + + AbstractMatrix.prototype.pow = function pow(value) { + if (typeof value === 'number') return this.powS(value); + return this.powM(value); + }; + + AbstractMatrix.prototype.powS = function powS(value) { for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.round(this.get(i, j))); + this.set(i, j, Math.pow(this.get(i, j), value)); } } return this; }; - AbstractMatrix.round = function round(matrix) { - const newMatrix = new Matrix(matrix); - return newMatrix.round(); - }; - - AbstractMatrix.prototype.sign = function sign() { + AbstractMatrix.prototype.powM = function powM(matrix) { + matrix = Matrix.checkMatrix(matrix); + if (this.rows !== matrix.rows || + this.columns !== matrix.columns) { + throw new RangeError('Matrices dimensions must be equal'); + } for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.sign(this.get(i, j))); + this.set(i, j, Math.pow(this.get(i, j), matrix.get(i, j))); } } return this; }; +} - AbstractMatrix.sign = function sign(matrix) { - const newMatrix = new Matrix(matrix); - return newMatrix.sign(); +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/util.js +/** + * @private + * Check that a row index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ +function checkRowIndex(matrix, index, outer) { + let max = outer ? matrix.rows : matrix.rows - 1; + if (index < 0 || index > max) { + throw new RangeError('Row index out of range'); + } +} + +/** + * @private + * Check that a column index is not out of bounds + * @param {Matrix} matrix + * @param {number} index + * @param {boolean} [outer] + */ +function checkColumnIndex(matrix, index, outer) { + let max = outer ? matrix.columns : matrix.columns - 1; + if (index < 0 || index > max) { + throw new RangeError('Column index out of range'); + } +} + +/** + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} + */ +function checkRowVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + if (vector.length !== matrix.columns) { + throw new RangeError( + 'vector size must be the same as the number of columns', + ); + } + return vector; +} + +/** + * @private + * Check that the provided vector is an array with the right length + * @param {Matrix} matrix + * @param {Array|Matrix} vector + * @return {Array} + * @throws {RangeError} + */ +function checkColumnVector(matrix, vector) { + if (vector.to1DArray) { + vector = vector.to1DArray(); + } + if (vector.length !== matrix.rows) { + throw new RangeError('vector size must be the same as the number of rows'); + } + return vector; +} + +function checkIndices(matrix, rowIndices, columnIndices) { + return { + row: checkRowIndices(matrix, rowIndices), + column: checkColumnIndices(matrix, columnIndices), }; +} - AbstractMatrix.prototype.sin = function sin() { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.sin(this.get(i, j))); - } +function checkRowIndices(matrix, rowIndices) { + if (typeof rowIndices !== 'object') { + throw new TypeError('unexpected type for row indices'); + } + + let rowOut = rowIndices.some((r) => { + return r < 0 || r >= matrix.rows; + }); + + if (rowOut) { + throw new RangeError('row indices are out of range'); + } + + if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices); + + return rowIndices; +} + +function checkColumnIndices(matrix, columnIndices) { + if (typeof columnIndices !== 'object') { + throw new TypeError('unexpected type for column indices'); + } + + let columnOut = columnIndices.some((c) => { + return c < 0 || c >= matrix.columns; + }); + + if (columnOut) { + throw new RangeError('column indices are out of range'); + } + if (!Array.isArray(columnIndices)) columnIndices = Array.from(columnIndices); + + return columnIndices; +} + +function checkRange(matrix, startRow, endRow, startColumn, endColumn) { + if (arguments.length !== 5) { + throw new RangeError('expected 4 arguments'); + } + checkNumber('startRow', startRow); + checkNumber('endRow', endRow); + checkNumber('startColumn', startColumn); + checkNumber('endColumn', endColumn); + if ( + startRow > endRow || + startColumn > endColumn || + startRow < 0 || + startRow >= matrix.rows || + endRow < 0 || + endRow >= matrix.rows || + startColumn < 0 || + startColumn >= matrix.columns || + endColumn < 0 || + endColumn >= matrix.columns + ) { + throw new RangeError('Submatrix indices are out of range'); + } +} + +function newArray(length, value = 0) { + let array = []; + for (let i = 0; i < length; i++) { + array.push(value); + } + return array; +} + +function checkNumber(name, value) { + if (typeof value !== 'number') { + throw new TypeError(`${name} must be a number`); + } +} + +function checkNonEmpty(matrix) { + if (matrix.isEmpty()) { + throw new Error('Empty matrix has no elements to index'); + } +} + +// CONCATENATED MODULE: ./node_modules/ml-matrix/src/stat.js + + +function sumByRow(matrix) { + let sum = newArray(matrix.rows); + for (let i = 0; i < matrix.rows; ++i) { + for (let j = 0; j < matrix.columns; ++j) { + sum[i] += matrix.get(i, j); + } + } + return sum; +} + +function sumByColumn(matrix) { + let sum = newArray(matrix.columns); + for (let i = 0; i < matrix.rows; ++i) { + for (let j = 0; j < matrix.columns; ++j) { + sum[j] += matrix.get(i, j); + } + } + return sum; +} + +function sumAll(matrix) { + let v = 0; + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + v += matrix.get(i, j); + } + } + return v; +} + +function productByRow(matrix) { + let sum = newArray(matrix.rows, 1); + for (let i = 0; i < matrix.rows; ++i) { + for (let j = 0; j < matrix.columns; ++j) { + sum[i] *= matrix.get(i, j); + } + } + return sum; +} + +function productByColumn(matrix) { + let sum = newArray(matrix.columns, 1); + for (let i = 0; i < matrix.rows; ++i) { + for (let j = 0; j < matrix.columns; ++j) { + sum[j] *= matrix.get(i, j); + } + } + return sum; +} + +function productAll(matrix) { + let v = 1; + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + v *= matrix.get(i, j); } - return this; - }; + } + return v; +} - AbstractMatrix.sin = function sin(matrix) { - const newMatrix = new Matrix(matrix); - return newMatrix.sin(); - }; +function varianceByRow(matrix, unbiased, mean) { + const rows = matrix.rows; + const cols = matrix.columns; + const variance = []; - AbstractMatrix.prototype.sinh = function sinh() { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.sinh(this.get(i, j))); - } + for (let i = 0; i < rows; i++) { + let sum1 = 0; + let sum2 = 0; + let x = 0; + for (let j = 0; j < cols; j++) { + x = matrix.get(i, j) - mean[i]; + sum1 += x; + sum2 += x * x; } - return this; - }; + if (unbiased) { + variance.push((sum2 - (sum1 * sum1) / cols) / (cols - 1)); + } else { + variance.push((sum2 - (sum1 * sum1) / cols) / cols); + } + } + return variance; +} - AbstractMatrix.sinh = function sinh(matrix) { - const newMatrix = new Matrix(matrix); - return newMatrix.sinh(); - }; +function varianceByColumn(matrix, unbiased, mean) { + const rows = matrix.rows; + const cols = matrix.columns; + const variance = []; - AbstractMatrix.prototype.sqrt = function sqrt() { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.sqrt(this.get(i, j))); - } + for (let j = 0; j < cols; j++) { + let sum1 = 0; + let sum2 = 0; + let x = 0; + for (let i = 0; i < rows; i++) { + x = matrix.get(i, j) - mean[j]; + sum1 += x; + sum2 += x * x; } - return this; - }; + if (unbiased) { + variance.push((sum2 - (sum1 * sum1) / rows) / (rows - 1)); + } else { + variance.push((sum2 - (sum1 * sum1) / rows) / rows); + } + } + return variance; +} - AbstractMatrix.sqrt = function sqrt(matrix) { - const newMatrix = new Matrix(matrix); - return newMatrix.sqrt(); - }; +function varianceAll(matrix, unbiased, mean) { + const rows = matrix.rows; + const cols = matrix.columns; + const size = rows * cols; - AbstractMatrix.prototype.tan = function tan() { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.tan(this.get(i, j))); - } + let sum1 = 0; + let sum2 = 0; + let x = 0; + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + x = matrix.get(i, j) - mean; + sum1 += x; + sum2 += x * x; } - return this; - }; - - AbstractMatrix.tan = function tan(matrix) { - const newMatrix = new Matrix(matrix); - return newMatrix.tan(); - }; + } + if (unbiased) { + return (sum2 - (sum1 * sum1) / size) / (size - 1); + } else { + return (sum2 - (sum1 * sum1) / size) / size; + } +} - AbstractMatrix.prototype.tanh = function tanh() { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.tanh(this.get(i, j))); - } +function centerByRow(matrix, mean) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) - mean[i]); } - return this; - }; + } +} - AbstractMatrix.tanh = function tanh(matrix) { - const newMatrix = new Matrix(matrix); - return newMatrix.tanh(); - }; +function centerByColumn(matrix, mean) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) - mean[j]); + } + } +} - AbstractMatrix.prototype.trunc = function trunc() { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.trunc(this.get(i, j))); - } +function centerAll(matrix, mean) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) - mean); } - return this; - }; + } +} - AbstractMatrix.trunc = function trunc(matrix) { - const newMatrix = new Matrix(matrix); - return newMatrix.trunc(); - }; +function getScaleByRow(matrix) { + const scale = []; + for (let i = 0; i < matrix.rows; i++) { + let sum = 0; + for (let j = 0; j < matrix.columns; j++) { + sum += Math.pow(matrix.get(i, j), 2) / (matrix.columns - 1); + } + scale.push(Math.sqrt(sum)); + } + return scale; +} - AbstractMatrix.pow = function pow(matrix, arg0) { - const newMatrix = new Matrix(matrix); - return newMatrix.pow(arg0); - }; +function scaleByRow(matrix, scale) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) / scale[i]); + } + } +} - AbstractMatrix.prototype.pow = function pow(value) { - if (typeof value === 'number') return this.powS(value); - return this.powM(value); - }; +function getScaleByColumn(matrix) { + const scale = []; + for (let j = 0; j < matrix.columns; j++) { + let sum = 0; + for (let i = 0; i < matrix.rows; i++) { + sum += Math.pow(matrix.get(i, j), 2) / (matrix.rows - 1); + } + scale.push(Math.sqrt(sum)); + } + return scale; +} - AbstractMatrix.prototype.powS = function powS(value) { - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.pow(this.get(i, j), value)); - } +function scaleByColumn(matrix, scale) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) / scale[j]); } - return this; - }; + } +} - AbstractMatrix.prototype.powM = function powM(matrix) { - matrix = Matrix.checkMatrix(matrix); - if (this.rows !== matrix.rows || - this.columns !== matrix.columns) { - throw new RangeError('Matrices dimensions must be equal'); +function getScaleAll(matrix) { + const divider = matrix.size - 1; + let sum = 0; + for (let j = 0; j < matrix.columns; j++) { + for (let i = 0; i < matrix.rows; i++) { + sum += Math.pow(matrix.get(i, j), 2) / divider; } - for (let i = 0; i < this.rows; i++) { - for (let j = 0; j < this.columns; j++) { - this.set(i, j, Math.pow(this.get(i, j), matrix.get(i, j))); - } + } + return Math.sqrt(sum); +} + +function scaleAll(matrix, scale) { + for (let i = 0; i < matrix.rows; i++) { + for (let j = 0; j < matrix.columns; j++) { + matrix.set(i, j, matrix.get(i, j) / scale); } - return this; - }; + } } // CONCATENATED MODULE: ./node_modules/ml-matrix/src/matrix.js @@ -3659,6 +3693,10 @@ class matrix_AbstractMatrix { return this.rows === this.columns; } + isEmpty() { + return this.rows === 0 || this.columns === 0; + } + isSymmetric() { if (this.isSquare()) { for (let i = 0; i < this.rows; i++) { @@ -3996,6 +4034,9 @@ class matrix_AbstractMatrix { } max() { + if (this.isEmpty()) { + return NaN; + } let v = this.get(0, 0); for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { @@ -4008,6 +4049,7 @@ class matrix_AbstractMatrix { } maxIndex() { + checkNonEmpty(this); let v = this.get(0, 0); let idx = [0, 0]; for (let i = 0; i < this.rows; i++) { @@ -4023,6 +4065,9 @@ class matrix_AbstractMatrix { } min() { + if (this.isEmpty()) { + return NaN; + } let v = this.get(0, 0); for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { @@ -4035,6 +4080,7 @@ class matrix_AbstractMatrix { } minIndex() { + checkNonEmpty(this); let v = this.get(0, 0); let idx = [0, 0]; for (let i = 0; i < this.rows; i++) { @@ -4051,6 +4097,9 @@ class matrix_AbstractMatrix { maxRow(row) { checkRowIndex(this, row); + if (this.isEmpty()) { + return NaN; + } let v = this.get(row, 0); for (let i = 1; i < this.columns; i++) { if (this.get(row, i) > v) { @@ -4062,6 +4111,7 @@ class matrix_AbstractMatrix { maxRowIndex(row) { checkRowIndex(this, row); + checkNonEmpty(this); let v = this.get(row, 0); let idx = [row, 0]; for (let i = 1; i < this.columns; i++) { @@ -4075,6 +4125,9 @@ class matrix_AbstractMatrix { minRow(row) { checkRowIndex(this, row); + if (this.isEmpty()) { + return NaN; + } let v = this.get(row, 0); for (let i = 1; i < this.columns; i++) { if (this.get(row, i) < v) { @@ -4086,6 +4139,7 @@ class matrix_AbstractMatrix { minRowIndex(row) { checkRowIndex(this, row); + checkNonEmpty(this); let v = this.get(row, 0); let idx = [row, 0]; for (let i = 1; i < this.columns; i++) { @@ -4099,6 +4153,9 @@ class matrix_AbstractMatrix { maxColumn(column) { checkColumnIndex(this, column); + if (this.isEmpty()) { + return NaN; + } let v = this.get(0, column); for (let i = 1; i < this.rows; i++) { if (this.get(i, column) > v) { @@ -4110,6 +4167,7 @@ class matrix_AbstractMatrix { maxColumnIndex(column) { checkColumnIndex(this, column); + checkNonEmpty(this); let v = this.get(0, column); let idx = [0, column]; for (let i = 1; i < this.rows; i++) { @@ -4123,6 +4181,9 @@ class matrix_AbstractMatrix { minColumn(column) { checkColumnIndex(this, column); + if (this.isEmpty()) { + return NaN; + } let v = this.get(0, column); for (let i = 1; i < this.rows; i++) { if (this.get(i, column) < v) { @@ -4134,6 +4195,7 @@ class matrix_AbstractMatrix { minColumnIndex(column) { checkColumnIndex(this, column); + checkNonEmpty(this); let v = this.get(0, column); let idx = [0, column]; for (let i = 1; i < this.rows; i++) { @@ -4452,7 +4514,9 @@ class matrix_AbstractMatrix { let newMatrix = new matrix_Matrix(this.rows, this.columns); for (let i = 0; i < this.rows; i++) { const row = this.getRow(i); - ml_array_rescale_lib_es6(row, { min, max, output: row }); + if (row.length > 0) { + ml_array_rescale_lib_es6(row, { min, max, output: row }); + } newMatrix.setRow(i, row); } return newMatrix; @@ -4469,11 +4533,13 @@ class matrix_AbstractMatrix { let newMatrix = new matrix_Matrix(this.rows, this.columns); for (let i = 0; i < this.columns; i++) { const column = this.getColumn(i); - ml_array_rescale_lib_es6(column, { - min: min, - max: max, - output: column, - }); + if (column.length) { + ml_array_rescale_lib_es6(column, { + min: min, + max: max, + output: column, + }); + } newMatrix.setColumn(i, column); } return newMatrix; @@ -4526,6 +4592,18 @@ class matrix_AbstractMatrix { return result; } + kroneckerSum(other) { + other = matrix_Matrix.checkMatrix(other); + if (!this.isSquare() || !other.isSquare()) { + throw new Error('Kronecker Sum needs two Square Matrices'); + } + let m = this.rows; + let n = other.rows; + let AxI = this.kroneckerProduct(matrix_Matrix.eye(n, n)); + let IxB = matrix_Matrix.eye(m, m).kroneckerProduct(other); + return AxI.add(IxB); + } + transpose() { let result = new matrix_Matrix(this.columns, this.rows); for (let i = 0; i < this.rows; i++) { @@ -4616,6 +4694,9 @@ class matrix_AbstractMatrix { setSubMatrix(matrix, startRow, startColumn) { matrix = matrix_Matrix.checkMatrix(matrix); + if (matrix.isEmpty()) { + return this; + } let endRow = startRow + matrix.rows - 1; let endColumn = startColumn + matrix.columns - 1; checkRange(this, startRow, endRow, startColumn, endColumn); @@ -4836,6 +4917,10 @@ class matrix_AbstractMatrix { throw new Error(`invalid option: ${by}`); } } + + toString(options) { + return inspectMatrixWithOptions(this, options); + } } matrix_AbstractMatrix.prototype.klass = 'Matrix'; @@ -4863,11 +4948,12 @@ class matrix_Matrix extends matrix_AbstractMatrix { constructor(nRows, nColumns) { super(); if (matrix_Matrix.isMatrix(nRows)) { + // eslint-disable-next-line no-constructor-return return nRows.clone(); - } else if (Number.isInteger(nRows) && nRows > 0) { + } else if (Number.isInteger(nRows) && nRows >= 0) { // Create an empty matrix this.data = []; - if (Number.isInteger(nColumns) && nColumns > 0) { + if (Number.isInteger(nColumns) && nColumns >= 0) { for (let i = 0; i < nRows; i++) { this.data.push(new Float64Array(nColumns)); } @@ -4878,8 +4964,8 @@ class matrix_Matrix extends matrix_AbstractMatrix { // Copy the values from the 2D array const arrayData = nRows; nRows = arrayData.length; - nColumns = arrayData[0].length; - if (typeof nColumns !== 'number' || nColumns === 0) { + nColumns = nRows ? arrayData[0].length : 0; + if (typeof nColumns !== 'number') { throw new TypeError( 'Data must be a 2D array with at least one element', ); @@ -4898,7 +4984,6 @@ class matrix_Matrix extends matrix_AbstractMatrix { } this.rows = nRows; this.columns = nColumns; - return this; } set(rowIndex, columnIndex, value) { @@ -4912,9 +4997,6 @@ class matrix_Matrix extends matrix_AbstractMatrix { removeRow(index) { checkRowIndex(this, index); - if (this.rows === 1) { - throw new RangeError('A matrix cannot have less than one row'); - } this.data.splice(index, 1); this.rows -= 1; return this; @@ -4926,7 +5008,7 @@ class matrix_Matrix extends matrix_AbstractMatrix { index = this.rows; } checkRowIndex(this, index, true); - array = Float64Array.from(checkRowVector(this, array, true)); + array = Float64Array.from(checkRowVector(this, array)); this.data.splice(index, 0, array); this.rows += 1; return this; @@ -4934,9 +5016,6 @@ class matrix_Matrix extends matrix_AbstractMatrix { removeColumn(index) { checkColumnIndex(this, index); - if (this.columns === 1) { - throw new RangeError('A matrix cannot have less than one column'); - } for (let i = 0; i < this.rows; i++) { const newRow = new Float64Array(this.columns - 1); for (let j = 0; j < index; j++) { @@ -5346,6 +5425,10 @@ class svd_SingularValueDecomposition { constructor(value, options = {}) { value = WrapperMatrix2D_WrapperMatrix2D.checkMatrix(value); + if (value.isEmpty()) { + throw new Error('Matrix must be non-empty'); + } + let m = value.rows; let n = value.columns; @@ -5907,20 +5990,20 @@ function gradientFunction( evaluatedData, params, gradientDifference, - paramFunction + paramFunction, ) { const n = params.length; const m = data.x.length; - var ans = new Array(n); + let ans = new Array(n); - for (var param = 0; param < n; param++) { + for (let param = 0; param < n; param++) { ans[param] = new Array(m); - var auxParams = params.concat(); + let auxParams = params.slice(); auxParams[param] += gradientDifference; - var funcParam = paramFunction(auxParams); + let funcParam = paramFunction(auxParams); - for (var point = 0; point < m; point++) { + for (let point = 0; point < m; point++) { ans[param][point] = evaluatedData[point] - funcParam(data.x[point]); } } @@ -5937,9 +6020,9 @@ function gradientFunction( function matrixFunction(data, evaluatedData) { const m = data.x.length; - var ans = new Array(m); + let ans = new Array(m); - for (var point = 0; point < m; point++) { + for (let point = 0; point < m; point++) { ans[point] = [data.y[point] - evaluatedData[point]]; } @@ -5961,24 +6044,28 @@ function step( params, damping, gradientDifference, - parameterizedFunction + parameterizedFunction, ) { - var value = damping * gradientDifference * gradientDifference; - var identity = matrix_Matrix.eye(params.length, params.length, value); + let value = damping * gradientDifference * gradientDifference; + let identity = matrix_Matrix.eye(params.length, params.length, value); const func = parameterizedFunction(params); - var evaluatedData = data.x.map((e) => func(e)); - var gradientFunc = gradientFunction( + let evaluatedData = new Float64Array(data.x.length); + for (let i = 0; i < data.x.length; i++) { + evaluatedData[i] = func(data.x[i]); + } + + let gradientFunc = gradientFunction( data, evaluatedData, params, gradientDifference, - parameterizedFunction + parameterizedFunction, ); - var matrixFunc = matrixFunction(data, evaluatedData); - var inverseMatrix = inverse( - identity.add(gradientFunc.mmul(gradientFunc.transpose())) + let matrixFunc = matrixFunction(data, evaluatedData); + let inverseMatrix = inverse( + identity.add(gradientFunc.mmul(gradientFunc.transpose())), ); params = new matrix_Matrix([params]); @@ -5987,7 +6074,7 @@ function step( .mmul(gradientFunc) .mmul(matrixFunc) .mul(gradientDifference) - .transpose() + .transpose(), ); return params.to1DArray(); @@ -5998,6 +6085,8 @@ function step( + + /** * Curve fitting algorithm * @param {{x:Array, y:Array}} data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ] @@ -6015,7 +6104,7 @@ function step( function levenbergMarquardt( data, parameterizedFunction, - options = {} + options = {}, ) { let { maxIterations = 100, @@ -6024,7 +6113,7 @@ function levenbergMarquardt( errorTolerance = 10e-3, minValues, maxValues, - initialValues + initialValues, } = options; if (damping <= 0) { @@ -6032,19 +6121,19 @@ function levenbergMarquardt( } else if (!data.x || !data.y) { throw new Error('The data parameter must have x and y elements'); } else if ( - !Array.isArray(data.x) || + !isAnyArray(data.x) || data.x.length < 2 || - !Array.isArray(data.y) || + !isAnyArray(data.y) || data.y.length < 2 ) { throw new Error( - 'The data parameter elements must be an array with more than 2 points' + 'The data parameter elements must be an array with more than 2 points', ); } else if (data.x.length !== data.y.length) { throw new Error('The data parameter elements must have the same size'); } - var parameters = + let parameters = initialValues || new Array(parameterizedFunction.length).fill(1); let parLen = parameters.length; maxValues = maxValues || new Array(parLen).fill(Number.MAX_SAFE_INTEGER); @@ -6054,31 +6143,28 @@ function levenbergMarquardt( throw new Error('minValues and maxValues must be the same size'); } - if (!Array.isArray(parameters)) { + if (!isAnyArray(parameters)) { throw new Error('initialValues must be an array'); } - var error = errorCalculation(data, parameters, parameterizedFunction); + let error = errorCalculation(data, parameters, parameterizedFunction); - var converged = error <= errorTolerance; + let converged = error <= errorTolerance; - for ( - var iteration = 0; - iteration < maxIterations && !converged; - iteration++ - ) { + let iteration; + for (iteration = 0; iteration < maxIterations && !converged; iteration++) { parameters = step( data, parameters, damping, gradientDifference, - parameterizedFunction + parameterizedFunction, ); for (let k = 0; k < parLen; k++) { parameters[k] = Math.min( Math.max(minValues[k], parameters[k]), - maxValues[k] + maxValues[k], ); } @@ -6090,7 +6176,7 @@ function levenbergMarquardt( return { parameterValues: parameters, parameterError: error, - iterations: iteration + iterations: iteration, }; } diff --git a/lib/umap-js.min.js b/lib/umap-js.min.js index 617fb4a..2d167ec 100644 --- a/lib/umap-js.min.js +++ b/lib/umap-js.min.js @@ -1 +1 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.UMAP=e():t.UMAP=e()}(this,function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=5)}([function(t,e,r){"use strict";const n=Object.prototype.toString;t.exports=function(t){return n.call(t).endsWith("Array]")}},function(t,e,r){"use strict";var n=this&&this.__values||function(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function o(t,e){return Math.floor(e()*t)}function i(t){for(var e=[],r=0;re?t[r]:e;return e},e.max2d=function(t){for(var e=0,r=0;re?t[r][n]:e;return e},e.rejectionSample=function(t,e,r){for(var n=a(t),i=0;i=s[0])return 0;for(var a=0;a=s[0])return 0;s[0]=r,i[0]=n,a[0]=o;for(var h=0,u=0;;){var l=2*h+1,f=l+1,c=t[0][0].length;if(l>=c)break;if(f>=c){if(!(s[l]>r))break;u=l}else if(s[l]>=s[f]){if(!(rr.length;a++)1===o[a]&&n[a]=0?(o[s]=0,Math.floor(r[s])):-1}},function(t,e,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(t,e,r,n){void 0===n&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){void 0===n&&(n=r),t[n]=e[r]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),s=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)"default"!==r&&Object.hasOwnProperty.call(t,r)&&o(e,t,r);return i(e,t),e},a=this&&this.__read||function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,o,i=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s},h=this&&this.__values||function(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(e,"__esModule",{value:!0}),e.getCSR=e.normalize=e.eliminateZeros=e.multiplyScalar=e.maximum=e.subtract=e.add=e.pairwiseMultiply=e.identity=e.transpose=e.SparseMatrix=void 0;var u=s(r(1)),l=function(){function t(t,e,r,n){if(this.entries=new Map,this.nRows=0,this.nCols=0,t.length!==e.length||t.length!==r.length)throw new Error("rows, cols and values arrays must all have the same length");this.nRows=n[0],this.nCols=n[1];for(var o=0;oe?t:e})},e.multiplyScalar=function(t,e){return t.map(function(t){return t*e})},e.eliminateZeros=function(t){for(var e=new Set,r=t.getValues(),n=t.getRows(),o=t.getCols(),i=0;ie?t[r]:e;return t.map(function(t){return t/e})},n.l1=function(t){for(var e=0,r=0;r0)&&!(n=i.next()).done;)s.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s},a=this&&this.__spread||function(){for(var t=[],e=0;e=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(e,"__esModule",{value:!0}),e.searchFlatTree=e.makeLeafArray=e.makeForest=e.FlatTree=void 0;var u=i(r(1)),l=function(){return function(t,e,r,n){this.hyperplanes=t,this.offsets=e,this.children=r,this.indices=n}}();function f(t,e,r,n){for(var o=e,i=0;i0?0:1}e.FlatTree=l,e.makeForest=function(t,e,r,n){var o=Math.max(10,e);return u.range(r).map(function(e,r){return function(t,e,r,n){void 0===e&&(e=30);var o=u.range(t.length);return function t(e,r,n,o,i){if(void 0===n&&(n=30),r.length>n){var s=function(t,e,r){var n=t[0].length,o=u.tauRandInt(e.length,r),i=u.tauRandInt(e.length,r);i=(i+=o===i?1:0)%e.length;for(var s=e[o],a=e[i],h=0,l=u.zeros(n),f=0;f0?(p[f]=0,c+=1):(p[f]=1,m+=1)}var d=u.zeros(c),y=u.zeros(m);c=0,m=0;for(var f=0;f0){var n=[];try{for(var o=h(t),i=o.next();!i.done;i=o.next()){var s=i.value;n.push.apply(n,a(s.indices))}}catch(t){e={error:t}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return n}return[[-1]]},e.searchFlatTree=function(t,e,r){for(var n=0;e.children[n][0]>0;)n=0===f(e.hyperplanes[n],e.offsets[n],t,r)?e.children[n][0]:e.children[n][1];var o=-1*e.children[n][0];return e.indices[o]}},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=r(6);Object.defineProperty(e,"UMAP",{enumerable:!0,get:function(){return n.UMAP}})},function(t,e,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(t,e,r,n){void 0===n&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){void 0===n&&(n=r),t[n]=e[r]}),o=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)"default"!==r&&Object.hasOwnProperty.call(t,r)&&n(e,t,r);return o(e,t),e},s=this&&this.__awaiter||function(t,e,r,n){return new(r||(r=Promise))(function(o,i){function s(t){try{h(n.next(t))}catch(t){i(t)}}function a(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r(function(t){t(e)})).then(s,a)}h((n=n.apply(t,e||[])).next())})},a=this&&this.__generator||function(t,e){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,n=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0)&&!(n=i.next()).done;)s.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s},u=this&&this.__spread||function(){for(var t=[],e=0;e0&&o.set(i,u,l)}var f=c.transpose(o);return c.maximum(o,f)},t.prototype.transform=function(t){var e=this,r=this.X;if(void 0===r||0===r.length)throw new Error("No data has been fit.");var n=Math.floor(this.nNeighbors*this.transformQueueSize);n=Math.min(r.length,n);var o=m.initializeSearch(this.rpForest,r,t,n,this.initFromRandom,this.initFromTree,this.random),i=this.search(r,this.searchGraph,o,t),s=f.deheapSort(i),a=s.indices,h=s.weights;a=a.map(function(t){return t.slice(0,e.nNeighbors)}),h=h.map(function(t){return t.slice(0,e.nNeighbors)});var u=Math.max(0,this.localConnectivity-1),l=this.smoothKNNDistance(h,this.nNeighbors,u),p=l.sigmas,w=l.rhos,d=this.computeMembershipStrengths(a,h,p,w),y=d.rows,v=d.cols,b=d.vals,M=[t.length,r.length],S=new c.SparseMatrix(y,v,b,M),x=c.normalize(S,"l1"),E=c.getCSR(x),k=t.length,z=R(g.reshape2d(E.indices,k,this.nNeighbors),g.reshape2d(E.values,k,this.nNeighbors),this.embedding),N=this.nEpochs?this.nEpochs/3:S.nRows<=1e4?100:30,A=S.getValues().reduce(function(t,e){return e>t?e:t},0);S=S.map(function(t){return t0});if(m.length>=r){var p=Math.floor(r),w=r-p;p>0?(s[h]=m[p-1],w>1e-5&&(s[h]+=w*(m[p]-m[p-1]))):s[h]=w*m[0]}else m.length>0&&(s[h]=g.max(m));for(var d=0;d0?Math.exp(-b/f):1}if(Math.abs(y-i)<1e-5)break;y>i?f=(u+(l=f))/2:(u=f,l===1/0?f*=2:f=(u+l)/2)}if(a[h]=f,s[h]>0){var M=g.mean(c);a[h]<.001*M&&(a[h]=.001*M)}else{var S=g.mean(t.map(g.mean));a[h]<.001*S&&(a[h]=.001*S)}}return{sigmas:a,rhos:s}},t.prototype.computeMembershipStrengths=function(t,e,r,n){for(var o=t.length,i=t[0].length,s=g.zeros(o*i),a=g.zeros(o*i),h=g.zeros(o*i),u=0;u0&&(r[n]=e/o[n])}),r},t.prototype.assignOptimizationStateParameters=function(t){Object.assign(this.optimizationState,t)},t.prototype.prepareForOptimizationLoop=function(){var t=this.repulsionStrength,e=this.learningRate,r=this.negativeSampleRate,n=this.optimizationState,o=n.epochsPerSample,i=n.headEmbedding,s=n.tailEmbedding,a=i[0].length,h=i.length===s.length,l=o.map(function(t){return t/r}),f=u(l),c=u(o);this.assignOptimizationStateParameters({epochOfNextSample:c,epochOfNextNegativeSample:f,epochsPerNegativeSample:l,moveOther:h,initialAlpha:e,alpha:e,gamma:t,dim:a})},t.prototype.initializeOptimization=function(){var t=this.embedding,e=this.embedding,r=this.optimizationState,n=r.head,o=r.tail,i=r.epochsPerSample,s=this.getNEpochs(),a=this.graph.nCols,h=S(this.spread,this.minDist),u=h.a,l=h.b;this.assignOptimizationStateParameters({headEmbedding:t,tailEmbedding:e,head:n,tail:o,epochsPerSample:i,a:u,b:l,nEpochs:s,nVertices:a})},t.prototype.optimizeLayoutStep=function(t){for(var e=this.optimizationState,r=e.head,n=e.tail,o=e.headEmbedding,i=e.tailEmbedding,s=e.epochsPerSample,a=e.epochOfNextSample,h=e.epochOfNextNegativeSample,u=e.epochsPerNegativeSample,l=e.moveOther,f=e.initialAlpha,c=e.alpha,m=e.gamma,p=e.a,w=e.b,d=e.dim,y=e.nEpochs,v=e.nVertices,S=0;St)){var x=r[S],E=n[S],R=o[x],k=i[E],z=M(R,k),N=0;z>0&&(N=-2*p*w*Math.pow(z,w-1),N/=p*Math.pow(z,w)+1);for(var A=0;A0)F=2*m*w,F/=(.001+C)*(p*Math.pow(C,w)+1);else if(x===O)continue;for(A=0;A0&&(_=b(F*(R[A]-T[A]),4)),R[A]+=_*c}}h[S]+=P*u[S]}return e.alpha=f*(1-t/y),e.currentEpoch+=1,o},t.prototype.optimizeLayoutAsync=function(t){var e=this;return void 0===t&&(t=function(){return!0}),new Promise(function(r,n){var o=function(){return s(e,void 0,void 0,function(){var e,i,s,h,u,l;return a(this,function(a){try{if(e=this.optimizationState,i=e.nEpochs,s=e.currentEpoch,this.embedding=this.optimizeLayoutStep(s),h=this.optimizationState.currentEpoch,u=!1===t(h),l=h===i,u||l)return[2,r(l)];setTimeout(function(){return o()},0)}catch(t){n(t)}return[2]})})};setTimeout(function(){return o()},0)})},t.prototype.optimizeLayout=function(t){void 0===t&&(t=function(){return!0});for(var e=!1,r=[];!e;){var n=this.optimizationState,o=n.nEpochs,i=n.currentEpoch;r=this.optimizeLayoutStep(i);var s=this.optimizationState.currentEpoch,a=!1===t(s);e=s===o||a}return r},t.prototype.getNEpochs=function(){var t=this.graph;if(this.nEpochs>0)return this.nEpochs;var e=t.nRows;return e<=2500?500:e<=5e3?400:e<=7500?300:200},t}();function y(t,e){for(var r=0,n=0;ne?e:t<-e?-e:t}function M(t,e){for(var r=0,n=0;n=e?Math.exp(-(r[o]-e)/t):n}),o={x:r,y:n},i={damping:1.5,initialValues:[.5,.5],gradientDifference:.1,maxIterations:100,errorTolerance:.01},s=w.default(o,function(t){var e=h(t,2),r=e[0],n=e[1];return function(t){return 1/(1+r*Math.pow(t,2*n))}},i).parameterValues,a=h(s,2);return{a:a[0],b:a[1]}}function x(t,e,r,n){return void 0===r&&(r=1),void 0===n&&(n=5),t.map(function(t,o,i){return-1===e[o]||-1===e[i]?t*Math.exp(-r):e[o]!==e[i]?t*Math.exp(-n):t})}function E(t){t=c.normalize(t,"max");var e=c.transpose(t),r=c.pairwiseMultiply(e,t);return t=c.add(t,c.subtract(e,r)),c.eliminateZeros(t)}function R(t,e,r){for(var n=g.zeros(t.length).map(function(t){return g.zeros(r[0].length)}),o=0;o=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(e,"__esModule",{value:!0}),e.initializeSearch=e.makeInitializedNNSearch=e.makeInitializations=e.makeNNDescent=void 0;var a=i(r(2)),h=i(r(3)),u=i(r(4)),l=i(r(1));e.makeNNDescent=function(t,e){return function(r,n,o,i,s,h,u,f){void 0===i&&(i=10),void 0===s&&(s=50),void 0===h&&(h=.001),void 0===u&&(u=.5),void 0===f&&(f=!0);for(var c=r.length,m=a.makeHeap(r.length,o),p=0;pe&&(e=t[r]);return e};var a=function(t){if(!i()(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");for(var e=t[0],r=1;r1&&void 0!==arguments[1]?arguments[1]:{};if(!i()(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");if(void 0!==r.output){if(!i()(r.output))throw new TypeError("output option must be an array if specified");e=r.output}else e=new Array(t.length);var n=a(t),o=s(t);if(n===o)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var h=r.min,u=void 0===h?r.autoMinMax?n:0:h,l=r.max,f=void 0===l?r.autoMinMax?o:1:l;if(u>=f)throw new RangeError("min option must be smaller than max option");for(var c=(f-u)/(o-n),m=0;mn)throw new RangeError("Row index out of range")}function l(t,e,r){let n=r?t.columns:t.columns-1;if(e<0||e>n)throw new RangeError("Column index out of range")}function f(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.columns)throw new RangeError("vector size must be the same as the number of columns");return e}function c(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.rows)throw new RangeError("vector size must be the same as the number of rows");return e}function m(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for row indices");if(e.some(e=>e<0||e>=t.rows))throw new RangeError("row indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function p(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for column indices");if(e.some(e=>e<0||e>=t.columns))throw new RangeError("column indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function g(t,e,r,n,o){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(d("startRow",e),d("endRow",r),d("startColumn",n),d("endColumn",o),e>r||n>o||e<0||e>=t.rows||r<0||r>=t.rows||n<0||n>=t.columns||o<0||o>=t.columns)throw new RangeError("Submatrix indices are out of range")}function w(t,e=0){let r=[];for(let n=0;n=o)throw new RangeError("min must be smaller than max");let s=o-n,a=new E(t,e);for(let r=0;rr?(o=!0,r=e):(n=!1,o=!0);t++}return n}isReducedEchelonForm(){let t=0,e=0,r=-1,n=!0,o=!1;for(;tr?(o=!0,r=e):(n=!1,o=!0);for(let r=e+1;rt.get(n,r)&&(n=o);if(0===t.get(n,r))r++;else{t.swapRows(e,n);let o=t.get(e,r);for(let n=r;n=0;)if(0===t.maxRow(n))n--;else{let o=0,i=!1;for(;ot&&(t=this.get(e,r));return t}maxIndex(){let t=this.get(0,0),e=[0,0];for(let r=0;rt&&(t=this.get(r,n),e[0]=r,e[1]=n);return e}min(){let t=this.get(0,0);for(let e=0;ee&&(e=this.get(t,r));return e}maxRowIndex(t){u(this,t);let e=this.get(t,0),r=[t,0];for(let n=1;ne&&(e=this.get(t,n),r[1]=n);return r}minRow(t){u(this,t);let e=this.get(t,0);for(let r=1;re&&(e=this.get(r,t));return e}maxColumnIndex(t){l(this,t);let e=this.get(0,t),r=[0,t];for(let n=1;ne&&(e=this.get(n,t),r[0]=n);return r}minColumn(t){l(this,t);let e=this.get(0,t);for(let r=1;r=r)throw new RangeError("min must be smaller than max");let n=new E(this.rows,this.columns);for(let t=0;t=r)throw new RangeError("min must be smaller than max");let n=new E(this.rows,this.columns);for(let t=0;tr||e<0||e>=this.columns||r<0||r>=this.columns)throw new RangeError("Argument out of range");let n=new E(t.length,r-e+1);for(let o=0;o=this.rows)throw new RangeError(`Row index out of range: ${t[o]}`);n.set(o,i-e,this.get(t[o],i))}return n}subMatrixColumn(t,e,r){if(void 0===e&&(e=0),void 0===r&&(r=this.rows-1),e>r||e<0||e>=this.rows||r<0||r>=this.rows)throw new RangeError("Argument out of range");let n=new E(r-e+1,t.length);for(let o=0;o=this.columns)throw new RangeError(`Column index out of range: ${t[o]}`);n.set(i-e,o,this.get(i,t[o]))}return n}setSubMatrix(t,e,r){g(this,e,e+(t=E.checkMatrix(t)).rows-1,r,r+t.columns-1);for(let n=0;n0){if(this.data=[],!(Number.isInteger(e)&&e>0))throw new TypeError("nColumns must be a positive integer");for(let r=0;r>t);return this},R.prototype.signPropagatingRightShiftM=function(t){if(t=k.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>t.get(e,r));return this},R.signPropagatingRightShift=function(t,e){return new k(t).signPropagatingRightShift(e)},R.prototype.rightShift=function(t){return"number"==typeof t?this.rightShiftS(t):this.rightShiftM(t)},R.prototype.rightShiftS=function(t){for(let e=0;e>>t);return this},R.prototype.rightShiftM=function(t){if(t=k.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>>t.get(e,r));return this},R.rightShift=function(t,e){return new k(t).rightShift(e)},R.prototype.zeroFillRightShift=R.prototype.rightShift,R.prototype.zeroFillRightShiftS=R.prototype.rightShiftS,R.prototype.zeroFillRightShiftM=R.prototype.rightShiftM,R.zeroFillRightShift=R.rightShift,R.prototype.not=function(){for(let t=0;tMath.abs(h[o])&&(o=e);if(o!==r){for(n=0;n=0;o--){for(n=0;ne?n.set(o,e,t.get(o,e)):o===e?n.set(o,e,1):n.set(o,e,0);return n}get upperTriangularMatrix(){let t=this.LU,e=t.rows,r=t.columns,n=new E(e,r);for(let o=0;oMath.abs(e)?(r=e/t,Math.abs(t)*Math.sqrt(1+r*r)):0!==e?(r=t/e,Math.abs(e)*Math.sqrt(1+r*r)):0}class _{constructor(t){let e,r,n,o,i=(t=z.checkMatrix(t)).clone(),s=t.rows,a=t.columns,h=new Float64Array(a);for(n=0;n=0;i--){for(o=0;o=0;r--){for(t=0;t=0;t--)if(0!==m[t]){for(let e=t+1;e=0;t--){if(t0;){let t,e;for(t=S-2;t>=-1&&-1!==t;t--){const e=Number.MIN_VALUE+k*Math.abs(m[t]+Math.abs(m[t+1]));if(Math.abs(w[t])<=e||Number.isNaN(w[t])){w[t]=0;break}}if(t===S-2)e=4;else{let r;for(r=S-1;r>=t&&r!==t;r--){let e=(r!==S?Math.abs(w[r]):0)+(r!==t+1?Math.abs(w[r-1]):0);if(Math.abs(m[r])<=k*e){m[r]=0;break}}r===t?e=3:r===S-1?e=1:(e=2,t=r)}switch(t++,e){case 1:{let e=w[S-2];w[S-2]=0;for(let r=S-2;r>=t;r--){let o=A(m[r],e),i=m[r]/o,s=e/o;if(m[r]=o,r!==t&&(e=-s*w[r-1],w[r-1]=i*w[r-1]),u)for(let t=0;t=m[t+1]);){let e=m[t];if(m[t]=m[t+1],m[t+1]=e,u&&te&&o.set(i,r,t.get(i,r)/this.s[r]);let i=this.U,s=i.rows,a=i.columns,h=new E(r,s);for(let t=0;tt&&e++;return e}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return E.diag(this.s)}}function j(t,e=!1){return t=z.checkMatrix(t),e?new P(t).inverse():function(t,e,r=!1){return t=z.checkMatrix(t),e=z.checkMatrix(e),r?new P(t).solve(e):t.isSquare()?new N(t).solve(e):new _(t).solve(e)}(t,E.eye(t.rows))}function O(t,e,r,n,o){var i=r*n*n,s=E.eye(e.length,e.length,i);const a=o(e);var h=t.x.map(t=>a(t)),u=function(t,e,r,n,o){const i=r.length,s=t.x.length;for(var a=new Array(i),h=0;h=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function o(t,e){return Math.floor(e()*t)}function i(t){for(var e=[],r=0;re?t[r]:e;return e},e.max2d=function(t){for(var e=0,r=0;re?t[r][n]:e;return e},e.rejectionSample=function(t,e,r){for(var n=a(t),i=0;i=s[0])return 0;for(var a=0;a=s[0])return 0;s[0]=r,i[0]=n,a[0]=o;for(var h=0,u=0;;){var l=2*h+1,f=l+1,c=t[0][0].length;if(l>=c)break;if(f>=c){if(!(s[l]>r))break;u=l}else if(s[l]>=s[f]){if(!(rr.length;a++)1===o[a]&&n[a]=0?(o[s]=0,Math.floor(r[s])):-1}},function(t,e,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(t,e,r,n){void 0===n&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){void 0===n&&(n=r),t[n]=e[r]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),s=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)"default"!==r&&Object.hasOwnProperty.call(t,r)&&o(e,t,r);return i(e,t),e},a=this&&this.__read||function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,o,i=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s},h=this&&this.__values||function(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(e,"__esModule",{value:!0}),e.getCSR=e.normalize=e.eliminateZeros=e.multiplyScalar=e.maximum=e.subtract=e.add=e.pairwiseMultiply=e.identity=e.transpose=e.SparseMatrix=void 0;var u=s(r(0)),l=function(){function t(t,e,r,n){if(this.entries=new Map,this.nRows=0,this.nCols=0,t.length!==e.length||t.length!==r.length)throw new Error("rows, cols and values arrays must all have the same length");this.nRows=n[0],this.nCols=n[1];for(var o=0;oe?t:e}))},e.multiplyScalar=function(t,e){return t.map((function(t){return t*e}))},e.eliminateZeros=function(t){for(var e=new Set,r=t.getValues(),n=t.getRows(),o=t.getCols(),i=0;ie?t[r]:e;return t.map((function(t){return t/e}))},n.l1=function(t){for(var e=0,r=0;r0)&&!(n=i.next()).done;)s.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s},a=this&&this.__spread||function(){for(var t=[],e=0;e=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(e,"__esModule",{value:!0}),e.searchFlatTree=e.makeLeafArray=e.makeForest=e.FlatTree=void 0;var u=i(r(0)),l=function(t,e,r,n){this.hyperplanes=t,this.offsets=e,this.children=r,this.indices=n};function f(t,e,r,n){for(var o=e,i=0;i0?0:1}e.FlatTree=l,e.makeForest=function(t,e,r,n){var o=Math.max(10,e);return u.range(r).map((function(e,r){return function(t,e,r,n){void 0===e&&(e=30);var o=u.range(t.length);return function t(e,r,n,o,i){void 0===n&&(n=30);if(r.length>n){var s=function(t,e,r){var n=t[0].length,o=u.tauRandInt(e.length,r),i=u.tauRandInt(e.length,r);i=(i+=o===i?1:0)%e.length;for(var s=e[o],a=e[i],h=0,l=u.zeros(n),f=0;f0?(p[f]=0,c+=1):(p[f]=1,m+=1)}var d=u.zeros(c),y=u.zeros(m);c=0,m=0;for(f=0;f0){var n=[];try{for(var o=h(t),i=o.next();!i.done;i=o.next()){var s=i.value;n.push.apply(n,a(s.indices))}}catch(t){e={error:t}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return n}return[[-1]]},e.searchFlatTree=function(t,e,r){for(var n=0;e.children[n][0]>0;){n=0===f(e.hyperplanes[n],e.offsets[n],t,r)?e.children[n][0]:e.children[n][1]}var o=-1*e.children[n][0];return e.indices[o]}},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=r(5);Object.defineProperty(e,"UMAP",{enumerable:!0,get:function(){return n.UMAP}})},function(t,e,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(t,e,r,n){void 0===n&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){void 0===n&&(n=r),t[n]=e[r]}),o=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)"default"!==r&&Object.hasOwnProperty.call(t,r)&&n(e,t,r);return o(e,t),e},s=this&&this.__awaiter||function(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{h(n.next(t))}catch(t){i(t)}}function a(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}h((n=n.apply(t,e||[])).next())}))},a=this&&this.__generator||function(t,e){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,n=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0)&&!(n=i.next()).done;)s.push(n.value)}catch(t){o={error:t}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s},u=this&&this.__spread||function(){for(var t=[],e=0;e0&&o.set(i,u,l)}var f=c.transpose(o);return c.maximum(o,f)},t.prototype.transform=function(t){var e=this,r=this.X;if(void 0===r||0===r.length)throw new Error("No data has been fit.");var n=Math.floor(this.nNeighbors*this.transformQueueSize);n=Math.min(r.length,n);var o=m.initializeSearch(this.rpForest,r,t,n,this.initFromRandom,this.initFromTree,this.random),i=this.search(r,this.searchGraph,o,t),s=f.deheapSort(i),a=s.indices,h=s.weights;a=a.map((function(t){return t.slice(0,e.nNeighbors)})),h=h.map((function(t){return t.slice(0,e.nNeighbors)}));var u=Math.max(0,this.localConnectivity-1),l=this.smoothKNNDistance(h,this.nNeighbors,u),p=l.sigmas,w=l.rhos,d=this.computeMembershipStrengths(a,h,p,w),y=d.rows,v=d.cols,b=d.vals,M=[t.length,r.length],S=new c.SparseMatrix(y,v,b,M),x=c.normalize(S,"l1"),E=c.getCSR(x),k=t.length,N=R(g.reshape2d(E.indices,k,this.nNeighbors),g.reshape2d(E.values,k,this.nNeighbors),this.embedding),z=this.nEpochs?this.nEpochs/3:S.nRows<=1e4?100:30,_=S.getValues().reduce((function(t,e){return e>t?e:t}),0);S=S.map((function(t){return t<_/z?0:t})),S=c.eliminateZeros(S);var A=this.makeEpochsPerSample(S.getValues(),z),P=S.getRows(),j=S.getCols();return this.assignOptimizationStateParameters({headEmbedding:N,tailEmbedding:this.embedding,head:P,tail:j,currentEpoch:0,nEpochs:z,nVertices:S.getDims()[1],epochsPerSample:A}),this.prepareForOptimizationLoop(),this.optimizeLayout()},t.prototype.processGraphForSupervisedProjection=function(){var t=this.Y,e=this.X;if(t){if(t.length!==e.length)throw new Error("Length of X and y must be equal");if("categorical"===this.targetMetric){var r=this.targetWeight<1?1/(1-this.targetWeight)*2.5:1e12;this.graph=this.categoricalSimplicialSetIntersection(this.graph,t,r)}}},t.prototype.step=function(){var t=this.optimizationState.currentEpoch;return t0}));if(m.length>=r){var p=Math.floor(r),w=r-p;p>0?(s[h]=m[p-1],w>1e-5&&(s[h]+=w*(m[p]-m[p-1]))):s[h]=w*m[0]}else m.length>0&&(s[h]=g.max(m));for(var d=0;d0?Math.exp(-b/f):1}if(Math.abs(y-i)<1e-5)break;y>i?f=(u+(l=f))/2:(u=f,l===1/0?f*=2:f=(u+l)/2)}if(a[h]=f,s[h]>0){var M=g.mean(c);a[h]<.001*M&&(a[h]=.001*M)}else{var S=g.mean(t.map(g.mean));a[h]<.001*S&&(a[h]=.001*S)}}return{sigmas:a,rhos:s}},t.prototype.computeMembershipStrengths=function(t,e,r,n){for(var o=t.length,i=t[0].length,s=g.zeros(o*i),a=g.zeros(o*i),h=g.zeros(o*i),u=0;u0&&(r[n]=e/o[n])})),r},t.prototype.assignOptimizationStateParameters=function(t){Object.assign(this.optimizationState,t)},t.prototype.prepareForOptimizationLoop=function(){var t=this.repulsionStrength,e=this.learningRate,r=this.negativeSampleRate,n=this.optimizationState,o=n.epochsPerSample,i=n.headEmbedding,s=n.tailEmbedding,a=i[0].length,h=i.length===s.length,l=o.map((function(t){return t/r})),f=u(l),c=u(o);this.assignOptimizationStateParameters({epochOfNextSample:c,epochOfNextNegativeSample:f,epochsPerNegativeSample:l,moveOther:h,initialAlpha:e,alpha:e,gamma:t,dim:a})},t.prototype.initializeOptimization=function(){var t=this.embedding,e=this.embedding,r=this.optimizationState,n=r.head,o=r.tail,i=r.epochsPerSample,s=this.getNEpochs(),a=this.graph.nCols,h=S(this.spread,this.minDist),u=h.a,l=h.b;this.assignOptimizationStateParameters({headEmbedding:t,tailEmbedding:e,head:n,tail:o,epochsPerSample:i,a:u,b:l,nEpochs:s,nVertices:a})},t.prototype.optimizeLayoutStep=function(t){for(var e=this.optimizationState,r=e.head,n=e.tail,o=e.headEmbedding,i=e.tailEmbedding,s=e.epochsPerSample,a=e.epochOfNextSample,h=e.epochOfNextNegativeSample,u=e.epochsPerNegativeSample,l=e.moveOther,f=e.initialAlpha,c=e.alpha,m=e.gamma,p=e.a,w=e.b,d=e.dim,y=e.nEpochs,v=e.nVertices,S=0;St)){var x=r[S],E=n[S],R=o[x],k=i[E],N=M(R,k),z=0;N>0&&(z=-2*p*w*Math.pow(N,w-1),z/=p*Math.pow(N,w)+1);for(var _=0;_0)I=2*m*w,I/=(.001+T)*(p*Math.pow(T,w)+1);else if(x===O)continue;for(_=0;_0&&(A=b(I*(R[_]-C[_]),4)),R[_]+=A*c}}h[S]+=P*u[S]}return e.alpha=f*(1-t/y),e.currentEpoch+=1,o},t.prototype.optimizeLayoutAsync=function(t){var e=this;return void 0===t&&(t=function(){return!0}),new Promise((function(r,n){var o=function(){return s(e,void 0,void 0,(function(){var e,i,s,h,u,l;return a(this,(function(a){try{if(e=this.optimizationState,i=e.nEpochs,s=e.currentEpoch,this.embedding=this.optimizeLayoutStep(s),h=this.optimizationState.currentEpoch,u=!1===t(h),l=h===i,u||l)return[2,r(l)];setTimeout((function(){return o()}),0)}catch(t){n(t)}return[2]}))}))};setTimeout((function(){return o()}),0)}))},t.prototype.optimizeLayout=function(t){void 0===t&&(t=function(){return!0});for(var e=!1,r=[];!e;){var n=this.optimizationState,o=n.nEpochs,i=n.currentEpoch;r=this.optimizeLayoutStep(i);var s=this.optimizationState.currentEpoch,a=!1===t(s);e=s===o||a}return r},t.prototype.getNEpochs=function(){var t=this.graph;if(this.nEpochs>0)return this.nEpochs;var e=t.nRows;return e<=2500?500:e<=5e3?400:e<=7500?300:200},t}();function y(t,e){for(var r=0,n=0;ne?e:t<-e?-e:t}function M(t,e){for(var r=0,n=0;n=e?Math.exp(-(r[o]-e)/t):n})),o={x:r,y:n},i={damping:1.5,initialValues:[.5,.5],gradientDifference:.1,maxIterations:100,errorTolerance:.01},s=w.default(o,(function(t){var e=h(t,2),r=e[0],n=e[1];return function(t){return 1/(1+r*Math.pow(t,2*n))}}),i).parameterValues,a=h(s,2);return{a:a[0],b:a[1]}}function x(t,e,r,n){return void 0===r&&(r=1),void 0===n&&(n=5),t.map((function(t,o,i){return-1===e[o]||-1===e[i]?t*Math.exp(-r):e[o]!==e[i]?t*Math.exp(-n):t}))}function E(t){t=c.normalize(t,"max");var e=c.transpose(t),r=c.pairwiseMultiply(e,t);return t=c.add(t,c.subtract(e,r)),c.eliminateZeros(t)}function R(t,e,r){for(var n=g.zeros(t.length).map((function(t){return g.zeros(r[0].length)})),o=0;o=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(e,"__esModule",{value:!0}),e.initializeSearch=e.makeInitializedNNSearch=e.makeInitializations=e.makeNNDescent=void 0;var a=i(r(1)),h=i(r(2)),u=i(r(3)),l=i(r(0));e.makeNNDescent=function(t,e){return function(r,n,o,i,s,h,u,f){void 0===i&&(i=10),void 0===s&&(s=50),void 0===h&&(h=.001),void 0===u&&(u=.5),void 0===f&&(f=!0);for(var c=r.length,m=a.makeHeap(r.length,o),p=0;p1&&void 0!==arguments[1]?arguments[1]:{};if(!u(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");var r=e.fromIndex,n=void 0===r?0:r,o=e.toIndex,i=void 0===o?t.length:o;if(n<0||n>=t.length||!Number.isInteger(n))throw new Error("fromIndex must be a positive integer smaller than length");if(i<=n||i>t.length||!Number.isInteger(i))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var s=t[n],a=n+1;as&&(s=t[a]);return s};const f=Object.prototype.toString;function c(t){return f.call(t).endsWith("Array]")}var m=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!c(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");var r=e.fromIndex,n=void 0===r?0:r,o=e.toIndex,i=void 0===o?t.length:o;if(n<0||n>=t.length||!Number.isInteger(n))throw new Error("fromIndex must be a positive integer smaller than length");if(i<=n||i>t.length||!Number.isInteger(i))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var s=t[n],a=n+1;a1&&void 0!==arguments[1]?arguments[1]:{};if(!a(t))throw new TypeError("input must be an array");if(0===t.length)throw new TypeError("input must not be empty");if(void 0!==r.output){if(!a(r.output))throw new TypeError("output option must be an array if specified");e=r.output}else e=new Array(t.length);var n=m(t),o=l(t);if(n===o)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var i=r.min,s=void 0===i?r.autoMinMax?n:0:i,h=r.max,u=void 0===h?r.autoMinMax?o:1:h;if(s>=u)throw new RangeError("min option must be smaller than max option");for(var f=(u-s)/(o-n),c=0;cn)throw new RangeError("Row index out of range")}function b(t,e,r){let n=r?t.columns:t.columns-1;if(e<0||e>n)throw new RangeError("Column index out of range")}function M(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.columns)throw new RangeError("vector size must be the same as the number of columns");return e}function S(t,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==t.rows)throw new RangeError("vector size must be the same as the number of rows");return e}function x(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for row indices");if(e.some(e=>e<0||e>=t.rows))throw new RangeError("row indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function E(t,e){if("object"!=typeof e)throw new TypeError("unexpected type for column indices");if(e.some(e=>e<0||e>=t.columns))throw new RangeError("column indices are out of range");return Array.isArray(e)||(e=Array.from(e)),e}function R(t,e,r,n,o){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(N("startRow",e),N("endRow",r),N("startColumn",n),N("endColumn",o),e>r||n>o||e<0||e>=t.rows||r<0||r>=t.rows||n<0||n>=t.columns||o<0||o>=t.columns)throw new RangeError("Submatrix indices are out of range")}function k(t,e=0){let r=[];for(let n=0;n=o)throw new RangeError("min must be smaller than max");let s=o-n,a=new P(t,e);for(let r=0;rr?(o=!0,r=e):(n=!1,o=!0);t++}return n}isReducedEchelonForm(){let t=0,e=0,r=-1,n=!0,o=!1;for(;tr?(o=!0,r=e):(n=!1,o=!0);for(let r=e+1;rt.get(n,r)&&(n=o);if(0===t.get(n,r))r++;else{t.swapRows(e,n);let o=t.get(e,r);for(let n=r;n=0;)if(0===t.maxRow(n))n--;else{let o=0,i=!1;for(;ot&&(t=this.get(e,r));return t}maxIndex(){z(this);let t=this.get(0,0),e=[0,0];for(let r=0;rt&&(t=this.get(r,n),e[0]=r,e[1]=n);return e}min(){if(this.isEmpty())return NaN;let t=this.get(0,0);for(let e=0;ee&&(e=this.get(t,r));return e}maxRowIndex(t){v(this,t),z(this);let e=this.get(t,0),r=[t,0];for(let n=1;ne&&(e=this.get(t,n),r[1]=n);return r}minRow(t){if(v(this,t),this.isEmpty())return NaN;let e=this.get(t,0);for(let r=1;re&&(e=this.get(r,t));return e}maxColumnIndex(t){b(this,t),z(this);let e=this.get(0,t),r=[0,t];for(let n=1;ne&&(e=this.get(n,t),r[0]=n);return r}minColumn(t){if(b(this,t),this.isEmpty())return NaN;let e=this.get(0,t);for(let r=1;r=r)throw new RangeError("min must be smaller than max");let n=new P(this.rows,this.columns);for(let t=0;t0&&p(o,{min:e,max:r,output:o}),n.setRow(t,o)}return n}scaleColumns(t={}){if("object"!=typeof t)throw new TypeError("options must be an object");const{min:e=0,max:r=1}=t;if(!Number.isFinite(e))throw new TypeError("min must be a number");if(!Number.isFinite(r))throw new TypeError("max must be a number");if(e>=r)throw new RangeError("min must be smaller than max");let n=new P(this.rows,this.columns);for(let t=0;tr||e<0||e>=this.columns||r<0||r>=this.columns)throw new RangeError("Argument out of range");let n=new P(t.length,r-e+1);for(let o=0;o=this.rows)throw new RangeError("Row index out of range: "+t[o]);n.set(o,i-e,this.get(t[o],i))}return n}subMatrixColumn(t,e,r){if(void 0===e&&(e=0),void 0===r&&(r=this.rows-1),e>r||e<0||e>=this.rows||r<0||r>=this.rows)throw new RangeError("Argument out of range");let n=new P(r-e+1,t.length);for(let o=0;o=this.columns)throw new RangeError("Column index out of range: "+t[o]);n.set(i-e,o,this.get(i,t[o]))}return n}setSubMatrix(t,e,r){if((t=P.checkMatrix(t)).isEmpty())return this;R(this,e,e+t.rows-1,r,r+t.columns-1);for(let n=0;n=0){if(this.data=[],!(Number.isInteger(e)&&e>=0))throw new TypeError("nColumns must be a positive integer");for(let r=0;r>t);return this},j.prototype.signPropagatingRightShiftM=function(t){if(t=O.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>t.get(e,r));return this},j.signPropagatingRightShift=function(t,e){return new O(t).signPropagatingRightShift(e)},j.prototype.rightShift=function(t){return"number"==typeof t?this.rightShiftS(t):this.rightShiftM(t)},j.prototype.rightShiftS=function(t){for(let e=0;e>>t);return this},j.prototype.rightShiftM=function(t){if(t=O.checkMatrix(t),this.rows!==t.rows||this.columns!==t.columns)throw new RangeError("Matrices dimensions must be equal");for(let e=0;e>>t.get(e,r));return this},j.rightShift=function(t,e){return new O(t).rightShift(e)},j.prototype.zeroFillRightShift=j.prototype.rightShift,j.prototype.zeroFillRightShiftS=j.prototype.rightShiftS,j.prototype.zeroFillRightShiftM=j.prototype.rightShiftM,j.zeroFillRightShift=j.rightShift,j.prototype.not=function(){for(let t=0;tMath.abs(h[o])&&(o=e);if(o!==r){for(n=0;n=0;o--){for(n=0;ne?n.set(o,e,t.get(o,e)):o===e?n.set(o,e,1):n.set(o,e,0);return n}get upperTriangularMatrix(){let t=this.LU,e=t.rows,r=t.columns,n=new P(e,r);for(let o=0;oMath.abs(e)?(r=e/t,Math.abs(t)*Math.sqrt(1+r*r)):0!==e?(r=t/e,Math.abs(e)*Math.sqrt(1+r*r)):0}class F{constructor(t){let e,r,n,o,i=(t=C.checkMatrix(t)).clone(),s=t.rows,a=t.columns,h=new Float64Array(a);for(n=0;n=0;i--){for(o=0;o=0;r--){for(t=0;t=0;t--)if(0!==m[t]){for(let e=t+1;e=0;t--){if(t0;){let t,e;for(t=S-2;t>=-1&&-1!==t;t--){const e=Number.MIN_VALUE+R*Math.abs(m[t]+Math.abs(m[t+1]));if(Math.abs(w[t])<=e||Number.isNaN(w[t])){w[t]=0;break}}if(t===S-2)e=4;else{let r;for(r=S-1;r>=t&&r!==t;r--){let e=(r!==S?Math.abs(w[r]):0)+(r!==t+1?Math.abs(w[r-1]):0);if(Math.abs(m[r])<=R*e){m[r]=0;break}}r===t?e=3:r===S-1?e=1:(e=2,t=r)}switch(t++,e){case 1:{let e=w[S-2];w[S-2]=0;for(let r=S-2;r>=t;r--){let o=I(m[r],e),i=m[r]/o,s=e/o;if(m[r]=o,r!==t&&(e=-s*w[r-1],w[r-1]=i*w[r-1]),u)for(let t=0;t=m[t+1]);){let e=m[t];if(m[t]=m[t+1],m[t+1]=e,u&&te&&o.set(i,r,t.get(i,r)/this.s[r]);let i=this.U,s=i.rows,a=i.columns,h=new P(r,s);for(let t=0;tt&&e++;return e}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return P.diag(this.s)}}function D(t,e=!1){return t=C.checkMatrix(t),e?new V(t).inverse():function(t,e,r=!1){return t=C.checkMatrix(t),e=C.checkMatrix(e),r?new V(t).solve(e):t.isSquare()?new T(t).solve(e):new F(t).solve(e)}(t,P.eye(t.rows))}function q(t,e,r,n,o){let i=r*n*n,s=P.eye(e.length,e.length,i);const a=o(e);let h=new Float64Array(t.x.length);for(let e=0;e