feat:node-modules

This commit is contained in:
houjunxiang
2025-11-24 10:26:18 +08:00
parent 753766893b
commit 8a3e48d856
8825 changed files with 567399 additions and 1 deletions

117
node_modules/mathjs/lib/cjs/function/matrix/apply.js generated vendored Normal file
View File

@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createApply = void 0;
var _factory = require("../../utils/factory.js");
var _array = require("../../utils/array.js");
var _is = require("../../utils/is.js");
var _IndexError = require("../../error/IndexError.js");
const name = 'apply';
const dependencies = ['typed', 'isInteger'];
const createApply = exports.createApply = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
isInteger
} = _ref;
/**
* Apply a function that maps an array to a scalar
* along a given axis of a matrix or array.
* Returns a new matrix or array with one less dimension than the input.
*
* Syntax:
*
* math.apply(A, dim, callback)
*
* Where:
*
* - `dim: number` is a zero-based dimension over which to concatenate the matrices.
*
* Examples:
*
* const A = [[1, 2], [3, 4]]
* const sum = math.sum
*
* math.apply(A, 0, sum) // returns [4, 6]
* math.apply(A, 1, sum) // returns [3, 7]
*
* See also:
*
* map, filter, forEach
*
* @param {Array | Matrix} array The input Matrix
* @param {number} dim The dimension along which the callback is applied
* @param {Function} callback The callback function that is applied. This Function
* should take an array or 1-d matrix as an input and
* return a number.
* @return {Array | Matrix} res The residual matrix with the function applied over some dimension.
*/
return typed(name, {
'Array | Matrix, number | BigNumber, function': function (mat, dim, callback) {
if (!isInteger(dim)) {
throw new TypeError('Integer number expected for dimension');
}
const size = Array.isArray(mat) ? (0, _array.arraySize)(mat) : mat.size();
if (dim < 0 || dim >= size.length) {
throw new _IndexError.IndexError(dim, size.length);
}
if ((0, _is.isMatrix)(mat)) {
return mat.create(_apply(mat.valueOf(), dim, callback), mat.datatype());
} else {
return _apply(mat, dim, callback);
}
}
});
});
/**
* Recursively reduce a matrix
* @param {Array} mat
* @param {number} dim
* @param {Function} callback
* @returns {Array} ret
* @private
*/
function _apply(mat, dim, callback) {
let i, ret, tran;
if (dim <= 0) {
if (!Array.isArray(mat[0])) {
return callback(mat);
} else {
tran = _switch(mat);
ret = [];
for (i = 0; i < tran.length; i++) {
ret[i] = _apply(tran[i], dim - 1, callback);
}
return ret;
}
} else {
ret = [];
for (i = 0; i < mat.length; i++) {
ret[i] = _apply(mat[i], dim - 1, callback);
}
return ret;
}
}
/**
* Transpose a matrix
* @param {Array} mat
* @returns {Array} ret
* @private
*/
function _switch(mat) {
const I = mat.length;
const J = mat[0].length;
let i, j;
const ret = [];
for (j = 0; j < J; j++) {
const tmp = [];
for (i = 0; i < I; i++) {
tmp.push(mat[i][j]);
}
ret.push(tmp);
}
return ret;
}

65
node_modules/mathjs/lib/cjs/function/matrix/column.js generated vendored Normal file
View File

@@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createColumn = void 0;
var _factory = require("../../utils/factory.js");
var _is = require("../../utils/is.js");
var _object = require("../../utils/object.js");
var _array = require("../../utils/array.js");
const name = 'column';
const dependencies = ['typed', 'Index', 'matrix', 'range'];
const createColumn = exports.createColumn = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
Index,
matrix,
range
} = _ref;
/**
* Return a column from a Matrix.
*
* Syntax:
*
* math.column(value, index)
*
* Example:
*
* // get a column
* const d = [[1, 2], [3, 4]]
* math.column(d, 1) // returns [[2], [4]]
*
* See also:
*
* row
*
* @param {Array | Matrix } value An array or matrix
* @param {number} column The index of the column
* @return {Array | Matrix} The retrieved column
*/
return typed(name, {
'Matrix, number': _column,
'Array, number': function (value, column) {
return _column(matrix((0, _object.clone)(value)), column).valueOf();
}
});
/**
* Retrieve a column of a matrix
* @param {Matrix } value A matrix
* @param {number} column The index of the column
* @return {Matrix} The retrieved column
*/
function _column(value, column) {
// check dimensions
if (value.size().length !== 2) {
throw new Error('Only two dimensional matrix is supported');
}
(0, _array.validateIndex)(column, value.size()[1]);
const rowRange = range(0, value.size()[0]);
const index = new Index(rowRange, column);
const result = value.subset(index);
return (0, _is.isMatrix)(result) ? result : matrix([[result]]);
}
});

110
node_modules/mathjs/lib/cjs/function/matrix/concat.js generated vendored Normal file
View File

@@ -0,0 +1,110 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createConcat = void 0;
var _is = require("../../utils/is.js");
var _object = require("../../utils/object.js");
var _array = require("../../utils/array.js");
var _IndexError = require("../../error/IndexError.js");
var _DimensionError = require("../../error/DimensionError.js");
var _factory = require("../../utils/factory.js");
const name = 'concat';
const dependencies = ['typed', 'matrix', 'isInteger'];
const createConcat = exports.createConcat = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
isInteger
} = _ref;
/**
* Concatenate two or more matrices.
*
* Syntax:
*
* math.concat(A, B, C, ...)
* math.concat(A, B, C, ..., dim)
*
* Where:
*
* - `dim: number` is a zero-based dimension over which to concatenate the matrices.
* By default the last dimension of the matrices.
*
* Examples:
*
* const A = [[1, 2], [5, 6]]
* const B = [[3, 4], [7, 8]]
*
* math.concat(A, B) // returns [[1, 2, 3, 4], [5, 6, 7, 8]]
* math.concat(A, B, 0) // returns [[1, 2], [5, 6], [3, 4], [7, 8]]
* math.concat('hello', ' ', 'world') // returns 'hello world'
*
* See also:
*
* size, squeeze, subset, transpose
*
* @param {... Array | Matrix} args Two or more matrices
* @return {Array | Matrix} Concatenated matrix
*/
return typed(name, {
// TODO: change signature to '...Array | Matrix, dim?' when supported
'...Array | Matrix | number | BigNumber': function (args) {
let i;
const len = args.length;
let dim = -1; // zero-based dimension
let prevDim;
let asMatrix = false;
const matrices = []; // contains multi dimensional arrays
for (i = 0; i < len; i++) {
const arg = args[i];
// test whether we need to return a Matrix (if not we return an Array)
if ((0, _is.isMatrix)(arg)) {
asMatrix = true;
}
if ((0, _is.isNumber)(arg) || (0, _is.isBigNumber)(arg)) {
if (i !== len - 1) {
throw new Error('Dimension must be specified as last argument');
}
// last argument contains the dimension on which to concatenate
prevDim = dim;
dim = arg.valueOf(); // change BigNumber to number
if (!isInteger(dim)) {
throw new TypeError('Integer number expected for dimension');
}
if (dim < 0 || i > 0 && dim > prevDim) {
// TODO: would be more clear when throwing a DimensionError here
throw new _IndexError.IndexError(dim, prevDim + 1);
}
} else {
// this is a matrix or array
const m = (0, _object.clone)(arg).valueOf();
const size = (0, _array.arraySize)(m);
matrices[i] = m;
prevDim = dim;
dim = size.length - 1;
// verify whether each of the matrices has the same number of dimensions
if (i > 0 && dim !== prevDim) {
throw new _DimensionError.DimensionError(prevDim + 1, dim + 1);
}
}
}
if (matrices.length === 0) {
throw new SyntaxError('At least one matrix expected');
}
let res = matrices.shift();
while (matrices.length) {
res = (0, _array.concat)(res, matrices.shift(), dim);
}
return asMatrix ? matrix(res) : res;
},
'...string': function (args) {
return args.join('');
}
});
});

45
node_modules/mathjs/lib/cjs/function/matrix/count.js generated vendored Normal file
View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createCount = void 0;
var _factory = require("../../utils/factory.js");
const name = 'count';
const dependencies = ['typed', 'size', 'prod'];
const createCount = exports.createCount = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
size,
prod
} = _ref;
/**
* Count the number of elements of a matrix, array or string.
*
* Syntax:
*
* math.count(x)
*
* Examples:
*
* math.count('hello world') // returns 11
* const A = [[1, 2, 3], [4, 5, 6]]
* math.count(A) // returns 6
* math.count(math.range(1,6)) // returns 5
*
* See also:
*
* size
*
* @param {string | Array | Matrix} x A matrix or string
* @return {number} An integer with the elements in `x`.
*/
return typed(name, {
string: function (x) {
return x.length;
},
'Matrix | Array': function (x) {
return prod(size(x));
}
});
});

87
node_modules/mathjs/lib/cjs/function/matrix/cross.js generated vendored Normal file
View File

@@ -0,0 +1,87 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createCross = void 0;
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'cross';
const dependencies = ['typed', 'matrix', 'subtract', 'multiply'];
const createCross = exports.createCross = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
subtract,
multiply
} = _ref;
/**
* Calculate the cross product for two vectors in three dimensional space.
* The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined
* as:
*
* cross(A, B) = [
* a2 * b3 - a3 * b2,
* a3 * b1 - a1 * b3,
* a1 * b2 - a2 * b1
* ]
*
* If one of the input vectors has a dimension greater than 1, the output
* vector will be a 1x3 (2-dimensional) matrix.
*
* Syntax:
*
* math.cross(x, y)
*
* Examples:
*
* math.cross([1, 1, 0], [0, 1, 1]) // Returns [1, -1, 1]
* math.cross([3, -3, 1], [4, 9, 2]) // Returns [-15, -2, 39]
* math.cross([2, 3, 4], [5, 6, 7]) // Returns [-3, 6, -3]
* math.cross([[1, 2, 3]], [[4], [5], [6]]) // Returns [[-3, 6, -3]]
*
* See also:
*
* dot, multiply
*
* @param {Array | Matrix} x First vector
* @param {Array | Matrix} y Second vector
* @return {Array | Matrix} Returns the cross product of `x` and `y`
*/
return typed(name, {
'Matrix, Matrix': function (x, y) {
return matrix(_cross(x.toArray(), y.toArray()));
},
'Matrix, Array': function (x, y) {
return matrix(_cross(x.toArray(), y));
},
'Array, Matrix': function (x, y) {
return matrix(_cross(x, y.toArray()));
},
'Array, Array': _cross
});
/**
* Calculate the cross product for two arrays
* @param {Array} x First vector
* @param {Array} y Second vector
* @returns {Array} Returns the cross product of x and y
* @private
*/
function _cross(x, y) {
const highestDimension = Math.max((0, _array.arraySize)(x).length, (0, _array.arraySize)(y).length);
x = (0, _array.squeeze)(x);
y = (0, _array.squeeze)(y);
const xSize = (0, _array.arraySize)(x);
const ySize = (0, _array.arraySize)(y);
if (xSize.length !== 1 || ySize.length !== 1 || xSize[0] !== 3 || ySize[0] !== 3) {
throw new RangeError('Vectors with length 3 expected ' + '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])');
}
const product = [subtract(multiply(x[1], y[2]), multiply(x[2], y[1])), subtract(multiply(x[2], y[0]), multiply(x[0], y[2])), subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))];
if (highestDimension > 1) {
return [product];
} else {
return product;
}
}
});

View File

@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createCtranspose = void 0;
var _factory = require("../../utils/factory.js");
const name = 'ctranspose';
const dependencies = ['typed', 'transpose', 'conj'];
const createCtranspose = exports.createCtranspose = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
transpose,
conj
} = _ref;
/**
* Transpose and complex conjugate a matrix. All values of the matrix are
* reflected over its main diagonal and then the complex conjugate is
* taken. This is equivalent to complex conjugation for scalars and
* vectors.
*
* Syntax:
*
* math.ctranspose(x)
*
* Examples:
*
* const A = [[1, 2, 3], [4, 5, math.complex(6,7)]]
* math.ctranspose(A) // returns [[1, 4], [2, 5], [3, {re:6,im:7}]]
*
* See also:
*
* transpose, diag, inv, subset, squeeze
*
* @param {Array | Matrix} x Matrix to be ctransposed
* @return {Array | Matrix} The ctransposed matrix
*/
return typed(name, {
any: function (x) {
return conj(transpose(x));
}
});
});

148
node_modules/mathjs/lib/cjs/function/matrix/det.js generated vendored Normal file
View File

@@ -0,0 +1,148 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createDet = void 0;
var _is = require("../../utils/is.js");
var _object = require("../../utils/object.js");
var _string = require("../../utils/string.js");
var _factory = require("../../utils/factory.js");
const name = 'det';
const dependencies = ['typed', 'matrix', 'subtractScalar', 'multiply', 'divideScalar', 'isZero', 'unaryMinus'];
const createDet = exports.createDet = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
subtractScalar,
multiply,
divideScalar,
isZero,
unaryMinus
} = _ref;
/**
* Calculate the determinant of a matrix.
*
* Syntax:
*
* math.det(x)
*
* Examples:
*
* math.det([[1, 2], [3, 4]]) // returns -2
*
* const A = [
* [-2, 2, 3],
* [-1, 1, 3],
* [2, 0, -1]
* ]
* math.det(A) // returns 6
*
* See also:
*
* inv
*
* @param {Array | Matrix} x A matrix
* @return {number} The determinant of `x`
*/
return typed(name, {
any: function (x) {
return (0, _object.clone)(x);
},
'Array | Matrix': function det(x) {
let size;
if ((0, _is.isMatrix)(x)) {
size = x.size();
} else if (Array.isArray(x)) {
x = matrix(x);
size = x.size();
} else {
// a scalar
size = [];
}
switch (size.length) {
case 0:
// scalar
return (0, _object.clone)(x);
case 1:
// vector
if (size[0] === 1) {
return (0, _object.clone)(x.valueOf()[0]);
}
if (size[0] === 0) {
return 1; // det of an empty matrix is per definition 1
} else {
throw new RangeError('Matrix must be square ' + '(size: ' + (0, _string.format)(size) + ')');
}
case 2:
{
// two-dimensional array
const rows = size[0];
const cols = size[1];
if (rows === cols) {
return _det(x.clone().valueOf(), rows, cols);
}
if (cols === 0) {
return 1; // det of an empty matrix is per definition 1
} else {
throw new RangeError('Matrix must be square ' + '(size: ' + (0, _string.format)(size) + ')');
}
}
default:
// multi dimensional array
throw new RangeError('Matrix must be two dimensional ' + '(size: ' + (0, _string.format)(size) + ')');
}
}
});
/**
* Calculate the determinant of a matrix
* @param {Array[]} matrix A square, two dimensional matrix
* @param {number} rows Number of rows of the matrix (zero-based)
* @param {number} cols Number of columns of the matrix (zero-based)
* @returns {number} det
* @private
*/
function _det(matrix, rows, cols) {
if (rows === 1) {
// this is a 1 x 1 matrix
return (0, _object.clone)(matrix[0][0]);
} else if (rows === 2) {
// this is a 2 x 2 matrix
// the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12
return subtractScalar(multiply(matrix[0][0], matrix[1][1]), multiply(matrix[1][0], matrix[0][1]));
} else {
// Bareiss algorithm
// this algorithm have same complexity as LUP decomposition (O(n^3))
// but it preserve precision of floating point more relative to the LUP decomposition
let negated = false;
const rowIndices = new Array(rows).fill(0).map((_, i) => i); // matrix index of row i
for (let k = 0; k < rows; k++) {
let k_ = rowIndices[k];
if (isZero(matrix[k_][k])) {
let _k;
for (_k = k + 1; _k < rows; _k++) {
if (!isZero(matrix[rowIndices[_k]][k])) {
k_ = rowIndices[_k];
rowIndices[_k] = rowIndices[k];
rowIndices[k] = k_;
negated = !negated;
break;
}
}
if (_k === rows) return matrix[k_][k]; // some zero of the type
}
const piv = matrix[k_][k];
const piv_ = k === 0 ? 1 : matrix[rowIndices[k - 1]][k - 1];
for (let i = k + 1; i < rows; i++) {
const i_ = rowIndices[i];
for (let j = k + 1; j < rows; j++) {
matrix[i_][j] = divideScalar(subtractScalar(multiply(matrix[i_][j], piv), multiply(matrix[i_][k], matrix[k_][j])), piv_);
}
}
}
const det = matrix[rowIndices[rows - 1]][rows - 1];
return negated ? unaryMinus(det) : det;
}
}
});

161
node_modules/mathjs/lib/cjs/function/matrix/diag.js generated vendored Normal file
View File

@@ -0,0 +1,161 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createDiag = void 0;
var _is = require("../../utils/is.js");
var _array = require("../../utils/array.js");
var _number = require("../../utils/number.js");
var _factory = require("../../utils/factory.js");
const name = 'diag';
const dependencies = ['typed', 'matrix', 'DenseMatrix', 'SparseMatrix'];
const createDiag = exports.createDiag = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
DenseMatrix,
SparseMatrix
} = _ref;
/**
* Create a diagonal matrix or retrieve the diagonal of a matrix
*
* When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
* When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.
* When k is positive, the values are placed on the super diagonal.
* When k is negative, the values are placed on the sub diagonal.
*
* Syntax:
*
* math.diag(X)
* math.diag(X, format)
* math.diag(X, k)
* math.diag(X, k, format)
*
* Examples:
*
* // create a diagonal matrix
* math.diag([1, 2, 3]) // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
* math.diag([1, 2, 3], 1) // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
* math.diag([1, 2, 3], -1) // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]]
*
* // retrieve the diagonal from a matrix
* const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
* math.diag(a) // returns [1, 5, 9]
*
* See also:
*
* ones, zeros, identity
*
* @param {Matrix | Array} x A two dimensional matrix or a vector
* @param {number | BigNumber} [k=0] The diagonal where the vector will be filled
* in or retrieved.
* @param {string} [format='dense'] The matrix storage format.
*
* @returns {Matrix | Array} Diagonal matrix from input vector, or diagonal from input matrix.
*/
return typed(name, {
// FIXME: simplify this huge amount of signatures as soon as typed-function supports optional arguments
Array: function (x) {
return _diag(x, 0, (0, _array.arraySize)(x), null);
},
'Array, number': function (x, k) {
return _diag(x, k, (0, _array.arraySize)(x), null);
},
'Array, BigNumber': function (x, k) {
return _diag(x, k.toNumber(), (0, _array.arraySize)(x), null);
},
'Array, string': function (x, format) {
return _diag(x, 0, (0, _array.arraySize)(x), format);
},
'Array, number, string': function (x, k, format) {
return _diag(x, k, (0, _array.arraySize)(x), format);
},
'Array, BigNumber, string': function (x, k, format) {
return _diag(x, k.toNumber(), (0, _array.arraySize)(x), format);
},
Matrix: function (x) {
return _diag(x, 0, x.size(), x.storage());
},
'Matrix, number': function (x, k) {
return _diag(x, k, x.size(), x.storage());
},
'Matrix, BigNumber': function (x, k) {
return _diag(x, k.toNumber(), x.size(), x.storage());
},
'Matrix, string': function (x, format) {
return _diag(x, 0, x.size(), format);
},
'Matrix, number, string': function (x, k, format) {
return _diag(x, k, x.size(), format);
},
'Matrix, BigNumber, string': function (x, k, format) {
return _diag(x, k.toNumber(), x.size(), format);
}
});
/**
* Creeate diagonal matrix from a vector or vice versa
* @param {Array | Matrix} x
* @param {number} k
* @param {string} format Storage format for matrix. If null,
* an Array is returned
* @returns {Array | Matrix}
* @private
*/
function _diag(x, k, size, format) {
if (!(0, _number.isInteger)(k)) {
throw new TypeError('Second parameter in function diag must be an integer');
}
const kSuper = k > 0 ? k : 0;
const kSub = k < 0 ? -k : 0;
// check dimensions
switch (size.length) {
case 1:
return _createDiagonalMatrix(x, k, format, size[0], kSub, kSuper);
case 2:
return _getDiagonal(x, k, format, size, kSub, kSuper);
}
throw new RangeError('Matrix for function diag must be 2 dimensional');
}
function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {
// matrix size
const ms = [l + kSub, l + kSuper];
if (format && format !== 'sparse' && format !== 'dense') {
throw new TypeError(`Unknown matrix type ${format}"`);
}
// create diagonal matrix
const m = format === 'sparse' ? SparseMatrix.diagonal(ms, x, k) : DenseMatrix.diagonal(ms, x, k);
// check we need to return a matrix
return format !== null ? m : m.valueOf();
}
function _getDiagonal(x, k, format, s, kSub, kSuper) {
// check x is a Matrix
if ((0, _is.isMatrix)(x)) {
// get diagonal matrix
const dm = x.diagonal(k);
// check we need to return a matrix
if (format !== null) {
// check we need to change matrix format
if (format !== dm.storage()) {
return matrix(dm, format);
}
return dm;
}
return dm.valueOf();
}
// vector size
const n = Math.min(s[0] - kSub, s[1] - kSuper);
// diagonal values
const vector = [];
// loop diagonal
for (let i = 0; i < n; i++) {
vector[i] = x[i + kSub][i + kSuper];
}
// check we need to return a matrix
return format !== null ? matrix(vector) : vector;
}
});

169
node_modules/mathjs/lib/cjs/function/matrix/diff.js generated vendored Normal file
View File

@@ -0,0 +1,169 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createDiff = void 0;
var _factory = require("../../utils/factory.js");
var _number = require("../../utils/number.js");
var _is = require("../../utils/is.js");
const name = 'diff';
const dependencies = ['typed', 'matrix', 'subtract', 'number'];
const createDiff = exports.createDiff = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
subtract,
number
} = _ref;
/**
* Create a new matrix or array of the difference between elements of the given array
* The optional dim parameter lets you specify the dimension to evaluate the difference of
* If no dimension parameter is passed it is assumed as dimension 0
*
* Dimension is zero-based in javascript and one-based in the parser and can be a number or bignumber
* Arrays must be 'rectangular' meaning arrays like [1, 2]
* If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays
*
* Syntax:
*
* math.diff(arr)
* math.diff(arr, dim)
*
* Examples:
*
* const arr = [1, 2, 4, 7, 0]
* math.diff(arr) // returns [1, 2, 3, -7] (no dimension passed so 0 is assumed)
* math.diff(math.matrix(arr)) // returns Matrix [1, 2, 3, -7]
*
* const arr = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [9, 8, 7, 6, 4]]
* math.diff(arr) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
* math.diff(arr, 0) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
* math.diff(arr, 1) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]
* math.diff(arr, math.bignumber(1)) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]
*
* math.diff(arr, 2) // throws RangeError as arr is 2 dimensional not 3
* math.diff(arr, -1) // throws RangeError as negative dimensions are not allowed
*
* // These will all produce the same result
* math.diff([[1, 2], [3, 4]])
* math.diff([math.matrix([1, 2]), math.matrix([3, 4])])
* math.diff([[1, 2], math.matrix([3, 4])])
* math.diff([math.matrix([1, 2]), [3, 4]])
* // They do not produce the same result as math.diff(math.matrix([[1, 2], [3, 4]])) as this returns a matrix
*
* See Also:
*
* sum
* subtract
* partitionSelect
*
* @param {Array | Matrix} arr An array or matrix
* @param {number | BigNumber} dim Dimension
* @return {Array | Matrix} Difference between array elements in given dimension
*/
return typed(name, {
'Array | Matrix': function (arr) {
// No dimension specified => assume dimension 0
if ((0, _is.isMatrix)(arr)) {
return matrix(_diff(arr.toArray()));
} else {
return _diff(arr);
}
},
'Array | Matrix, number': function (arr, dim) {
if (!(0, _number.isInteger)(dim)) throw new RangeError('Dimension must be a whole number');
if ((0, _is.isMatrix)(arr)) {
return matrix(_recursive(arr.toArray(), dim));
} else {
return _recursive(arr, dim);
}
},
'Array, BigNumber': typed.referTo('Array,number', selfAn => (arr, dim) => selfAn(arr, number(dim))),
'Matrix, BigNumber': typed.referTo('Matrix,number', selfMn => (arr, dim) => selfMn(arr, number(dim)))
});
/**
* Recursively find the correct dimension in the array/matrix
* Then Apply _diff to that dimension
*
* @param {Array} arr The array
* @param {number} dim Dimension
* @return {Array} resulting array
*/
function _recursive(arr, dim) {
if ((0, _is.isMatrix)(arr)) {
arr = arr.toArray(); // Makes sure arrays like [ matrix([0, 1]), matrix([1, 0]) ] are processed properly
}
if (!Array.isArray(arr)) {
throw RangeError('Array/Matrix does not have that many dimensions');
}
if (dim > 0) {
const result = [];
arr.forEach(element => {
result.push(_recursive(element, dim - 1));
});
return result;
} else if (dim === 0) {
return _diff(arr);
} else {
throw RangeError('Cannot have negative dimension');
}
}
/**
* Difference between elements in the array
*
* @param {Array} arr An array
* @return {Array} resulting array
*/
function _diff(arr) {
const result = [];
const size = arr.length;
for (let i = 1; i < size; i++) {
result.push(_ElementDiff(arr[i - 1], arr[i]));
}
return result;
}
/**
* Difference between 2 objects
*
* @param {Object} obj1 First object
* @param {Object} obj2 Second object
* @return {Array} resulting array
*/
function _ElementDiff(obj1, obj2) {
// Convert matrices to arrays
if ((0, _is.isMatrix)(obj1)) obj1 = obj1.toArray();
if ((0, _is.isMatrix)(obj2)) obj2 = obj2.toArray();
const obj1IsArray = Array.isArray(obj1);
const obj2IsArray = Array.isArray(obj2);
if (obj1IsArray && obj2IsArray) {
return _ArrayDiff(obj1, obj2);
}
if (!obj1IsArray && !obj2IsArray) {
return subtract(obj2, obj1); // Difference is (second - first) NOT (first - second)
}
throw TypeError('Cannot calculate difference between 1 array and 1 non-array');
}
/**
* Difference of elements in 2 arrays
*
* @param {Array} arr1 Array 1
* @param {Array} arr2 Array 2
* @return {Array} resulting array
*/
function _ArrayDiff(arr1, arr2) {
if (arr1.length !== arr2.length) {
throw RangeError('Not all sub-arrays have the same length');
}
const result = [];
const size = arr1.length;
for (let i = 0; i < size; i++) {
result.push(_ElementDiff(arr1[i], arr2[i]));
}
return result;
}
});

162
node_modules/mathjs/lib/cjs/function/matrix/dot.js generated vendored Normal file
View File

@@ -0,0 +1,162 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createDot = void 0;
var _factory = require("../../utils/factory.js");
var _is = require("../../utils/is.js");
const name = 'dot';
const dependencies = ['typed', 'addScalar', 'multiplyScalar', 'conj', 'size'];
const createDot = exports.createDot = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
addScalar,
multiplyScalar,
conj,
size
} = _ref;
/**
* Calculate the dot product of two vectors. The dot product of
* `A = [a1, a2, ..., an]` and `B = [b1, b2, ..., bn]` is defined as:
*
* dot(A, B) = conj(a1) * b1 + conj(a2) * b2 + ... + conj(an) * bn
*
* Syntax:
*
* math.dot(x, y)
*
* Examples:
*
* math.dot([2, 4, 1], [2, 2, 3]) // returns number 15
* math.multiply([2, 4, 1], [2, 2, 3]) // returns number 15
*
* See also:
*
* multiply, cross
*
* @param {Array | Matrix} x First vector
* @param {Array | Matrix} y Second vector
* @return {number} Returns the dot product of `x` and `y`
*/
return typed(name, {
'Array | DenseMatrix, Array | DenseMatrix': _denseDot,
'SparseMatrix, SparseMatrix': _sparseDot
});
function _validateDim(x, y) {
const xSize = _size(x);
const ySize = _size(y);
let xLen, yLen;
if (xSize.length === 1) {
xLen = xSize[0];
} else if (xSize.length === 2 && xSize[1] === 1) {
xLen = xSize[0];
} else {
throw new RangeError('Expected a column vector, instead got a matrix of size (' + xSize.join(', ') + ')');
}
if (ySize.length === 1) {
yLen = ySize[0];
} else if (ySize.length === 2 && ySize[1] === 1) {
yLen = ySize[0];
} else {
throw new RangeError('Expected a column vector, instead got a matrix of size (' + ySize.join(', ') + ')');
}
if (xLen !== yLen) throw new RangeError('Vectors must have equal length (' + xLen + ' != ' + yLen + ')');
if (xLen === 0) throw new RangeError('Cannot calculate the dot product of empty vectors');
return xLen;
}
function _denseDot(a, b) {
const N = _validateDim(a, b);
const adata = (0, _is.isMatrix)(a) ? a._data : a;
const adt = (0, _is.isMatrix)(a) ? a._datatype || a.getDataType() : undefined;
const bdata = (0, _is.isMatrix)(b) ? b._data : b;
const bdt = (0, _is.isMatrix)(b) ? b._datatype || b.getDataType() : undefined;
// are these 2-dimensional column vectors? (as opposed to 1-dimensional vectors)
const aIsColumn = _size(a).length === 2;
const bIsColumn = _size(b).length === 2;
let add = addScalar;
let mul = multiplyScalar;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
const dt = adt;
// find signatures that matches (dt, dt)
add = typed.find(addScalar, [dt, dt]);
mul = typed.find(multiplyScalar, [dt, dt]);
}
// both vectors 1-dimensional
if (!aIsColumn && !bIsColumn) {
let c = mul(conj(adata[0]), bdata[0]);
for (let i = 1; i < N; i++) {
c = add(c, mul(conj(adata[i]), bdata[i]));
}
return c;
}
// a is 1-dim, b is column
if (!aIsColumn && bIsColumn) {
let c = mul(conj(adata[0]), bdata[0][0]);
for (let i = 1; i < N; i++) {
c = add(c, mul(conj(adata[i]), bdata[i][0]));
}
return c;
}
// a is column, b is 1-dim
if (aIsColumn && !bIsColumn) {
let c = mul(conj(adata[0][0]), bdata[0]);
for (let i = 1; i < N; i++) {
c = add(c, mul(conj(adata[i][0]), bdata[i]));
}
return c;
}
// both vectors are column
if (aIsColumn && bIsColumn) {
let c = mul(conj(adata[0][0]), bdata[0][0]);
for (let i = 1; i < N; i++) {
c = add(c, mul(conj(adata[i][0]), bdata[i][0]));
}
return c;
}
}
function _sparseDot(x, y) {
_validateDim(x, y);
const xindex = x._index;
const xvalues = x._values;
const yindex = y._index;
const yvalues = y._values;
// TODO optimize add & mul using datatype
let c = 0;
const add = addScalar;
const mul = multiplyScalar;
let i = 0;
let j = 0;
while (i < xindex.length && j < yindex.length) {
const I = xindex[i];
const J = yindex[j];
if (I < J) {
i++;
continue;
}
if (I > J) {
j++;
continue;
}
if (I === J) {
c = add(c, mul(xvalues[i], yvalues[j]));
i++;
j++;
}
}
return c;
}
// TODO remove this once #1771 is fixed
function _size(x) {
return (0, _is.isMatrix)(x) ? x.size() : size(x);
}
});

335
node_modules/mathjs/lib/cjs/function/matrix/eigs.js generated vendored Normal file
View File

@@ -0,0 +1,335 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createEigs = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _factory = require("../../utils/factory.js");
var _string = require("../../utils/string.js");
var _complexEigs = require("./eigs/complexEigs.js");
var _realSymmetric = require("./eigs/realSymmetric.js");
var _is = require("../../utils/is.js");
const name = 'eigs';
// The absolute state of math.js's dependency system:
const dependencies = ['config', 'typed', 'matrix', 'addScalar', 'equal', 'subtract', 'abs', 'atan', 'cos', 'sin', 'multiplyScalar', 'divideScalar', 'inv', 'bignumber', 'multiply', 'add', 'larger', 'column', 'flatten', 'number', 'complex', 'sqrt', 'diag', 'size', 'reshape', 'qr', 'usolve', 'usolveAll', 'im', 're', 'smaller', 'matrixFromColumns', 'dot'];
const createEigs = exports.createEigs = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
config,
typed,
matrix,
addScalar,
subtract,
equal,
abs,
atan,
cos,
sin,
multiplyScalar,
divideScalar,
inv,
bignumber,
multiply,
add,
larger,
column,
flatten,
number,
complex,
sqrt,
diag,
size,
reshape,
qr,
usolve,
usolveAll,
im,
re,
smaller,
matrixFromColumns,
dot
} = _ref;
const doRealSymmetric = (0, _realSymmetric.createRealSymmetric)({
config,
addScalar,
subtract,
column,
flatten,
equal,
abs,
atan,
cos,
sin,
multiplyScalar,
inv,
bignumber,
complex,
multiply,
add
});
const doComplexEigs = (0, _complexEigs.createComplexEigs)({
config,
addScalar,
subtract,
multiply,
multiplyScalar,
flatten,
divideScalar,
sqrt,
abs,
bignumber,
diag,
size,
reshape,
qr,
inv,
usolve,
usolveAll,
equal,
complex,
larger,
smaller,
matrixFromColumns,
dot
});
/**
* Compute eigenvalues and optionally eigenvectors of a square matrix.
* The eigenvalues are sorted by their absolute value, ascending, and
* returned as a vector in the `values` property of the returned project.
* An eigenvalue with algebraic multiplicity k will be listed k times, so
* that the returned `values` vector always has length equal to the size
* of the input matrix.
*
* The `eigenvectors` property of the return value provides the eigenvectors.
* It is an array of plain objects: the `value` property of each gives the
* associated eigenvalue, and the `vector` property gives the eigenvector
* itself. Note that the same `value` property will occur as many times in
* the list provided by `eigenvectors` as the geometric multiplicity of
* that value.
*
* If the algorithm fails to converge, it will throw an error
* in that case, however, you may still find useful information
* in `err.values` and `err.vectors`.
*
* Note that the 'precision' option does not directly specify the _accuracy_
* of the returned eigenvalues. Rather, it determines how small an entry
* of the iterative approximations to an upper triangular matrix must be
* in order to be considered zero. The actual accuracy of the returned
* eigenvalues may be greater or less than the precision, depending on the
* conditioning of the matrix and how far apart or close the actual
* eigenvalues are. Note that currently, relatively simple, "traditional"
* methods of eigenvalue computation are being used; this is not a modern,
* high-precision eigenvalue computation. That said, it should typically
* produce fairly reasonable results.
*
* Syntax:
*
* math.eigs(x, [prec])
* math.eigs(x, {options})
*
* Examples:
*
* const { eigs, multiply, column, transpose, matrixFromColumns } = math
* const H = [[5, 2.3], [2.3, 1]]
* const ans = eigs(H) // returns {values: [E1,E2...sorted], eigenvectors: [{value: E1, vector: v2}, {value: e, vector: v2}, ...]
* const E = ans.values
* const V = ans.eigenvectors
* multiply(H, V[0].vector)) // returns multiply(E[0], V[0].vector))
* const U = matrixFromColumns(...V.map(obj => obj.vector))
* const UTxHxU = multiply(transpose(U), H, U) // diagonalizes H if possible
* E[0] == UTxHxU[0][0] // returns true always
*
* // Compute only approximate eigenvalues:
* const {values} = eigs(H, {eigenvectors: false, precision: 1e-6})
*
* See also:
*
* inv
*
* @param {Array | Matrix} x Matrix to be diagonalized
*
* @param {number | BigNumber | OptsObject} [opts] Object with keys `precision`, defaulting to config.relTol, and `eigenvectors`, defaulting to true and specifying whether to compute eigenvectors. If just a number, specifies precision.
* @return {{values: Array|Matrix, eigenvectors?: Array<EVobj>}} Object containing an array of eigenvalues and an array of {value: number|BigNumber, vector: Array|Matrix} objects. The eigenvectors property is undefined if eigenvectors were not requested.
*
*/
return typed('eigs', {
// The conversion to matrix in the first two implementations,
// just to convert back to an array right away in
// computeValuesAndVectors, is unfortunate, and should perhaps be
// streamlined. It is done because the Matrix object carries some
// type information about its entries, and so constructing the matrix
// is a roundabout way of doing type detection.
Array: function (x) {
return doEigs(matrix(x));
},
'Array, number|BigNumber': function (x, prec) {
return doEigs(matrix(x), {
precision: prec
});
},
'Array, Object'(x, opts) {
return doEigs(matrix(x), opts);
},
Matrix: function (mat) {
return doEigs(mat, {
matricize: true
});
},
'Matrix, number|BigNumber': function (mat, prec) {
return doEigs(mat, {
precision: prec,
matricize: true
});
},
'Matrix, Object': function (mat, opts) {
const useOpts = {
matricize: true
};
(0, _extends2.default)(useOpts, opts);
return doEigs(mat, useOpts);
}
});
function doEigs(mat) {
var _opts$precision;
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const computeVectors = 'eigenvectors' in opts ? opts.eigenvectors : true;
const prec = (_opts$precision = opts.precision) !== null && _opts$precision !== void 0 ? _opts$precision : config.relTol;
const result = computeValuesAndVectors(mat, prec, computeVectors);
if (opts.matricize) {
result.values = matrix(result.values);
if (computeVectors) {
result.eigenvectors = result.eigenvectors.map(_ref2 => {
let {
value,
vector
} = _ref2;
return {
value,
vector: matrix(vector)
};
});
}
}
if (computeVectors) {
Object.defineProperty(result, 'vectors', {
enumerable: false,
// to make sure that the eigenvectors can still be
// converted to string.
get: () => {
throw new Error('eigs(M).vectors replaced with eigs(M).eigenvectors');
}
});
}
return result;
}
function computeValuesAndVectors(mat, prec, computeVectors) {
const arr = mat.toArray(); // NOTE: arr is guaranteed to be unaliased
// and so safe to modify in place
const asize = mat.size();
if (asize.length !== 2 || asize[0] !== asize[1]) {
throw new RangeError(`Matrix must be square (size: ${(0, _string.format)(asize)})`);
}
const N = asize[0];
if (isReal(arr, N, prec)) {
coerceReal(arr, N); // modifies arr by side effect
if (isSymmetric(arr, N, prec)) {
const type = coerceTypes(mat, arr, N); // modifies arr by side effect
return doRealSymmetric(arr, N, prec, type, computeVectors);
}
}
const type = coerceTypes(mat, arr, N); // modifies arr by side effect
return doComplexEigs(arr, N, prec, type, computeVectors);
}
/** @return {boolean} */
function isSymmetric(arr, N, prec) {
for (let i = 0; i < N; i++) {
for (let j = i; j < N; j++) {
// TODO proper comparison of bignum and frac
if (larger(bignumber(abs(subtract(arr[i][j], arr[j][i]))), prec)) {
return false;
}
}
}
return true;
}
/** @return {boolean} */
function isReal(arr, N, prec) {
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
// TODO proper comparison of bignum and frac
if (larger(bignumber(abs(im(arr[i][j]))), prec)) {
return false;
}
}
}
return true;
}
function coerceReal(arr, N) {
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
arr[i][j] = re(arr[i][j]);
}
}
}
/** @return {'number' | 'BigNumber' | 'Complex'} */
function coerceTypes(mat, arr, N) {
/** @type {string} */
const type = mat.datatype();
if (type === 'number' || type === 'BigNumber' || type === 'Complex') {
return type;
}
let hasNumber = false;
let hasBig = false;
let hasComplex = false;
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
const el = arr[i][j];
if ((0, _is.isNumber)(el) || (0, _is.isFraction)(el)) {
hasNumber = true;
} else if ((0, _is.isBigNumber)(el)) {
hasBig = true;
} else if ((0, _is.isComplex)(el)) {
hasComplex = true;
} else {
throw TypeError('Unsupported type in Matrix: ' + (0, _is.typeOf)(el));
}
}
}
if (hasBig && hasComplex) {
console.warn('Complex BigNumbers not supported, this operation will lose precission.');
}
if (hasComplex) {
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
arr[i][j] = complex(arr[i][j]);
}
}
return 'Complex';
}
if (hasBig) {
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
arr[i][j] = bignumber(arr[i][j]);
}
}
return 'BigNumber';
}
if (hasNumber) {
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
arr[i][j] = number(arr[i][j]);
}
}
return 'number';
} else {
throw TypeError('Matrix contains unsupported types only.');
}
}
});

View File

@@ -0,0 +1,701 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createComplexEigs = createComplexEigs;
var _object = require("../../../utils/object.js");
function createComplexEigs(_ref) {
let {
addScalar,
subtract,
flatten,
multiply,
multiplyScalar,
divideScalar,
sqrt,
abs,
bignumber,
diag,
size,
reshape,
inv,
qr,
usolve,
usolveAll,
equal,
complex,
larger,
smaller,
matrixFromColumns,
dot
} = _ref;
/**
* @param {number[][]} arr the matrix to find eigenvalues of
* @param {number} N size of the matrix
* @param {number|BigNumber} prec precision, anything lower will be considered zero
* @param {'number'|'BigNumber'|'Complex'} type
* @param {boolean} findVectors should we find eigenvectors?
*
* @returns {{ values: number[], vectors: number[][] }}
*/
function complexEigs(arr, N, prec, type) {
let findVectors = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
// TODO check if any row/col are zero except the diagonal
// make sure corresponding rows and columns have similar magnitude
// important because of numerical stability
// MODIFIES arr by side effect!
const R = balance(arr, N, prec, type, findVectors);
// R is the row transformation matrix
// arr = A' = R A R^-1, A is the original matrix
// (if findVectors is false, R is undefined)
// (And so to return to original matrix: A = R^-1 arr R)
// TODO if magnitudes of elements vary over many orders,
// move greatest elements to the top left corner
// using similarity transformations, reduce the matrix
// to Hessenberg form (upper triangular plus one subdiagonal row)
// updates the transformation matrix R with new row operationsq
// MODIFIES arr by side effect!
reduceToHessenberg(arr, N, prec, type, findVectors, R);
// still true that original A = R^-1 arr R)
// find eigenvalues
const {
values,
C
} = iterateUntilTriangular(arr, N, prec, type, findVectors);
// values is the list of eigenvalues, C is the column
// transformation matrix that transforms arr, the hessenberg
// matrix, to upper triangular
// (So U = C^-1 arr C and the relationship between current arr
// and original A is unchanged.)
if (findVectors) {
const eigenvectors = findEigenvectors(arr, N, C, R, values, prec, type);
return {
values,
eigenvectors
};
}
return {
values
};
}
/**
* @param {number[][]} arr
* @param {number} N
* @param {number} prec
* @param {'number'|'BigNumber'|'Complex'} type
* @returns {number[][]}
*/
function balance(arr, N, prec, type, findVectors) {
const big = type === 'BigNumber';
const cplx = type === 'Complex';
const realzero = big ? bignumber(0) : 0;
const one = big ? bignumber(1) : cplx ? complex(1) : 1;
const realone = big ? bignumber(1) : 1;
// base of the floating-point arithmetic
const radix = big ? bignumber(10) : 2;
const radixSq = multiplyScalar(radix, radix);
// the diagonal transformation matrix R
let Rdiag;
if (findVectors) {
Rdiag = Array(N).fill(one);
}
// this isn't the only time we loop thru the matrix...
let last = false;
while (!last) {
// ...haha I'm joking! unless...
last = true;
for (let i = 0; i < N; i++) {
// compute the taxicab norm of i-th column and row
// TODO optimize for complex numbers
let colNorm = realzero;
let rowNorm = realzero;
for (let j = 0; j < N; j++) {
if (i === j) continue;
colNorm = addScalar(colNorm, abs(arr[j][i]));
rowNorm = addScalar(rowNorm, abs(arr[i][j]));
}
if (!equal(colNorm, 0) && !equal(rowNorm, 0)) {
// find integer power closest to balancing the matrix
// (we want to scale only by integer powers of radix,
// so that we don't lose any precision due to round-off)
let f = realone;
let c = colNorm;
const rowDivRadix = divideScalar(rowNorm, radix);
const rowMulRadix = multiplyScalar(rowNorm, radix);
while (smaller(c, rowDivRadix)) {
c = multiplyScalar(c, radixSq);
f = multiplyScalar(f, radix);
}
while (larger(c, rowMulRadix)) {
c = divideScalar(c, radixSq);
f = divideScalar(f, radix);
}
// check whether balancing is needed
// condition = (c + rowNorm) / f < 0.95 * (colNorm + rowNorm)
const condition = smaller(divideScalar(addScalar(c, rowNorm), f), multiplyScalar(addScalar(colNorm, rowNorm), 0.95));
// apply balancing similarity transformation
if (condition) {
// we should loop once again to check whether
// another rebalancing is needed
last = false;
const g = divideScalar(1, f);
for (let j = 0; j < N; j++) {
if (i === j) {
continue;
}
arr[i][j] = multiplyScalar(arr[i][j], g);
arr[j][i] = multiplyScalar(arr[j][i], f);
}
// keep track of transformations
if (findVectors) {
Rdiag[i] = multiplyScalar(Rdiag[i], g);
}
}
}
}
}
// return the diagonal row transformation matrix
return findVectors ? diag(Rdiag) : null;
}
/**
* @param {number[][]} arr
* @param {number} N
* @param {number} prec
* @param {'number'|'BigNumber'|'Complex'} type
* @param {boolean} findVectors
* @param {number[][]} R the row transformation matrix that will be modified
*/
function reduceToHessenberg(arr, N, prec, type, findVectors, R) {
const big = type === 'BigNumber';
const cplx = type === 'Complex';
const zero = big ? bignumber(0) : cplx ? complex(0) : 0;
if (big) {
prec = bignumber(prec);
}
for (let i = 0; i < N - 2; i++) {
// Find the largest subdiag element in the i-th col
let maxIndex = 0;
let max = zero;
for (let j = i + 1; j < N; j++) {
const el = arr[j][i];
if (smaller(abs(max), abs(el))) {
max = el;
maxIndex = j;
}
}
// This col is pivoted, no need to do anything
if (smaller(abs(max), prec)) {
continue;
}
if (maxIndex !== i + 1) {
// Interchange maxIndex-th and (i+1)-th row
const tmp1 = arr[maxIndex];
arr[maxIndex] = arr[i + 1];
arr[i + 1] = tmp1;
// Interchange maxIndex-th and (i+1)-th column
for (let j = 0; j < N; j++) {
const tmp2 = arr[j][maxIndex];
arr[j][maxIndex] = arr[j][i + 1];
arr[j][i + 1] = tmp2;
}
// keep track of transformations
if (findVectors) {
const tmp3 = R[maxIndex];
R[maxIndex] = R[i + 1];
R[i + 1] = tmp3;
}
}
// Reduce following rows and columns
for (let j = i + 2; j < N; j++) {
const n = divideScalar(arr[j][i], max);
if (n === 0) {
continue;
}
// from j-th row subtract n-times (i+1)th row
for (let k = 0; k < N; k++) {
arr[j][k] = subtract(arr[j][k], multiplyScalar(n, arr[i + 1][k]));
}
// to (i+1)th column add n-times j-th column
for (let k = 0; k < N; k++) {
arr[k][i + 1] = addScalar(arr[k][i + 1], multiplyScalar(n, arr[k][j]));
}
// keep track of transformations
if (findVectors) {
for (let k = 0; k < N; k++) {
R[j][k] = subtract(R[j][k], multiplyScalar(n, R[i + 1][k]));
}
}
}
}
return R;
}
/**
* @returns {{values: values, C: Matrix}}
* @see Press, Wiliams: Numerical recipes in Fortran 77
* @see https://en.wikipedia.org/wiki/QR_algorithm
*/
function iterateUntilTriangular(A, N, prec, type, findVectors) {
const big = type === 'BigNumber';
const cplx = type === 'Complex';
const one = big ? bignumber(1) : cplx ? complex(1) : 1;
if (big) {
prec = bignumber(prec);
}
// The Francis Algorithm
// The core idea of this algorithm is that doing successive
// A' = QtAQ transformations will eventually converge to block-
// upper-triangular with diagonal blocks either 1x1 or 2x2.
// The Q here is the one from the QR decomposition, A = QR.
// Since the eigenvalues of a block-upper-triangular matrix are
// the eigenvalues of its diagonal blocks and we know how to find
// eigenvalues of a 2x2 matrix, we know the eigenvalues of A.
let arr = (0, _object.clone)(A);
// the list of converged eigenvalues
const lambdas = [];
// size of arr, which will get smaller as eigenvalues converge
let n = N;
// the diagonal of the block-diagonal matrix that turns
// converged 2x2 matrices into upper triangular matrices
const Sdiag = [];
// N×N matrix describing the overall transformation done during the QR algorithm
let Qtotal = findVectors ? diag(Array(N).fill(one)) : undefined;
// nxn matrix describing the QR transformations done since last convergence
let Qpartial = findVectors ? diag(Array(n).fill(one)) : undefined;
// last eigenvalue converged before this many steps
let lastConvergenceBefore = 0;
while (lastConvergenceBefore <= 100) {
lastConvergenceBefore += 1;
// TODO if the convergence is slow, do something clever
// Perform the factorization
const k = arr[n - 1][n - 1]; // TODO this is apparently a somewhat
// old-fashioned choice; ideally set close to an eigenvalue, or
// perhaps better yet switch to the implicit QR version that is sometimes
// specifically called the "Francis algorithm" that is alluded to
// in the following TODO. (Or perhaps we switch to an independently
// optimized third-party package for the linear algebra operations...)
for (let i = 0; i < n; i++) {
arr[i][i] = subtract(arr[i][i], k);
}
// TODO do an implicit QR transformation
const {
Q,
R
} = qr(arr);
arr = multiply(R, Q);
for (let i = 0; i < n; i++) {
arr[i][i] = addScalar(arr[i][i], k);
}
// keep track of transformations
if (findVectors) {
Qpartial = multiply(Qpartial, Q);
}
// The rightmost diagonal element converged to an eigenvalue
if (n === 1 || smaller(abs(arr[n - 1][n - 2]), prec)) {
lastConvergenceBefore = 0;
lambdas.push(arr[n - 1][n - 1]);
// keep track of transformations
if (findVectors) {
Sdiag.unshift([[1]]);
inflateMatrix(Qpartial, N);
Qtotal = multiply(Qtotal, Qpartial);
if (n > 1) {
Qpartial = diag(Array(n - 1).fill(one));
}
}
// reduce the matrix size
n -= 1;
arr.pop();
for (let i = 0; i < n; i++) {
arr[i].pop();
}
// The rightmost diagonal 2x2 block converged
} else if (n === 2 || smaller(abs(arr[n - 2][n - 3]), prec)) {
lastConvergenceBefore = 0;
const ll = eigenvalues2x2(arr[n - 2][n - 2], arr[n - 2][n - 1], arr[n - 1][n - 2], arr[n - 1][n - 1]);
lambdas.push(...ll);
// keep track of transformations
if (findVectors) {
Sdiag.unshift(jordanBase2x2(arr[n - 2][n - 2], arr[n - 2][n - 1], arr[n - 1][n - 2], arr[n - 1][n - 1], ll[0], ll[1], prec, type));
inflateMatrix(Qpartial, N);
Qtotal = multiply(Qtotal, Qpartial);
if (n > 2) {
Qpartial = diag(Array(n - 2).fill(one));
}
}
// reduce the matrix size
n -= 2;
arr.pop();
arr.pop();
for (let i = 0; i < n; i++) {
arr[i].pop();
arr[i].pop();
}
}
if (n === 0) {
break;
}
}
// standard sorting
lambdas.sort((a, b) => +subtract(abs(a), abs(b)));
// the algorithm didn't converge
if (lastConvergenceBefore > 100) {
const err = Error('The eigenvalues failed to converge. Only found these eigenvalues: ' + lambdas.join(', '));
err.values = lambdas;
err.vectors = [];
throw err;
}
// combine the overall QR transformation Qtotal with the subsequent
// transformation S that turns the diagonal 2x2 blocks to upper triangular
const C = findVectors ? multiply(Qtotal, blockDiag(Sdiag, N)) : undefined;
return {
values: lambdas,
C
};
}
/**
* @param {Matrix} A hessenberg-form matrix
* @param {number} N size of A
* @param {Matrix} C column transformation matrix that turns A into upper triangular
* @param {Matrix} R similarity that turns original matrix into A
* @param {number[]} values array of eigenvalues of A
* @param {'number'|'BigNumber'|'Complex'} type
* @returns {number[][]} eigenvalues
*/
function findEigenvectors(A, N, C, R, values, prec, type) {
const Cinv = inv(C);
const U = multiply(Cinv, A, C);
const big = type === 'BigNumber';
const cplx = type === 'Complex';
const zero = big ? bignumber(0) : cplx ? complex(0) : 0;
const one = big ? bignumber(1) : cplx ? complex(1) : 1;
// turn values into a kind of "multiset"
// this way it is easier to find eigenvectors
const uniqueValues = [];
const multiplicities = [];
for (const lambda of values) {
const i = indexOf(uniqueValues, lambda, equal);
if (i === -1) {
uniqueValues.push(lambda);
multiplicities.push(1);
} else {
multiplicities[i] += 1;
}
}
// find eigenvectors by solving U lambdaE = 0
// TODO replace with an iterative eigenvector algorithm
// (this one might fail for imprecise eigenvalues)
const vectors = [];
const len = uniqueValues.length;
const b = Array(N).fill(zero);
const E = diag(Array(N).fill(one));
for (let i = 0; i < len; i++) {
const lambda = uniqueValues[i];
const S = subtract(U, multiply(lambda, E)); // the characteristic matrix
let solutions = usolveAll(S, b);
solutions.shift(); // ignore the null vector
// looks like we missed something, try inverse iteration
// But if that fails, just presume that the original matrix truly
// was defective.
while (solutions.length < multiplicities[i]) {
const approxVec = inverseIterate(S, N, solutions, prec, type);
if (approxVec === null) {
break;
} // no more vectors were found
solutions.push(approxVec);
}
// Transform back into original array coordinates
const correction = multiply(inv(R), C);
solutions = solutions.map(v => multiply(correction, v));
vectors.push(...solutions.map(v => ({
value: lambda,
vector: flatten(v)
})));
}
return vectors;
}
/**
* Compute the eigenvalues of an 2x2 matrix
* @return {[number,number]}
*/
function eigenvalues2x2(a, b, c, d) {
// lambda_+- = 1/2 trA +- 1/2 sqrt( tr^2 A - 4 detA )
const trA = addScalar(a, d);
const detA = subtract(multiplyScalar(a, d), multiplyScalar(b, c));
const x = multiplyScalar(trA, 0.5);
const y = multiplyScalar(sqrt(subtract(multiplyScalar(trA, trA), multiplyScalar(4, detA))), 0.5);
return [addScalar(x, y), subtract(x, y)];
}
/**
* For an 2x2 matrix compute the transformation matrix S,
* so that SAS^-1 is an upper triangular matrix
* @return {[[number,number],[number,number]]}
* @see https://math.berkeley.edu/~ogus/old/Math_54-05/webfoils/jordan.pdf
* @see http://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html
*/
function jordanBase2x2(a, b, c, d, l1, l2, prec, type) {
const big = type === 'BigNumber';
const cplx = type === 'Complex';
const zero = big ? bignumber(0) : cplx ? complex(0) : 0;
const one = big ? bignumber(1) : cplx ? complex(1) : 1;
// matrix is already upper triangular
// return an identity matrix
if (smaller(abs(c), prec)) {
return [[one, zero], [zero, one]];
}
// matrix is diagonalizable
// return its eigenvectors as columns
if (larger(abs(subtract(l1, l2)), prec)) {
return [[subtract(l1, d), subtract(l2, d)], [c, c]];
}
// matrix is not diagonalizable
// compute diagonal elements of N = A - lambdaI
const na = subtract(a, l1);
const nd = subtract(d, l1);
// col(N,2) = 0 implies S = ( col(N,1), e_1 )
// col(N,2) != 0 implies S = ( col(N,2), e_2 )
if (smaller(abs(b), prec) && smaller(abs(nd), prec)) {
return [[na, one], [c, zero]];
} else {
return [[b, zero], [nd, one]];
}
}
/**
* Enlarge the matrix from nxn to NxN, setting the new
* elements to 1 on diagonal and 0 elsewhere
*/
function inflateMatrix(arr, N) {
// add columns
for (let i = 0; i < arr.length; i++) {
arr[i].push(...Array(N - arr[i].length).fill(0));
}
// add rows
for (let i = arr.length; i < N; i++) {
arr.push(Array(N).fill(0));
arr[i][i] = 1;
}
return arr;
}
/**
* Create a block-diagonal matrix with the given square matrices on the diagonal
* @param {Matrix[] | number[][][]} arr array of matrices to be placed on the diagonal
* @param {number} N the size of the resulting matrix
*/
function blockDiag(arr, N) {
const M = [];
for (let i = 0; i < N; i++) {
M[i] = Array(N).fill(0);
}
let I = 0;
for (const sub of arr) {
const n = sub.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
M[I + i][I + j] = sub[i][j];
}
}
I += n;
}
return M;
}
/**
* Finds the index of an element in an array using a custom equality function
* @template T
* @param {Array<T>} arr array in which to search
* @param {T} el the element to find
* @param {function(T, T): boolean} fn the equality function, first argument is an element of `arr`, the second is always `el`
* @returns {number} the index of `el`, or -1 when it's not in `arr`
*/
function indexOf(arr, el, fn) {
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i], el)) {
return i;
}
}
return -1;
}
/**
* Provided a near-singular upper-triangular matrix A and a list of vectors,
* finds an eigenvector of A with the smallest eigenvalue, which is orthogonal
* to each vector in the list
* @template T
* @param {T[][]} A near-singular square matrix
* @param {number} N dimension
* @param {T[][]} orthog list of vectors
* @param {number} prec epsilon
* @param {'number'|'BigNumber'|'Complex'} type
* @return {T[] | null} eigenvector
*
* @see Numerical Recipes for Fortran 77 11.7 Eigenvalues or Eigenvectors by Inverse Iteration
*/
function inverseIterate(A, N, orthog, prec, type) {
const largeNum = type === 'BigNumber' ? bignumber(1000) : 1000;
let b; // the vector
// you better choose a random vector before I count to five
let i = 0;
for (; i < 5; ++i) {
b = randomOrthogonalVector(N, orthog, type);
try {
b = usolve(A, b);
} catch (_unused) {
// That direction didn't work, likely because the original matrix
// was defective. But still make the full number of tries...
continue;
}
if (larger(norm(b), largeNum)) {
break;
}
}
if (i >= 5) {
return null; // couldn't find any orthogonal vector in the image
}
// you better converge before I count to ten
i = 0;
while (true) {
const c = usolve(A, b);
if (smaller(norm(orthogonalComplement(b, [c])), prec)) {
break;
}
if (++i >= 10) {
return null;
}
b = normalize(c);
}
return b;
}
/**
* Generates a random unit vector of dimension N, orthogonal to each vector in the list
* @template T
* @param {number} N dimension
* @param {T[][]} orthog list of vectors
* @param {'number'|'BigNumber'|'Complex'} type
* @returns {T[]} random vector
*/
function randomOrthogonalVector(N, orthog, type) {
const big = type === 'BigNumber';
const cplx = type === 'Complex';
// generate random vector with the correct type
let v = Array(N).fill(0).map(_ => 2 * Math.random() - 1);
if (big) {
v = v.map(n => bignumber(n));
}
if (cplx) {
v = v.map(n => complex(n));
}
// project to orthogonal complement
v = orthogonalComplement(v, orthog);
// normalize
return normalize(v, type);
}
/**
* Project vector v to the orthogonal complement of an array of vectors
*/
function orthogonalComplement(v, orthog) {
const vectorShape = size(v);
for (let w of orthog) {
w = reshape(w, vectorShape); // make sure this is just a vector computation
// v := v (w, v)/|w|^2 w
v = subtract(v, multiply(divideScalar(dot(w, v), dot(w, w)), w));
}
return v;
}
/**
* Calculate the norm of a vector.
* We can't use math.norm because factory can't handle circular dependency.
* Seriously, I'm really fed up with factory.
*/
function norm(v) {
return abs(sqrt(dot(v, v)));
}
/**
* Normalize a vector
* @template T
* @param {T[]} v
* @param {'number'|'BigNumber'|'Complex'} type
* @returns {T[]} normalized vec
*/
function normalize(v, type) {
const big = type === 'BigNumber';
const cplx = type === 'Complex';
const one = big ? bignumber(1) : cplx ? complex(1) : 1;
return multiply(divideScalar(one, norm(v)), v);
}
return complexEigs;
}

View File

@@ -0,0 +1,303 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createRealSymmetric = createRealSymmetric;
var _object = require("../../../utils/object.js");
function createRealSymmetric(_ref) {
let {
config,
addScalar,
subtract,
abs,
atan,
cos,
sin,
multiplyScalar,
inv,
bignumber,
multiply,
add
} = _ref;
/**
* @param {number[] | BigNumber[]} arr
* @param {number} N
* @param {number} prec
* @param {'number' | 'BigNumber'} type
*/
function main(arr, N) {
let prec = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : config.relTol;
let type = arguments.length > 3 ? arguments[3] : undefined;
let computeVectors = arguments.length > 4 ? arguments[4] : undefined;
if (type === 'number') {
return diag(arr, prec, computeVectors);
}
if (type === 'BigNumber') {
return diagBig(arr, prec, computeVectors);
}
throw TypeError('Unsupported data type: ' + type);
}
// diagonalization implementation for number (efficient)
function diag(x, precision, computeVectors) {
const N = x.length;
const e0 = Math.abs(precision / N);
let psi;
let Sij;
if (computeVectors) {
Sij = new Array(N);
// Sij is Identity Matrix
for (let i = 0; i < N; i++) {
Sij[i] = Array(N).fill(0);
Sij[i][i] = 1.0;
}
}
// initial error
let Vab = getAij(x);
while (Math.abs(Vab[1]) >= Math.abs(e0)) {
const i = Vab[0][0];
const j = Vab[0][1];
psi = getTheta(x[i][i], x[j][j], x[i][j]);
x = x1(x, psi, i, j);
if (computeVectors) Sij = Sij1(Sij, psi, i, j);
Vab = getAij(x);
}
const Ei = Array(N).fill(0); // eigenvalues
for (let i = 0; i < N; i++) {
Ei[i] = x[i][i];
}
return sorting((0, _object.clone)(Ei), Sij, computeVectors);
}
// diagonalization implementation for bigNumber
function diagBig(x, precision, computeVectors) {
const N = x.length;
const e0 = abs(precision / N);
let psi;
let Sij;
if (computeVectors) {
Sij = new Array(N);
// Sij is Identity Matrix
for (let i = 0; i < N; i++) {
Sij[i] = Array(N).fill(0);
Sij[i][i] = 1.0;
}
}
// initial error
let Vab = getAijBig(x);
while (abs(Vab[1]) >= abs(e0)) {
const i = Vab[0][0];
const j = Vab[0][1];
psi = getThetaBig(x[i][i], x[j][j], x[i][j]);
x = x1Big(x, psi, i, j);
if (computeVectors) Sij = Sij1Big(Sij, psi, i, j);
Vab = getAijBig(x);
}
const Ei = Array(N).fill(0); // eigenvalues
for (let i = 0; i < N; i++) {
Ei[i] = x[i][i];
}
// return [clone(Ei), clone(Sij)]
return sorting((0, _object.clone)(Ei), Sij, computeVectors);
}
// get angle
function getTheta(aii, ajj, aij) {
const denom = ajj - aii;
if (Math.abs(denom) <= config.relTol) {
return Math.PI / 4.0;
} else {
return 0.5 * Math.atan(2.0 * aij / (ajj - aii));
}
}
// get angle
function getThetaBig(aii, ajj, aij) {
const denom = subtract(ajj, aii);
if (abs(denom) <= config.relTol) {
return bignumber(-1).acos().div(4);
} else {
return multiplyScalar(0.5, atan(multiply(2.0, aij, inv(denom))));
}
}
// update eigvec
function Sij1(Sij, theta, i, j) {
const N = Sij.length;
const c = Math.cos(theta);
const s = Math.sin(theta);
const Ski = Array(N).fill(0);
const Skj = Array(N).fill(0);
for (let k = 0; k < N; k++) {
Ski[k] = c * Sij[k][i] - s * Sij[k][j];
Skj[k] = s * Sij[k][i] + c * Sij[k][j];
}
for (let k = 0; k < N; k++) {
Sij[k][i] = Ski[k];
Sij[k][j] = Skj[k];
}
return Sij;
}
// update eigvec for overlap
function Sij1Big(Sij, theta, i, j) {
const N = Sij.length;
const c = cos(theta);
const s = sin(theta);
const Ski = Array(N).fill(bignumber(0));
const Skj = Array(N).fill(bignumber(0));
for (let k = 0; k < N; k++) {
Ski[k] = subtract(multiplyScalar(c, Sij[k][i]), multiplyScalar(s, Sij[k][j]));
Skj[k] = addScalar(multiplyScalar(s, Sij[k][i]), multiplyScalar(c, Sij[k][j]));
}
for (let k = 0; k < N; k++) {
Sij[k][i] = Ski[k];
Sij[k][j] = Skj[k];
}
return Sij;
}
// update matrix
function x1Big(Hij, theta, i, j) {
const N = Hij.length;
const c = bignumber(cos(theta));
const s = bignumber(sin(theta));
const c2 = multiplyScalar(c, c);
const s2 = multiplyScalar(s, s);
const Aki = Array(N).fill(bignumber(0));
const Akj = Array(N).fill(bignumber(0));
// 2cs Hij
const csHij = multiply(bignumber(2), c, s, Hij[i][j]);
// Aii
const Aii = addScalar(subtract(multiplyScalar(c2, Hij[i][i]), csHij), multiplyScalar(s2, Hij[j][j]));
const Ajj = add(multiplyScalar(s2, Hij[i][i]), csHij, multiplyScalar(c2, Hij[j][j]));
// 0 to i
for (let k = 0; k < N; k++) {
Aki[k] = subtract(multiplyScalar(c, Hij[i][k]), multiplyScalar(s, Hij[j][k]));
Akj[k] = addScalar(multiplyScalar(s, Hij[i][k]), multiplyScalar(c, Hij[j][k]));
}
// Modify Hij
Hij[i][i] = Aii;
Hij[j][j] = Ajj;
Hij[i][j] = bignumber(0);
Hij[j][i] = bignumber(0);
// 0 to i
for (let k = 0; k < N; k++) {
if (k !== i && k !== j) {
Hij[i][k] = Aki[k];
Hij[k][i] = Aki[k];
Hij[j][k] = Akj[k];
Hij[k][j] = Akj[k];
}
}
return Hij;
}
// update matrix
function x1(Hij, theta, i, j) {
const N = Hij.length;
const c = Math.cos(theta);
const s = Math.sin(theta);
const c2 = c * c;
const s2 = s * s;
const Aki = Array(N).fill(0);
const Akj = Array(N).fill(0);
// Aii
const Aii = c2 * Hij[i][i] - 2 * c * s * Hij[i][j] + s2 * Hij[j][j];
const Ajj = s2 * Hij[i][i] + 2 * c * s * Hij[i][j] + c2 * Hij[j][j];
// 0 to i
for (let k = 0; k < N; k++) {
Aki[k] = c * Hij[i][k] - s * Hij[j][k];
Akj[k] = s * Hij[i][k] + c * Hij[j][k];
}
// Modify Hij
Hij[i][i] = Aii;
Hij[j][j] = Ajj;
Hij[i][j] = 0;
Hij[j][i] = 0;
// 0 to i
for (let k = 0; k < N; k++) {
if (k !== i && k !== j) {
Hij[i][k] = Aki[k];
Hij[k][i] = Aki[k];
Hij[j][k] = Akj[k];
Hij[k][j] = Akj[k];
}
}
return Hij;
}
// get max off-diagonal value from Upper Diagonal
function getAij(Mij) {
const N = Mij.length;
let maxMij = 0;
let maxIJ = [0, 1];
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
if (Math.abs(maxMij) < Math.abs(Mij[i][j])) {
maxMij = Math.abs(Mij[i][j]);
maxIJ = [i, j];
}
}
}
return [maxIJ, maxMij];
}
// get max off-diagonal value from Upper Diagonal
function getAijBig(Mij) {
const N = Mij.length;
let maxMij = 0;
let maxIJ = [0, 1];
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
if (abs(maxMij) < abs(Mij[i][j])) {
maxMij = abs(Mij[i][j]);
maxIJ = [i, j];
}
}
}
return [maxIJ, maxMij];
}
// sort results
function sorting(E, S, computeVectors) {
const N = E.length;
const values = Array(N);
let vecs;
if (computeVectors) {
vecs = Array(N);
for (let k = 0; k < N; k++) {
vecs[k] = Array(N);
}
}
for (let i = 0; i < N; i++) {
let minID = 0;
let minE = E[0];
for (let j = 0; j < E.length; j++) {
if (abs(E[j]) < abs(minE)) {
minID = j;
minE = E[minID];
}
}
values[i] = E.splice(minID, 1)[0];
if (computeVectors) {
for (let k = 0; k < N; k++) {
vecs[i][k] = S[k][minID];
S[k].splice(minID, 1);
}
}
}
if (!computeVectors) return {
values
};
const eigenvectors = vecs.map((vector, i) => ({
value: values[i],
vector
}));
return {
values,
eigenvectors
};
}
return main;
}

160
node_modules/mathjs/lib/cjs/function/matrix/expm.js generated vendored Normal file
View File

@@ -0,0 +1,160 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createExpm = void 0;
var _is = require("../../utils/is.js");
var _string = require("../../utils/string.js");
var _factory = require("../../utils/factory.js");
const name = 'expm';
const dependencies = ['typed', 'abs', 'add', 'identity', 'inv', 'multiply'];
const createExpm = exports.createExpm = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
abs,
add,
identity,
inv,
multiply
} = _ref;
/**
* Compute the matrix exponential, expm(A) = e^A. The matrix must be square.
* Not to be confused with exp(a), which performs element-wise
* exponentiation.
*
* The exponential is calculated using the Padé approximant with scaling and
* squaring; see "Nineteen Dubious Ways to Compute the Exponential of a
* Matrix," by Moler and Van Loan.
*
* Syntax:
*
* math.expm(x)
*
* Examples:
*
* const A = [[0,2],[0,0]]
* math.expm(A) // returns [[1,2],[0,1]]
*
* See also:
*
* exp
*
* @param {Matrix} x A square Matrix
* @return {Matrix} The exponential of x
*/
return typed(name, {
Matrix: function (A) {
// Check matrix size
const size = A.size();
if (size.length !== 2 || size[0] !== size[1]) {
throw new RangeError('Matrix must be square ' + '(size: ' + (0, _string.format)(size) + ')');
}
const n = size[0];
// Desired accuracy of the approximant (The actual accuracy
// will be affected by round-off error)
const eps = 1e-15;
// The Padé approximant is not so accurate when the values of A
// are "large", so scale A by powers of two. Then compute the
// exponential, and square the result repeatedly according to
// the identity e^A = (e^(A/m))^m
// Compute infinity-norm of A, ||A||, to see how "big" it is
const infNorm = infinityNorm(A);
// Find the optimal scaling factor and number of terms in the
// Padé approximant to reach the desired accuracy
const params = findParams(infNorm, eps);
const q = params.q;
const j = params.j;
// The Pade approximation to e^A is:
// Rqq(A) = Dqq(A) ^ -1 * Nqq(A)
// where
// Nqq(A) = sum(i=0, q, (2q-i)!p! / [ (2q)!i!(q-i)! ] A^i
// Dqq(A) = sum(i=0, q, (2q-i)!q! / [ (2q)!i!(q-i)! ] (-A)^i
// Scale A by 1 / 2^j
const Apos = multiply(A, Math.pow(2, -j));
// The i=0 term is just the identity matrix
let N = identity(n);
let D = identity(n);
// Initialization (i=0)
let factor = 1;
// Initialization (i=1)
let AposToI = Apos; // Cloning not necessary
let alternate = -1;
for (let i = 1; i <= q; i++) {
if (i > 1) {
AposToI = multiply(AposToI, Apos);
alternate = -alternate;
}
factor = factor * (q - i + 1) / ((2 * q - i + 1) * i);
N = add(N, multiply(factor, AposToI));
D = add(D, multiply(factor * alternate, AposToI));
}
let R = multiply(inv(D), N);
// Square j times
for (let i = 0; i < j; i++) {
R = multiply(R, R);
}
return (0, _is.isSparseMatrix)(A) ? A.createSparseMatrix(R) : R;
}
});
function infinityNorm(A) {
const n = A.size()[0];
let infNorm = 0;
for (let i = 0; i < n; i++) {
let rowSum = 0;
for (let j = 0; j < n; j++) {
rowSum += abs(A.get([i, j]));
}
infNorm = Math.max(rowSum, infNorm);
}
return infNorm;
}
/**
* Find the best parameters for the Pade approximant given
* the matrix norm and desired accuracy. Returns the first acceptable
* combination in order of increasing computational load.
*/
function findParams(infNorm, eps) {
const maxSearchSize = 30;
for (let k = 0; k < maxSearchSize; k++) {
for (let q = 0; q <= k; q++) {
const j = k - q;
if (errorEstimate(infNorm, q, j) < eps) {
return {
q,
j
};
}
}
}
throw new Error('Could not find acceptable parameters to compute the matrix exponential (try increasing maxSearchSize in expm.js)');
}
/**
* Returns the estimated error of the Pade approximant for the given
* parameters.
*/
function errorEstimate(infNorm, q, j) {
let qfac = 1;
for (let i = 2; i <= q; i++) {
qfac *= i;
}
let twoqfac = qfac;
for (let i = q + 1; i <= 2 * q; i++) {
twoqfac *= i;
}
const twoqp1fac = twoqfac * (2 * q + 1);
return 8.0 * Math.pow(infNorm / Math.pow(2, j), 2 * q) * qfac * qfac / (twoqfac * twoqp1fac);
}
});

134
node_modules/mathjs/lib/cjs/function/matrix/fft.js generated vendored Normal file
View File

@@ -0,0 +1,134 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createFft = void 0;
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'fft';
const dependencies = ['typed', 'matrix', 'addScalar', 'multiplyScalar', 'divideScalar', 'exp', 'tau', 'i', 'dotDivide', 'conj', 'pow', 'ceil', 'log2'];
const createFft = exports.createFft = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
addScalar,
multiplyScalar,
divideScalar,
exp,
tau,
i: I,
dotDivide,
conj,
pow,
ceil,
log2
} = _ref;
/**
* Calculate N-dimensional Fourier transform
*
* Syntax:
*
* math.fft(arr)
*
* Examples:
*
* math.fft([[1, 0], [1, 0]]) // returns [[{re:2, im:0}, {re:2, im:0}], [{re:0, im:0}, {re:0, im:0}]]
*
*
* See Also:
*
* ifft
*
* @param {Array | Matrix} arr An array or matrix
* @return {Array | Matrix} N-dimensional Fourier transformation of the array
*/
return typed(name, {
Array: _ndFft,
Matrix: function (matrix) {
return matrix.create(_ndFft(matrix.valueOf()), matrix.datatype());
}
});
/**
* Perform an N-dimensional Fourier transform
*
* @param {Array} arr The array
* @return {Array} resulting array
*/
function _ndFft(arr) {
const size = (0, _array.arraySize)(arr);
if (size.length === 1) return _fft(arr, size[0]);
// ndFft along dimension 1,...,N-1 then 1dFft along dimension 0
return _1dFft(arr.map(slice => _ndFft(slice, size.slice(1))), 0);
}
/**
* Perform an 1-dimensional Fourier transform
*
* @param {Array} arr The array
* @param {number} dim dimension of the array to perform on
* @return {Array} resulting array
*/
function _1dFft(arr, dim) {
const size = (0, _array.arraySize)(arr);
if (dim !== 0) return new Array(size[0]).fill(0).map((_, i) => _1dFft(arr[i], dim - 1));
if (size.length === 1) return _fft(arr);
function _transpose(arr) {
// Swap first 2 dimensions
const size = (0, _array.arraySize)(arr);
return new Array(size[1]).fill(0).map((_, j) => new Array(size[0]).fill(0).map((_, i) => arr[i][j]));
}
return _transpose(_1dFft(_transpose(arr), 1));
}
/**
* Perform an 1-dimensional non-power-of-2 Fourier transform using Chirp-Z Transform
*
* @param {Array} arr The array
* @return {Array} resulting array
*/
function _czt(arr) {
const n = arr.length;
const w = exp(divideScalar(multiplyScalar(-1, multiplyScalar(I, tau)), n));
const chirp = [];
for (let i = 1 - n; i < n; i++) {
chirp.push(pow(w, divideScalar(pow(i, 2), 2)));
}
const N2 = pow(2, ceil(log2(n + n - 1)));
const xp = [...new Array(n).fill(0).map((_, i) => multiplyScalar(arr[i], chirp[n - 1 + i])), ...new Array(N2 - n).fill(0)];
const ichirp = [...new Array(n + n - 1).fill(0).map((_, i) => divideScalar(1, chirp[i])), ...new Array(N2 - (n + n - 1)).fill(0)];
const fftXp = _fft(xp);
const fftIchirp = _fft(ichirp);
const fftProduct = new Array(N2).fill(0).map((_, i) => multiplyScalar(fftXp[i], fftIchirp[i]));
const ifftProduct = dotDivide(conj(_ndFft(conj(fftProduct))), N2);
const ret = [];
for (let i = n - 1; i < n + n - 1; i++) {
ret.push(multiplyScalar(ifftProduct[i], chirp[i]));
}
return ret;
}
/**
* Perform an 1-dimensional Fourier transform
*
* @param {Array} arr The array
* @return {Array} resulting array
*/
function _fft(arr) {
const len = arr.length;
if (len === 1) return [arr[0]];
if (len % 2 === 0) {
const ret = [..._fft(arr.filter((_, i) => i % 2 === 0), len / 2), ..._fft(arr.filter((_, i) => i % 2 === 1), len / 2)];
for (let k = 0; k < len / 2; k++) {
const p = ret[k];
const q = multiplyScalar(ret[k + len / 2], exp(multiplyScalar(multiplyScalar(tau, I), divideScalar(-k, len))));
ret[k] = addScalar(p, q);
ret[k + len / 2] = addScalar(p, multiplyScalar(-1, q));
}
return ret;
} else {
// use chirp-z transform for non-power-of-2 FFT
return _czt(arr);
}
// throw new Error('Can only calculate FFT of power-of-two size')
}
});

77
node_modules/mathjs/lib/cjs/function/matrix/filter.js generated vendored Normal file
View File

@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createFilter = void 0;
var _optimizeCallback = require("../../utils/optimizeCallback.js");
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'filter';
const dependencies = ['typed'];
const createFilter = exports.createFilter = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed
} = _ref;
/**
* Filter the items in an array or one dimensional matrix.
*
* The callback is invoked with three arguments: the current value,
* the current index, and the matrix operated upon.
* Note that because the matrix/array might be
* multidimensional, the "index" argument is always an array of numbers giving
* the index in each dimension. This is true even for vectors: the "index"
* argument is an array of length 1, rather than simply a number.
*
* Syntax:
*
* math.filter(x, test)
*
* Examples:
*
* function isPositive (x) {
* return x > 0
* }
* math.filter([6, -2, -1, 4, 3], isPositive) // returns [6, 4, 3]
*
* math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/) // returns ["23", "100", "55"]
*
* See also:
*
* forEach, map, sort
*
* @param {Matrix | Array} x A one dimensional matrix or array to filter
* @param {Function | RegExp} test
* A function or regular expression to test items.
* All entries for which `test` returns true are returned.
* When `test` is a function, it is invoked with three parameters:
* the value of the element, the index of the element, and the
* matrix/array being traversed. The function must return a boolean.
* @return {Matrix | Array} Returns the filtered matrix.
*/
return typed('filter', {
'Array, function': _filterCallback,
'Matrix, function': function (x, test) {
return x.create(_filterCallback(x.valueOf(), test), x.datatype());
},
'Array, RegExp': _array.filterRegExp,
'Matrix, RegExp': function (x, test) {
return x.create((0, _array.filterRegExp)(x.valueOf(), test), x.datatype());
}
});
});
/**
* Filter values in a callback given a callback function
* @param {Array} x
* @param {Function} callback
* @return {Array} Returns the filtered array
* @private
*/
function _filterCallback(x, callback) {
const fastCallback = (0, _optimizeCallback.optimizeCallback)(callback, x, 'filter');
return (0, _array.filter)(x, function (value, index, array) {
// invoke the callback function with the right number of arguments
return fastCallback(value, [index], array);
});
}

44
node_modules/mathjs/lib/cjs/function/matrix/flatten.js generated vendored Normal file
View File

@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createFlatten = void 0;
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'flatten';
const dependencies = ['typed'];
const createFlatten = exports.createFlatten = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed
} = _ref;
/**
* Flatten a multidimensional matrix into a single dimensional matrix.
* A new matrix is returned, the original matrix is left untouched.
*
* Syntax:
*
* math.flatten(x)
*
* Examples:
*
* math.flatten([[1,2], [3,4]]) // returns [1, 2, 3, 4]
*
* See also:
*
* concat, resize, size, squeeze
*
* @param {Matrix | Array} x Matrix to be flattened
* @return {Matrix | Array} Returns the flattened matrix
*/
return typed(name, {
Array: function (x) {
return (0, _array.flatten)(x);
},
Matrix: function (x) {
// Return the same matrix type as x (Dense or Sparse Matrix)
// Return the same data type as x
return x.create((0, _array.flatten)(x.toArray()), x.datatype());
}
});
});

62
node_modules/mathjs/lib/cjs/function/matrix/forEach.js generated vendored Normal file
View File

@@ -0,0 +1,62 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createForEach = void 0;
var _optimizeCallback = require("../../utils/optimizeCallback.js");
var _factory = require("../../utils/factory.js");
var _array = require("../../utils/array.js");
const name = 'forEach';
const dependencies = ['typed'];
const createForEach = exports.createForEach = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed
} = _ref;
/**
* Iterate over all elements of a matrix/array, and executes the given callback function.
*
* The callback is invoked with three arguments: the current value,
* the current index, and the matrix operated upon.
* Note that because the matrix/array might be
* multidimensional, the "index" argument is always an array of numbers giving
* the index in each dimension. This is true even for vectors: the "index"
* argument is an array of length 1, rather than simply a number.
*
* Syntax:
*
* math.forEach(x, callback)
*
* Examples:
*
* math.forEach([1, 2, 3], function(value) {
* console.log(value)
* })
* // outputs 1, 2, 3
*
* See also:
*
* filter, map, sort
*
* @param {Matrix | Array} x The matrix to iterate on.
* @param {Function} callback The callback function is invoked with three
* parameters: the value of the element, the index
* of the element, and the Matrix/array being traversed.
*/
return typed(name, {
'Array, function': _forEach,
'Matrix, function': function (x, callback) {
x.forEach(callback);
}
});
});
/**
* forEach for a multidimensional array
* @param {Array} array
* @param {Function} callback
* @private
*/
function _forEach(array, callback) {
(0, _array.recurse)(array, [], array, (0, _optimizeCallback.optimizeCallback)(callback, array, name));
}

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createGetMatrixDataType = void 0;
var _factory = require("../../utils/factory.js");
var _array = require("../../utils/array.js");
var _is = require("../../utils/is.js");
const name = 'getMatrixDataType';
const dependencies = ['typed'];
const createGetMatrixDataType = exports.createGetMatrixDataType = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed
} = _ref;
/**
* Find the data type of all elements in a matrix or array,
* for example 'number' if all items are a number and 'Complex' if all values
* are complex numbers.
* If a matrix contains more than one data type, it will return 'mixed'.
*
* Syntax:
*
* math.getMatrixDataType(x)
*
* Examples:
*
* const x = [ [1, 2, 3], [4, 5, 6] ]
* const mixedX = [ [1, true], [2, 3] ]
* const fractionX = [ [math.fraction(1, 3)], [math.fraction(1, 3)] ]
* const unitX = [ [math.unit('5cm')], [math.unit('5cm')] ]
* const bigNumberX = [ [math.bignumber(1)], [math.bignumber(0)] ]
* const sparse = math.sparse(x)
* const dense = math.matrix(x)
* math.getMatrixDataType(x) // returns 'number'
* math.getMatrixDataType(sparse) // returns 'number'
* math.getMatrixDataType(dense) // returns 'number'
* math.getMatrixDataType(mixedX) // returns 'mixed'
* math.getMatrixDataType(fractionX) // returns 'Fraction'
* math.getMatrixDataType(unitX) // returns 'Unit'
* math.getMatrixDataType(bigNumberX) // return 'BigNumber'
*
* See also:
* SparseMatrix, DenseMatrix
*
* @param {...Matrix | Array} x The Matrix with values.
*
* @return {string} A string representation of the matrix type
*/
return typed(name, {
Array: function (x) {
return (0, _array.getArrayDataType)(x, _is.typeOf);
},
Matrix: function (x) {
return x.getDataType();
}
});
});

142
node_modules/mathjs/lib/cjs/function/matrix/identity.js generated vendored Normal file
View File

@@ -0,0 +1,142 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createIdentity = void 0;
var _is = require("../../utils/is.js");
var _array = require("../../utils/array.js");
var _number = require("../../utils/number.js");
var _factory = require("../../utils/factory.js");
const name = 'identity';
const dependencies = ['typed', 'config', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix'];
const createIdentity = exports.createIdentity = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
config,
matrix,
BigNumber,
DenseMatrix,
SparseMatrix
} = _ref;
/**
* Create a 2-dimensional identity matrix with size m x n or n x n.
* The matrix has ones on the diagonal and zeros elsewhere.
*
* Syntax:
*
* math.identity(n)
* math.identity(n, format)
* math.identity(m, n)
* math.identity(m, n, format)
* math.identity([m, n])
* math.identity([m, n], format)
*
* Examples:
*
* math.identity(3) // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
* math.identity(3, 2) // returns [[1, 0], [0, 1], [0, 0]]
*
* const A = [[1, 2, 3], [4, 5, 6]]
* math.identity(math.size(A)) // returns [[1, 0, 0], [0, 1, 0]]
*
* See also:
*
* diag, ones, zeros, size, range
*
* @param {...number | Matrix | Array} size The size for the matrix
* @param {string} [format] The Matrix storage format
*
* @return {Matrix | Array | number} A matrix with ones on the diagonal.
*/
return typed(name, {
'': function () {
return config.matrix === 'Matrix' ? matrix([]) : [];
},
string: function (format) {
return matrix(format);
},
'number | BigNumber': function (rows) {
return _identity(rows, rows, config.matrix === 'Matrix' ? 'dense' : undefined);
},
'number | BigNumber, string': function (rows, format) {
return _identity(rows, rows, format);
},
'number | BigNumber, number | BigNumber': function (rows, cols) {
return _identity(rows, cols, config.matrix === 'Matrix' ? 'dense' : undefined);
},
'number | BigNumber, number | BigNumber, string': function (rows, cols, format) {
return _identity(rows, cols, format);
},
Array: function (size) {
return _identityVector(size);
},
'Array, string': function (size, format) {
return _identityVector(size, format);
},
Matrix: function (size) {
return _identityVector(size.valueOf(), size.storage());
},
'Matrix, string': function (size, format) {
return _identityVector(size.valueOf(), format);
}
});
function _identityVector(size, format) {
switch (size.length) {
case 0:
return format ? matrix(format) : [];
case 1:
return _identity(size[0], size[0], format);
case 2:
return _identity(size[0], size[1], format);
default:
throw new Error('Vector containing two values expected');
}
}
/**
* Create an identity matrix
* @param {number | BigNumber} rows
* @param {number | BigNumber} cols
* @param {string} [format]
* @returns {Matrix}
* @private
*/
function _identity(rows, cols, format) {
// BigNumber constructor with the right precision
const Big = (0, _is.isBigNumber)(rows) || (0, _is.isBigNumber)(cols) ? BigNumber : null;
if ((0, _is.isBigNumber)(rows)) rows = rows.toNumber();
if ((0, _is.isBigNumber)(cols)) cols = cols.toNumber();
if (!(0, _number.isInteger)(rows) || rows < 1) {
throw new Error('Parameters in function identity must be positive integers');
}
if (!(0, _number.isInteger)(cols) || cols < 1) {
throw new Error('Parameters in function identity must be positive integers');
}
const one = Big ? new BigNumber(1) : 1;
const defaultValue = Big ? new Big(0) : 0;
const size = [rows, cols];
// check we need to return a matrix
if (format) {
// create diagonal matrix (use optimized implementation for storage format)
if (format === 'sparse') {
return SparseMatrix.diagonal(size, one, 0, defaultValue);
}
if (format === 'dense') {
return DenseMatrix.diagonal(size, one, 0, defaultValue);
}
throw new TypeError(`Unknown matrix type "${format}"`);
}
// create and resize array
const res = (0, _array.resize)([], size, defaultValue);
// fill in ones on the diagonal
const minimum = rows < cols ? rows : cols;
// fill diagonal
for (let d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
}
});

43
node_modules/mathjs/lib/cjs/function/matrix/ifft.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createIfft = void 0;
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
var _is = require("../../utils/is.js");
const name = 'ifft';
const dependencies = ['typed', 'fft', 'dotDivide', 'conj'];
const createIfft = exports.createIfft = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
fft,
dotDivide,
conj
} = _ref;
/**
* Calculate N-dimensional inverse Fourier transform
*
* Syntax:
*
* math.ifft(arr)
*
* Examples:
*
* math.ifft([[2, 2], [0, 0]]) // returns [[{re:1, im:0}, {re:0, im:0}], [{re:1, im:0}, {re:0, im:0}]]
*
* See Also:
*
* fft
*
* @param {Array | Matrix} arr An array or matrix
* @return {Array | Matrix} N-dimensional Fourier transformation of the array
*/
return typed(name, {
'Array | Matrix': function (arr) {
const size = (0, _is.isMatrix)(arr) ? arr.size() : (0, _array.arraySize)(arr);
return dotDivide(conj(fft(conj(arr))), size.reduce((acc, curr) => acc * curr, 1));
}
});
});

190
node_modules/mathjs/lib/cjs/function/matrix/inv.js generated vendored Normal file
View File

@@ -0,0 +1,190 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createInv = void 0;
var _is = require("../../utils/is.js");
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
var _string = require("../../utils/string.js");
const name = 'inv';
const dependencies = ['typed', 'matrix', 'divideScalar', 'addScalar', 'multiply', 'unaryMinus', 'det', 'identity', 'abs'];
const createInv = exports.createInv = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
divideScalar,
addScalar,
multiply,
unaryMinus,
det,
identity,
abs
} = _ref;
/**
* Calculate the inverse of a square matrix.
*
* Syntax:
*
* math.inv(x)
*
* Examples:
*
* math.inv([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]]
* math.inv(4) // returns 0.25
* 1 / 4 // returns 0.25
*
* See also:
*
* det, transpose
*
* @param {number | Complex | Array | Matrix} x Matrix to be inversed
* @return {number | Complex | Array | Matrix} The inverse of `x`.
*/
return typed(name, {
'Array | Matrix': function (x) {
const size = (0, _is.isMatrix)(x) ? x.size() : (0, _array.arraySize)(x);
switch (size.length) {
case 1:
// vector
if (size[0] === 1) {
if ((0, _is.isMatrix)(x)) {
return matrix([divideScalar(1, x.valueOf()[0])]);
} else {
return [divideScalar(1, x[0])];
}
} else {
throw new RangeError('Matrix must be square ' + '(size: ' + (0, _string.format)(size) + ')');
}
case 2:
// two dimensional array
{
const rows = size[0];
const cols = size[1];
if (rows === cols) {
if ((0, _is.isMatrix)(x)) {
return matrix(_inv(x.valueOf(), rows, cols), x.storage());
} else {
// return an Array
return _inv(x, rows, cols);
}
} else {
throw new RangeError('Matrix must be square ' + '(size: ' + (0, _string.format)(size) + ')');
}
}
default:
// multi dimensional array
throw new RangeError('Matrix must be two dimensional ' + '(size: ' + (0, _string.format)(size) + ')');
}
},
any: function (x) {
// scalar
return divideScalar(1, x); // FIXME: create a BigNumber one when configured for bignumbers
}
});
/**
* Calculate the inverse of a square matrix
* @param {Array[]} mat A square matrix
* @param {number} rows Number of rows
* @param {number} cols Number of columns, must equal rows
* @return {Array[]} inv Inverse matrix
* @private
*/
function _inv(mat, rows, cols) {
let r, s, f, value, temp;
if (rows === 1) {
// this is a 1 x 1 matrix
value = mat[0][0];
if (value === 0) {
throw Error('Cannot calculate inverse, determinant is zero');
}
return [[divideScalar(1, value)]];
} else if (rows === 2) {
// this is a 2 x 2 matrix
const d = det(mat);
if (d === 0) {
throw Error('Cannot calculate inverse, determinant is zero');
}
return [[divideScalar(mat[1][1], d), divideScalar(unaryMinus(mat[0][1]), d)], [divideScalar(unaryMinus(mat[1][0]), d), divideScalar(mat[0][0], d)]];
} else {
// this is a matrix of 3 x 3 or larger
// calculate inverse using gauss-jordan elimination
// https://en.wikipedia.org/wiki/Gaussian_elimination
// http://mathworld.wolfram.com/MatrixInverse.html
// http://math.uww.edu/~mcfarlat/inverse.htm
// make a copy of the matrix (only the arrays, not of the elements)
const A = mat.concat();
for (r = 0; r < rows; r++) {
A[r] = A[r].concat();
}
// create an identity matrix which in the end will contain the
// matrix inverse
const B = identity(rows).valueOf();
// loop over all columns, and perform row reductions
for (let c = 0; c < cols; c++) {
// Pivoting: Swap row c with row r, where row r contains the largest element A[r][c]
let ABig = abs(A[c][c]);
let rBig = c;
r = c + 1;
while (r < rows) {
if (abs(A[r][c]) > ABig) {
ABig = abs(A[r][c]);
rBig = r;
}
r++;
}
if (ABig === 0) {
throw Error('Cannot calculate inverse, determinant is zero');
}
r = rBig;
if (r !== c) {
temp = A[c];
A[c] = A[r];
A[r] = temp;
temp = B[c];
B[c] = B[r];
B[r] = temp;
}
// eliminate non-zero values on the other rows at column c
const Ac = A[c];
const Bc = B[c];
for (r = 0; r < rows; r++) {
const Ar = A[r];
const Br = B[r];
if (r !== c) {
// eliminate value at column c and row r
if (Ar[c] !== 0) {
f = divideScalar(unaryMinus(Ar[c]), Ac[c]);
// add (f * row c) to row r to eliminate the value
// at column c
for (s = c; s < cols; s++) {
Ar[s] = addScalar(Ar[s], multiply(f, Ac[s]));
}
for (s = 0; s < cols; s++) {
Br[s] = addScalar(Br[s], multiply(f, Bc[s]));
}
}
} else {
// normalize value at Acc to 1,
// divide each value on row r with the value at Acc
f = Ac[c];
for (s = c; s < cols; s++) {
Ar[s] = divideScalar(Ar[s], f);
}
for (s = 0; s < cols; s++) {
Br[s] = divideScalar(Br[s], f);
}
}
}
}
return B;
}
}
});

91
node_modules/mathjs/lib/cjs/function/matrix/kron.js generated vendored Normal file
View File

@@ -0,0 +1,91 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createKron = void 0;
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'kron';
const dependencies = ['typed', 'matrix', 'multiplyScalar'];
const createKron = exports.createKron = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
multiplyScalar
} = _ref;
/**
* Calculates the Kronecker product of 2 matrices or vectors.
*
* NOTE: If a one dimensional vector / matrix is given, it will be
* wrapped so its two dimensions.
* See the examples.
*
* Syntax:
*
* math.kron(x, y)
*
* Examples:
*
* math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])
* // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ]
*
* math.kron([1,1], [2,3,4])
* // returns [ [ 2, 3, 4, 2, 3, 4 ] ]
*
* See also:
*
* multiply, dot, cross
*
* @param {Array | Matrix} x First vector
* @param {Array | Matrix} y Second vector
* @return {Array | Matrix} Returns the Kronecker product of `x` and `y`
*/
return typed(name, {
'Matrix, Matrix': function (x, y) {
return matrix(_kron(x.toArray(), y.toArray()));
},
'Matrix, Array': function (x, y) {
return matrix(_kron(x.toArray(), y));
},
'Array, Matrix': function (x, y) {
return matrix(_kron(x, y.toArray()));
},
'Array, Array': _kron
});
/**
* Calculate the Kronecker product of two matrices / vectors
* @param {Array} a First vector
* @param {Array} b Second vector
* @returns {Array} Returns the Kronecker product of x and y
* @private
*/
function _kron(a, b) {
// Deal with the dimensions of the matricies.
if ((0, _array.arraySize)(a).length === 1) {
// Wrap it in a 2D Matrix
a = [a];
}
if ((0, _array.arraySize)(b).length === 1) {
// Wrap it in a 2D Matrix
b = [b];
}
if ((0, _array.arraySize)(a).length > 2 || (0, _array.arraySize)(b).length > 2) {
throw new RangeError('Vectors with dimensions greater then 2 are not supported expected ' + '(Size x = ' + JSON.stringify(a.length) + ', y = ' + JSON.stringify(b.length) + ')');
}
const t = [];
let r = [];
return a.map(function (a) {
return b.map(function (b) {
r = [];
t.push(r);
return a.map(function (y) {
return b.map(function (x) {
return r.push(multiplyScalar(y, x));
});
});
});
}) && t;
}
});

148
node_modules/mathjs/lib/cjs/function/matrix/map.js generated vendored Normal file
View File

@@ -0,0 +1,148 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createMap = void 0;
var _optimizeCallback = require("../../utils/optimizeCallback.js");
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'map';
const dependencies = ['typed'];
const createMap = exports.createMap = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed
} = _ref;
/**
* Create a new matrix or array with the results of a callback function executed on
* each entry of a given matrix/array.
*
* For each entry of the input,
*
* the callback is invoked with 2N + 1 arguments:
* the N values of the entry, the index at which that entry occurs, and the N full
* broadcasted matrix/array being traversed where N is the number of matrices being traversed.
* Note that because the matrix/array might be
* multidimensional, the "index" argument is always an array of numbers giving
* the index in each dimension. This is true even for vectors: the "index"
* argument is an array of length 1, rather than simply a number.
*
* Syntax:
*
* math.map(x, callback)
* math.map(x, y, ..., callback)
*
* Examples:
*
* math.map([1, 2, 3], function(value) {
* return value * value
* }) // returns [1, 4, 9]
* math.map([1, 2], [3, 4], function(a, b) {
* return a + b
* }) // returns [4, 6]
*
* // The callback is normally called with three arguments:
* // callback(value, index, Array)
* // If you want to call with only one argument, use:
* math.map([1, 2, 3], x => math.format(x)) // returns ['1', '2', '3']
* // It can also be called with 2N + 1 arguments: for N arrays
* // callback(value1, value2, index, BroadcastedArray1, BroadcastedArray2)
*
* See also:
*
* filter, forEach, sort
*
* @param {Matrix | Array} x The input to iterate on.
* @param {Function} callback
* The function to call (as described above) on each entry of the input
* @return {Matrix | array}
* Transformed map of x; always has the same type and shape as x
*/
return typed(name, {
'Array, function': _mapArray,
'Matrix, function': function (x, callback) {
return x.map(callback);
},
'Array|Matrix, Array|Matrix, ...Array|Matrix|function': (A, B, rest) => _mapMultiple([A, B, ...rest.slice(0, rest.length - 1)], rest[rest.length - 1])
});
/**
* Maps over multiple arrays or matrices.
*
* @param {Array<Array|Matrix>} Arrays - An array of arrays or matrices to map over.
* @param {function} multiCallback - The callback function to apply to each element.
* @throws {Error} If the last argument is not a callback function.
* @returns {Array|Matrix} A new array or matrix with each element being the result of the callback function.
*
* @example
* _mapMultiple([[1, 2, 3], [4, 5, 6]], (a, b) => a + b); // Returns [5, 7, 9]
*/
function _mapMultiple(Arrays, multiCallback) {
if (typeof multiCallback !== 'function') {
throw new Error('Last argument must be a callback function');
}
const firstArrayIsMatrix = Arrays[0].isMatrix;
const newSize = (0, _array.broadcastSizes)(...Arrays.map(M => M.isMatrix ? M.size() : (0, _array.arraySize)(M)));
const _get = firstArrayIsMatrix ? (matrix, idx) => matrix.get(idx) : _array.get;
const broadcastedArrays = firstArrayIsMatrix ? Arrays.map(M => M.isMatrix ? M.create((0, _array.broadcastTo)(M.toArray(), newSize), M.datatype()) : Arrays[0].create((0, _array.broadcastTo)(M.valueOf(), newSize))) : Arrays.map(M => M.isMatrix ? (0, _array.broadcastTo)(M.toArray(), newSize) : (0, _array.broadcastTo)(M, newSize));
let callback;
if (typed.isTypedFunction(multiCallback)) {
const firstIndex = newSize.map(() => 0);
const firstValues = broadcastedArrays.map(array => _get(array, firstIndex));
const callbackCase = _getTypedCallbackCase(multiCallback, firstValues, firstIndex, broadcastedArrays);
callback = _getLimitedCallback(callbackCase);
} else {
const numberOfArrays = Arrays.length;
const callbackCase = _getCallbackCase(multiCallback, numberOfArrays);
callback = _getLimitedCallback(callbackCase);
}
const broadcastedArraysCallback = (x, idx) => callback([x, ...broadcastedArrays.slice(1).map(Array => _get(Array, idx))], idx);
if (firstArrayIsMatrix) {
return broadcastedArrays[0].map(broadcastedArraysCallback);
} else {
return _mapArray(broadcastedArrays[0], broadcastedArraysCallback);
}
function _getLimitedCallback(callbackCase) {
switch (callbackCase) {
case 0:
return x => multiCallback(...x);
case 1:
return (x, idx) => multiCallback(...x, idx);
case 2:
return (x, idx) => multiCallback(...x, idx, ...broadcastedArrays);
}
}
function _getCallbackCase(callback, numberOfArrays) {
if (callback.length > numberOfArrays + 1) {
return 2;
}
if (callback.length === numberOfArrays + 1) {
return 1;
}
return 0;
}
function _getTypedCallbackCase(callback, values, idx, arrays) {
if (typed.resolve(callback, [...values, idx, ...arrays]) !== null) {
return 2;
}
if (typed.resolve(callback, [...values, idx]) !== null) {
return 1;
}
if (typed.resolve(callback, values) !== null) {
return 0;
}
// this should never happen
return 0;
}
}
/**
* Map for a multi dimensional array
* @param {Array} array
* @param {Function} callback
* @return {Array}
* @private
*/
function _mapArray(array, callback) {
return (0, _array.recurse)(array, [], array, (0, _optimizeCallback.optimizeCallback)(callback, array, name));
}
});

View File

@@ -0,0 +1,94 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createMatrixFromColumns = void 0;
var _factory = require("../../utils/factory.js");
const name = 'matrixFromColumns';
const dependencies = ['typed', 'matrix', 'flatten', 'size'];
const createMatrixFromColumns = exports.createMatrixFromColumns = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
flatten,
size
} = _ref;
/**
* Create a dense matrix from vectors as individual columns.
* If you pass row vectors, they will be transposed (but not conjugated!)
*
* Syntax:
*
* math.matrixFromColumns(...arr)
* math.matrixFromColumns(col1, col2)
* math.matrixFromColumns(col1, col2, col3)
*
* Examples:
*
* math.matrixFromColumns([1, 2, 3], [[4],[5],[6]])
* math.matrixFromColumns(...vectors)
*
* See also:
*
* matrix, matrixFromRows, matrixFromFunction, zeros
*
* @param {... Array | Matrix} cols Multiple columns
* @return { number[][] | Matrix } if at least one of the arguments is an array, an array will be returned
*/
return typed(name, {
'...Array': function (arr) {
return _createArray(arr);
},
'...Matrix': function (arr) {
return matrix(_createArray(arr.map(m => m.toArray())));
}
// TODO implement this properly for SparseMatrix
});
function _createArray(arr) {
if (arr.length === 0) throw new TypeError('At least one column is needed to construct a matrix.');
const N = checkVectorTypeAndReturnLength(arr[0]);
// create an array with empty rows
const result = [];
for (let i = 0; i < N; i++) {
result[i] = [];
}
// loop columns
for (const col of arr) {
const colLength = checkVectorTypeAndReturnLength(col);
if (colLength !== N) {
throw new TypeError('The vectors had different length: ' + (N | 0) + ' ≠ ' + (colLength | 0));
}
const f = flatten(col);
// push a value to each row
for (let i = 0; i < N; i++) {
result[i].push(f[i]);
}
}
return result;
}
function checkVectorTypeAndReturnLength(vec) {
const s = size(vec);
if (s.length === 1) {
// 1D vector
return s[0];
} else if (s.length === 2) {
// 2D vector
if (s[0] === 1) {
// row vector
return s[1];
} else if (s[1] === 1) {
// col vector
return s[0];
} else {
throw new TypeError('At least one of the arguments is not a vector.');
}
} else {
throw new TypeError('Only one- or two-dimensional vectors are supported.');
}
}
});

View File

@@ -0,0 +1,80 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createMatrixFromFunction = void 0;
var _factory = require("../../utils/factory.js");
const name = 'matrixFromFunction';
const dependencies = ['typed', 'matrix', 'isZero'];
const createMatrixFromFunction = exports.createMatrixFromFunction = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
isZero
} = _ref;
/**
* Create a matrix by evaluating a generating function at each index.
* The simplest overload returns a multi-dimensional array as long as `size` is an array.
* Passing `size` as a Matrix or specifying a `format` will result in returning a Matrix.
*
* Syntax:
*
* math.matrixFromFunction(size, fn)
* math.matrixFromFunction(size, fn, format)
* math.matrixFromFunction(size, fn, format, datatype)
* math.matrixFromFunction(size, format, fn)
* math.matrixFromFunction(size, format, datatype, fn)
*
* Examples:
*
* math.matrixFromFunction([3,3], i => i[0] - i[1]) // an antisymmetric matrix
* math.matrixFromFunction([100, 100], 'sparse', i => i[0] - i[1] === 1 ? 4 : 0) // a sparse subdiagonal matrix
* math.matrixFromFunction([5], i => math.random()) // a random vector
*
* See also:
*
* matrix, zeros
*
* @param {Array | Matrix} size The size of the matrix to be created
* @param {function} fn Callback function invoked for every entry in the matrix
* @param {string} [format] The Matrix storage format, either `'dense'` or `'sparse'`
* @param {string} [datatype] Type of the values
* @return {Array | Matrix} Returns the created matrix
*/
return typed(name, {
'Array | Matrix, function, string, string': function (size, fn, format, datatype) {
return _create(size, fn, format, datatype);
},
'Array | Matrix, function, string': function (size, fn, format) {
return _create(size, fn, format);
},
'Matrix, function': function (size, fn) {
return _create(size, fn, 'dense');
},
'Array, function': function (size, fn) {
return _create(size, fn, 'dense').toArray();
},
'Array | Matrix, string, function': function (size, format, fn) {
return _create(size, fn, format);
},
'Array | Matrix, string, string, function': function (size, format, datatype, fn) {
return _create(size, fn, format, datatype);
}
});
function _create(size, fn, format, datatype) {
let m;
if (datatype !== undefined) {
m = matrix(format, datatype);
} else {
m = matrix(format);
}
m.resize(size);
m.forEach(function (_, index) {
const val = fn(index);
if (isZero(val)) return;
m.set(index, val);
});
return m;
}
});

View File

@@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createMatrixFromRows = void 0;
var _factory = require("../../utils/factory.js");
const name = 'matrixFromRows';
const dependencies = ['typed', 'matrix', 'flatten', 'size'];
const createMatrixFromRows = exports.createMatrixFromRows = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
flatten,
size
} = _ref;
/**
* Create a dense matrix from vectors as individual rows.
* If you pass column vectors, they will be transposed (but not conjugated!)
*
* Syntax:
*
* math.matrixFromRows(...arr)
* math.matrixFromRows(row1, row2)
* math.matrixFromRows(row1, row2, row3)
*
* Examples:
*
* math.matrixFromRows([1, 2, 3], [[4],[5],[6]])
* math.matrixFromRows(...vectors)
*
* See also:
*
* matrix, matrixFromColumns, matrixFromFunction, zeros
*
* @param {... Array | Matrix} rows Multiple rows
* @return { number[][] | Matrix } if at least one of the arguments is an array, an array will be returned
*/
return typed(name, {
'...Array': function (arr) {
return _createArray(arr);
},
'...Matrix': function (arr) {
return matrix(_createArray(arr.map(m => m.toArray())));
}
// TODO implement this properly for SparseMatrix
});
function _createArray(arr) {
if (arr.length === 0) throw new TypeError('At least one row is needed to construct a matrix.');
const N = checkVectorTypeAndReturnLength(arr[0]);
const result = [];
for (const row of arr) {
const rowLength = checkVectorTypeAndReturnLength(row);
if (rowLength !== N) {
throw new TypeError('The vectors had different length: ' + (N | 0) + ' ≠ ' + (rowLength | 0));
}
result.push(flatten(row));
}
return result;
}
function checkVectorTypeAndReturnLength(vec) {
const s = size(vec);
if (s.length === 1) {
// 1D vector
return s[0];
} else if (s.length === 2) {
// 2D vector
if (s[0] === 1) {
// row vector
return s[1];
} else if (s[1] === 1) {
// col vector
return s[0];
} else {
throw new TypeError('At least one of the arguments is not a vector.');
}
} else {
throw new TypeError('Only one- or two-dimensional vectors are supported.');
}
}
});

129
node_modules/mathjs/lib/cjs/function/matrix/ones.js generated vendored Normal file
View File

@@ -0,0 +1,129 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createOnes = void 0;
var _is = require("../../utils/is.js");
var _number = require("../../utils/number.js");
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'ones';
const dependencies = ['typed', 'config', 'matrix', 'BigNumber'];
const createOnes = exports.createOnes = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
config,
matrix,
BigNumber
} = _ref;
/**
* Create a matrix filled with ones. The created matrix can have one or
* multiple dimensions.
*
* Syntax:
*
* math.ones(m)
* math.ones(m, format)
* math.ones(m, n)
* math.ones(m, n, format)
* math.ones([m, n])
* math.ones([m, n], format)
* math.ones([m, n, p, ...])
* math.ones([m, n, p, ...], format)
*
* Examples:
*
* math.ones() // returns []
* math.ones(3) // returns [1, 1, 1]
* math.ones(3, 2) // returns [[1, 1], [1, 1], [1, 1]]
* math.ones(3, 2, 'dense') // returns Dense Matrix [[1, 1], [1, 1], [1, 1]]
*
* const A = [[1, 2, 3], [4, 5, 6]]
* math.ones(math.size(A)) // returns [[1, 1, 1], [1, 1, 1]]
*
* See also:
*
* zeros, identity, size, range
*
* @param {...(number|BigNumber) | Array} size The size of each dimension of the matrix
* @param {string} [format] The Matrix storage format
*
* @return {Array | Matrix | number} A matrix filled with ones
*/
return typed('ones', {
'': function () {
return config.matrix === 'Array' ? _ones([]) : _ones([], 'default');
},
// math.ones(m, n, p, ..., format)
// TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
'...number | BigNumber | string': function (size) {
const last = size[size.length - 1];
if (typeof last === 'string') {
const format = size.pop();
return _ones(size, format);
} else if (config.matrix === 'Array') {
return _ones(size);
} else {
return _ones(size, 'default');
}
},
Array: _ones,
Matrix: function (size) {
const format = size.storage();
return _ones(size.valueOf(), format);
},
'Array | Matrix, string': function (size, format) {
return _ones(size.valueOf(), format);
}
});
/**
* Create an Array or Matrix with ones
* @param {Array} size
* @param {string} [format='default']
* @return {Array | Matrix}
* @private
*/
function _ones(size, format) {
const hasBigNumbers = _normalize(size);
const defaultValue = hasBigNumbers ? new BigNumber(1) : 1;
_validate(size);
if (format) {
// return a matrix
const m = matrix(format);
if (size.length > 0) {
return m.resize(size, defaultValue);
}
return m;
} else {
// return an Array
const arr = [];
if (size.length > 0) {
return (0, _array.resize)(arr, size, defaultValue);
}
return arr;
}
}
// replace BigNumbers with numbers, returns true if size contained BigNumbers
function _normalize(size) {
let hasBigNumbers = false;
size.forEach(function (value, index, arr) {
if ((0, _is.isBigNumber)(value)) {
hasBigNumbers = true;
arr[index] = value.toNumber();
}
});
return hasBigNumbers;
}
// validate arguments
function _validate(size) {
size.forEach(function (value) {
if (typeof value !== 'number' || !(0, _number.isInteger)(value) || value < 0) {
throw new Error('Parameters in function ones must be positive integers');
}
});
}
});

View File

@@ -0,0 +1,149 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createPartitionSelect = void 0;
var _is = require("../../utils/is.js");
var _number = require("../../utils/number.js");
var _factory = require("../../utils/factory.js");
const name = 'partitionSelect';
const dependencies = ['typed', 'isNumeric', 'isNaN', 'compare'];
const createPartitionSelect = exports.createPartitionSelect = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
isNumeric,
isNaN,
compare
} = _ref;
const asc = compare;
const desc = (a, b) => -compare(a, b);
/**
* Partition-based selection of an array or 1D matrix.
* Will find the kth smallest value, and mutates the input array.
* Uses Quickselect.
*
* Syntax:
*
* math.partitionSelect(x, k)
* math.partitionSelect(x, k, compare)
*
* Examples:
*
* math.partitionSelect([5, 10, 1], 2) // returns 10
* math.partitionSelect(['C', 'B', 'A', 'D'], 1, math.compareText) // returns 'B'
*
* function sortByLength (a, b) {
* return a.length - b.length
* }
* math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength) // returns 'Langdon'
*
* // the input array is mutated
* arr = [5, 2, 1]
* math.partitionSelect(arr, 0) // returns 1, arr is now: [1, 2, 5]
* math.partitionSelect(arr, 1, 'desc') // returns 2, arr is now: [5, 2, 1]
*
* See also:
*
* sort
*
* @param {Matrix | Array} x A one dimensional matrix or array to sort
* @param {Number} k The kth smallest value to be retrieved zero-based index
* @param {Function | 'asc' | 'desc'} [compare='asc']
* An optional comparator function. The function is called as
* `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
* and 0 when a == b.
* @return {*} Returns the kth lowest value.
*/
return typed(name, {
'Array | Matrix, number': function (x, k) {
return _partitionSelect(x, k, asc);
},
'Array | Matrix, number, string': function (x, k, compare) {
if (compare === 'asc') {
return _partitionSelect(x, k, asc);
} else if (compare === 'desc') {
return _partitionSelect(x, k, desc);
} else {
throw new Error('Compare string must be "asc" or "desc"');
}
},
'Array | Matrix, number, function': _partitionSelect
});
function _partitionSelect(x, k, compare) {
if (!(0, _number.isInteger)(k) || k < 0) {
throw new Error('k must be a non-negative integer');
}
if ((0, _is.isMatrix)(x)) {
const size = x.size();
if (size.length > 1) {
throw new Error('Only one dimensional matrices supported');
}
return quickSelect(x.valueOf(), k, compare);
}
if (Array.isArray(x)) {
return quickSelect(x, k, compare);
}
}
/**
* Quickselect algorithm.
* Code adapted from:
* https://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
*
* @param {Array} arr
* @param {Number} k
* @param {Function} compare
* @private
*/
function quickSelect(arr, k, compare) {
if (k >= arr.length) {
throw new Error('k out of bounds');
}
// check for NaN values since these can cause an infinite while loop
for (let i = 0; i < arr.length; i++) {
if (isNumeric(arr[i]) && isNaN(arr[i])) {
return arr[i]; // return NaN
}
}
let from = 0;
let to = arr.length - 1;
// if from == to we reached the kth element
while (from < to) {
let r = from;
let w = to;
const pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from];
// stop if the reader and writer meets
while (r < w) {
// arr[r] >= pivot
if (compare(arr[r], pivot) >= 0) {
// put the large values at the end
const tmp = arr[w];
arr[w] = arr[r];
arr[r] = tmp;
--w;
} else {
// the value is smaller than the pivot, skip
++r;
}
}
// if we stepped up (r++) we need to step one down (arr[r] > pivot)
if (compare(arr[r], pivot) > 0) {
--r;
}
// the r pointer is on the end of the first k elements
if (k <= r) {
to = r;
} else {
from = r + 1;
}
}
return arr[k];
}
});

185
node_modules/mathjs/lib/cjs/function/matrix/pinv.js generated vendored Normal file
View File

@@ -0,0 +1,185 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createPinv = void 0;
var _is = require("../../utils/is.js");
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
var _string = require("../../utils/string.js");
var _object = require("../../utils/object.js");
const name = 'pinv';
const dependencies = ['typed', 'matrix', 'inv', 'deepEqual', 'equal', 'dotDivide', 'dot', 'ctranspose', 'divideScalar', 'multiply', 'add', 'Complex'];
const createPinv = exports.createPinv = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
inv,
deepEqual,
equal,
dotDivide,
dot,
ctranspose,
divideScalar,
multiply,
add,
Complex
} = _ref;
/**
* Calculate the MoorePenrose inverse of a matrix.
*
* Syntax:
*
* math.pinv(x)
*
* Examples:
*
* math.pinv([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]]
* math.pinv([[1, 0], [0, 1], [0, 1]]) // returns [[1, 0, 0], [0, 0.5, 0.5]]
* math.pinv(4) // returns 0.25
*
* See also:
*
* inv
*
* @param {number | Complex | Array | Matrix} x Matrix to be inversed
* @return {number | Complex | Array | Matrix} The inverse of `x`.
*/
return typed(name, {
'Array | Matrix': function (x) {
const size = (0, _is.isMatrix)(x) ? x.size() : (0, _array.arraySize)(x);
switch (size.length) {
case 1:
// vector
if (_isZeros(x)) return ctranspose(x); // null vector
if (size[0] === 1) {
return inv(x); // invertible matrix
} else {
return dotDivide(ctranspose(x), dot(x, x));
}
case 2:
// two dimensional array
{
if (_isZeros(x)) return ctranspose(x); // zero matrixx
const rows = size[0];
const cols = size[1];
if (rows === cols) {
try {
return inv(x); // invertible matrix
} catch (err) {
if (err instanceof Error && err.message.match(/Cannot calculate inverse, determinant is zero/)) {
// Expected
} else {
throw err;
}
}
}
if ((0, _is.isMatrix)(x)) {
return matrix(_pinv(x.valueOf(), rows, cols), x.storage());
} else {
// return an Array
return _pinv(x, rows, cols);
}
}
default:
// multi dimensional array
throw new RangeError('Matrix must be two dimensional ' + '(size: ' + (0, _string.format)(size) + ')');
}
},
any: function (x) {
// scalar
if (equal(x, 0)) return (0, _object.clone)(x); // zero
return divideScalar(1, x);
}
});
/**
* Calculate the MoorePenrose inverse of a matrix
* @param {Array[]} mat A matrix
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @return {Array[]} pinv Pseudoinverse matrix
* @private
*/
function _pinv(mat, rows, cols) {
const {
C,
F
} = _rankFact(mat, rows, cols); // TODO: Use SVD instead (may improve precision)
const Cpinv = multiply(inv(multiply(ctranspose(C), C)), ctranspose(C));
const Fpinv = multiply(ctranspose(F), inv(multiply(F, ctranspose(F))));
return multiply(Fpinv, Cpinv);
}
/**
* Calculate the reduced row echelon form of a matrix
*
* Modified from https://rosettacode.org/wiki/Reduced_row_echelon_form
*
* @param {Array[]} mat A matrix
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @return {Array[]} Reduced row echelon form
* @private
*/
function _rref(mat, rows, cols) {
const M = (0, _object.clone)(mat);
let lead = 0;
for (let r = 0; r < rows; r++) {
if (cols <= lead) {
return M;
}
let i = r;
while (_isZero(M[i][lead])) {
i++;
if (rows === i) {
i = r;
lead++;
if (cols === lead) {
return M;
}
}
}
[M[i], M[r]] = [M[r], M[i]];
let val = M[r][lead];
for (let j = 0; j < cols; j++) {
M[r][j] = dotDivide(M[r][j], val);
}
for (let i = 0; i < rows; i++) {
if (i === r) continue;
val = M[i][lead];
for (let j = 0; j < cols; j++) {
M[i][j] = add(M[i][j], multiply(-1, multiply(val, M[r][j])));
}
}
lead++;
}
return M;
}
/**
* Calculate the rank factorization of a matrix
*
* @param {Array[]} mat A matrix (M)
* @param {number} rows Number of rows
* @param {number} cols Number of columns
* @return {{C: Array, F: Array}} rank factorization where M = C F
* @private
*/
function _rankFact(mat, rows, cols) {
const rref = _rref(mat, rows, cols);
const C = mat.map((_, i) => _.filter((_, j) => j < rows && !_isZero(dot(rref[j], rref[j]))));
const F = rref.filter((_, i) => !_isZero(dot(rref[i], rref[i])));
return {
C,
F
};
}
function _isZero(x) {
return equal(add(x, Complex(1, 1)), add(0, Complex(1, 1)));
}
function _isZeros(arr) {
return deepEqual(add(arr, Complex(1, 1)), add(multiply(arr, 0), Complex(1, 1)));
}
});

188
node_modules/mathjs/lib/cjs/function/matrix/range.js generated vendored Normal file
View File

@@ -0,0 +1,188 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createRange = void 0;
var _factory = require("../../utils/factory.js");
var _noop = require("../../utils/noop.js");
const name = 'range';
const dependencies = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq', 'add', 'isPositive'];
const createRange = exports.createRange = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
config,
matrix,
bignumber,
smaller,
smallerEq,
larger,
largerEq,
add,
isPositive
} = _ref;
/**
* Create an array from a range.
* By default, the range end is excluded. This can be customized by providing
* an extra parameter `includeEnd`.
*
* Syntax:
*
* math.range(str [, includeEnd]) // Create a range from a string,
* // where the string contains the
* // start, optional step, and end,
* // separated by a colon.
* math.range(start, end [, includeEnd]) // Create a range with start and
* // end and a step size of 1.
* math.range(start, end, step [, includeEnd]) // Create a range with start, step,
* // and end.
*
* Where:
*
* - `str: string`
* A string 'start:end' or 'start:step:end'
* - `start: {number | BigNumber | Unit}`
* Start of the range
* - `end: number | BigNumber | Unit`
* End of the range, excluded by default, included when parameter includeEnd=true
* - `step: number | BigNumber | Unit`
* Step size. Default value is 1.
* - `includeEnd: boolean`
* Option to specify whether to include the end or not. False by default.
*
* Examples:
*
* math.range(2, 6) // [2, 3, 4, 5]
* math.range(2, -3, -1) // [2, 1, 0, -1, -2]
* math.range('2:1:6') // [2, 3, 4, 5]
* math.range(2, 6, true) // [2, 3, 4, 5, 6]
* math.range(math.unit(2, 'm'), math.unit(-3, 'm'), math.unit(-1, 'm')) // [2 m, 1 m, 0 m , -1 m, -2 m]
*
* See also:
*
* ones, zeros, size, subset
*
* @param {*} args Parameters describing the ranges `start`, `end`, and optional `step`.
* @return {Array | Matrix} range
*/
return typed(name, {
// TODO: simplify signatures when typed-function supports default values and optional arguments
// TODO: a number or boolean should not be converted to string here
string: _strRange,
'string, boolean': _strRange,
'number, number': function (start, end) {
return _out(_range(start, end, 1, false));
},
'number, number, number': function (start, end, step) {
return _out(_range(start, end, step, false));
},
'number, number, boolean': function (start, end, includeEnd) {
return _out(_range(start, end, 1, includeEnd));
},
'number, number, number, boolean': function (start, end, step, includeEnd) {
return _out(_range(start, end, step, includeEnd));
},
'BigNumber, BigNumber': function (start, end) {
const BigNumber = start.constructor;
return _out(_range(start, end, new BigNumber(1), false));
},
'BigNumber, BigNumber, BigNumber': function (start, end, step) {
return _out(_range(start, end, step, false));
},
'BigNumber, BigNumber, boolean': function (start, end, includeEnd) {
const BigNumber = start.constructor;
return _out(_range(start, end, new BigNumber(1), includeEnd));
},
'BigNumber, BigNumber, BigNumber, boolean': function (start, end, step, includeEnd) {
return _out(_range(start, end, step, includeEnd));
},
'Unit, Unit, Unit': function (start, end, step) {
return _out(_range(start, end, step, false));
},
'Unit, Unit, Unit, boolean': function (start, end, step, includeEnd) {
return _out(_range(start, end, step, includeEnd));
}
});
function _out(arr) {
if (config.matrix === 'Matrix') {
return matrix ? matrix(arr) : (0, _noop.noMatrix)();
}
return arr;
}
function _strRange(str, includeEnd) {
const r = _parse(str);
if (!r) {
throw new SyntaxError('String "' + str + '" is no valid range');
}
if (config.number === 'BigNumber') {
if (bignumber === undefined) {
(0, _noop.noBignumber)();
}
return _out(_range(bignumber(r.start), bignumber(r.end), bignumber(r.step)), includeEnd);
} else {
return _out(_range(r.start, r.end, r.step, includeEnd));
}
}
/**
* Create a range with numbers or BigNumbers
* @param {number | BigNumber | Unit} start
* @param {number | BigNumber | Unit} end
* @param {number | BigNumber | Unit} step
* @param {boolean} includeEnd
* @returns {Array} range
* @private
*/
function _range(start, end, step, includeEnd) {
const array = [];
const ongoing = isPositive(step) ? includeEnd ? smallerEq : smaller : includeEnd ? largerEq : larger;
let x = start;
while (ongoing(x, end)) {
array.push(x);
x = add(x, step);
}
return array;
}
/**
* Parse a string into a range,
* The string contains the start, optional step, and end, separated by a colon.
* If the string does not contain a valid range, null is returned.
* For example str='0:2:11'.
* @param {string} str
* @return {{start: number, end: number, step: number} | null} range Object containing properties start, end, step
* @private
*/
function _parse(str) {
const args = str.split(':');
// number
const nums = args.map(function (arg) {
// use Number and not parseFloat as Number returns NaN on invalid garbage in the string
return Number(arg);
});
const invalid = nums.some(function (num) {
return isNaN(num);
});
if (invalid) {
return null;
}
switch (nums.length) {
case 2:
return {
start: nums[0],
end: nums[1],
step: 1
};
case 3:
return {
start: nums[0],
end: nums[2],
step: nums[1]
};
default:
return null;
}
}
});

69
node_modules/mathjs/lib/cjs/function/matrix/reshape.js generated vendored Normal file
View File

@@ -0,0 +1,69 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createReshape = void 0;
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'reshape';
const dependencies = ['typed', 'isInteger', 'matrix'];
const createReshape = exports.createReshape = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
isInteger
} = _ref;
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3])
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4])
* // returns Array [[1, 2, 3, 4]]
*
* math.reshape([[1, 2], [3, 4]], [4])
* // returns Array [1, 2, 3, 4]
*
* const x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8])
* math.reshape(x, [2, 2, 2])
* // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
*
* math.reshape([1, 2, 3, 4], [-1, 2])
* // returns Matrix [[1, 2], [3, 4]]
*
* See also:
*
* size, squeeze, resize
*
* @param {Array | Matrix | *} x Matrix to be reshaped
* @param {number[]} sizes One dimensional array with integral sizes for
* each dimension. One -1 is allowed as wildcard,
* which calculates this dimension automatically.
*
* @return {* | Array | Matrix} A reshaped clone of matrix `x`
*
* @throws {TypeError} If `sizes` does not contain solely integers
* @throws {DimensionError} If the product of the new dimension sizes does
* not equal that of the old ones
*/
return typed(name, {
'Matrix, Array': function (x, sizes) {
return x.reshape(sizes, true);
},
'Array, Array': function (x, sizes) {
sizes.forEach(function (size) {
if (!isInteger(size)) {
throw new TypeError('Invalid size for dimension: ' + size);
}
});
return (0, _array.reshape)(x, sizes);
}
});
});

126
node_modules/mathjs/lib/cjs/function/matrix/resize.js generated vendored Normal file
View File

@@ -0,0 +1,126 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createResize = void 0;
var _is = require("../../utils/is.js");
var _DimensionError = require("../../error/DimensionError.js");
var _ArgumentsError = require("../../error/ArgumentsError.js");
var _number = require("../../utils/number.js");
var _string = require("../../utils/string.js");
var _object = require("../../utils/object.js");
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'resize';
const dependencies = ['config', 'matrix'];
const createResize = exports.createResize = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
config,
matrix
} = _ref;
/**
* Resize a matrix
*
* Syntax:
*
* math.resize(x, size)
* math.resize(x, size, defaultValue)
*
* Examples:
*
* math.resize([1, 2, 3, 4, 5], [3]) // returns Array [1, 2, 3]
* math.resize([1, 2, 3], [5], 0) // returns Array [1, 2, 3, 0, 0]
* math.resize(2, [2, 3], 0) // returns Matrix [[2, 0, 0], [0, 0, 0]]
* math.resize("hello", [8], "!") // returns string 'hello!!!'
*
* See also:
*
* size, squeeze, subset, reshape
*
* @param {Array | Matrix | *} x Matrix to be resized
* @param {Array | Matrix} size One dimensional array with numbers
* @param {number | string} [defaultValue=0] Zero by default, except in
* case of a string, in that case
* defaultValue = ' '
* @return {* | Array | Matrix} A resized clone of matrix `x`
*/
// TODO: rework resize to a typed-function
return function resize(x, size, defaultValue) {
if (arguments.length !== 2 && arguments.length !== 3) {
throw new _ArgumentsError.ArgumentsError('resize', arguments.length, 2, 3);
}
if ((0, _is.isMatrix)(size)) {
size = size.valueOf(); // get Array
}
if ((0, _is.isBigNumber)(size[0])) {
// convert bignumbers to numbers
size = size.map(function (value) {
return !(0, _is.isBigNumber)(value) ? value : value.toNumber();
});
}
// check x is a Matrix
if ((0, _is.isMatrix)(x)) {
// use optimized matrix implementation, return copy
return x.resize(size, defaultValue, true);
}
if (typeof x === 'string') {
// resize string
return _resizeString(x, size, defaultValue);
}
// check result should be a matrix
const asMatrix = Array.isArray(x) ? false : config.matrix !== 'Array';
if (size.length === 0) {
// output a scalar
while (Array.isArray(x)) {
x = x[0];
}
return (0, _object.clone)(x);
} else {
// output an array/matrix
if (!Array.isArray(x)) {
x = [x];
}
x = (0, _object.clone)(x);
const res = (0, _array.resize)(x, size, defaultValue);
return asMatrix ? matrix(res) : res;
}
};
/**
* Resize a string
* @param {string} str
* @param {number[]} size
* @param {string} [defaultChar=' ']
* @private
*/
function _resizeString(str, size, defaultChar) {
if (defaultChar !== undefined) {
if (typeof defaultChar !== 'string' || defaultChar.length !== 1) {
throw new TypeError('Single character expected as defaultValue');
}
} else {
defaultChar = ' ';
}
if (size.length !== 1) {
throw new _DimensionError.DimensionError(size.length, 1);
}
const len = size[0];
if (typeof len !== 'number' || !(0, _number.isInteger)(len)) {
throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + (0, _string.format)(size) + ')');
}
if (str.length > len) {
return str.substring(0, len);
} else if (str.length < len) {
let res = str;
for (let i = 0, ii = len - str.length; i < ii; i++) {
res += defaultChar;
}
return res;
} else {
return str;
}
}
});

77
node_modules/mathjs/lib/cjs/function/matrix/rotate.js generated vendored Normal file
View File

@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createRotate = void 0;
var _factory = require("../../utils/factory.js");
var _array = require("../../utils/array.js");
const name = 'rotate';
const dependencies = ['typed', 'multiply', 'rotationMatrix'];
const createRotate = exports.createRotate = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
multiply,
rotationMatrix
} = _ref;
/**
* Rotate a vector of size 1x2 counter-clockwise by a given angle
* Rotate a vector of size 1x3 counter-clockwise by a given angle around the given axis
*
* Syntax:
*
* math.rotate(w, theta)
* math.rotate(w, theta, v)
*
* Examples:
*
* math.rotate([11, 12], math.pi / 2) // returns [-12, 11]
* math.rotate(matrix([11, 12]), math.pi / 2) // returns [-12, 11]
*
* math.rotate([1, 0, 0], unit('90deg'), [0, 0, 1]) // returns [0, 1, 0]
* math.rotate(matrix([1, 0, 0]), unit('90deg'), [0, 0, 1]) // returns Matrix [0, 1, 0]
*
* math.rotate([1, 0], math.complex(1 + i)) // returns [cos(1 + i) - sin(1 + i), sin(1 + i) + cos(1 + i)]
*
* See also:
*
* matrix, rotationMatrix
*
* @param {Array | Matrix} w Vector to rotate
* @param {number | BigNumber | Complex | Unit} theta Rotation angle
* @param {Array | Matrix} [v] Rotation axis
* @return {Array | Matrix} Multiplication of the rotation matrix and w
*/
return typed(name, {
'Array , number | BigNumber | Complex | Unit': function (w, theta) {
_validateSize(w, 2);
const matrixRes = multiply(rotationMatrix(theta), w);
return matrixRes.toArray();
},
'Matrix , number | BigNumber | Complex | Unit': function (w, theta) {
_validateSize(w, 2);
return multiply(rotationMatrix(theta), w);
},
'Array, number | BigNumber | Complex | Unit, Array | Matrix': function (w, theta, v) {
_validateSize(w, 3);
const matrixRes = multiply(rotationMatrix(theta, v), w);
return matrixRes;
},
'Matrix, number | BigNumber | Complex | Unit, Array | Matrix': function (w, theta, v) {
_validateSize(w, 3);
return multiply(rotationMatrix(theta, v), w);
}
});
function _validateSize(v, expectedSize) {
const actualSize = Array.isArray(v) ? (0, _array.arraySize)(v) : v.size();
if (actualSize.length > 2) {
throw new RangeError(`Vector must be of dimensions 1x${expectedSize}`);
}
if (actualSize.length === 2 && actualSize[1] !== 1) {
throw new RangeError(`Vector must be of dimensions 1x${expectedSize}`);
}
if (actualSize[0] !== expectedSize) {
throw new RangeError(`Vector must be of dimensions 1x${expectedSize}`);
}
}
});

View File

@@ -0,0 +1,166 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createRotationMatrix = void 0;
var _is = require("../../utils/is.js");
var _factory = require("../../utils/factory.js");
const name = 'rotationMatrix';
const dependencies = ['typed', 'config', 'multiplyScalar', 'addScalar', 'unaryMinus', 'norm', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix', 'cos', 'sin'];
const createRotationMatrix = exports.createRotationMatrix = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
config,
multiplyScalar,
addScalar,
unaryMinus,
norm,
BigNumber,
matrix,
DenseMatrix,
SparseMatrix,
cos,
sin
} = _ref;
/**
* Create a 2-dimensional counter-clockwise rotation matrix (2x2) for a given angle (expressed in radians).
* Create a 2-dimensional counter-clockwise rotation matrix (3x3) by a given angle (expressed in radians) around a given axis (1x3).
*
* Syntax:
*
* math.rotationMatrix(theta)
* math.rotationMatrix(theta, format)
* math.rotationMatrix(theta, [v])
* math.rotationMatrix(theta, [v], format)
*
* Examples:
*
* math.rotationMatrix(math.pi / 2) // returns [[0, -1], [1, 0]]
* math.rotationMatrix(math.bignumber(1)) // returns [[bignumber(cos(1)), bignumber(-sin(1))], [bignumber(sin(1)), bignumber(cos(1))]]
* math.rotationMatrix(math.complex(1 + i)) // returns [[cos(1 + i), -sin(1 + i)], [sin(1 + i), cos(1 + i)]]
* math.rotationMatrix(math.unit('1rad')) // returns [[cos(1), -sin(1)], [sin(1), cos(1)]]
*
* math.rotationMatrix(math.pi / 2, [0, 1, 0]) // returns [[0, 0, 1], [0, 1, 0], [-1, 0, 0]]
* math.rotationMatrix(math.pi / 2, matrix([0, 1, 0])) // returns matrix([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])
*
*
* See also:
*
* matrix, cos, sin
*
*
* @param {number | BigNumber | Complex | Unit} theta Rotation angle
* @param {Array | Matrix} [v] Rotation axis
* @param {string} [format] Result Matrix storage format
* @return {Array | Matrix} Rotation matrix
*/
return typed(name, {
'': function () {
return config.matrix === 'Matrix' ? matrix([]) : [];
},
string: function (format) {
return matrix(format);
},
'number | BigNumber | Complex | Unit': function (theta) {
return _rotationMatrix2x2(theta, config.matrix === 'Matrix' ? 'dense' : undefined);
},
'number | BigNumber | Complex | Unit, string': function (theta, format) {
return _rotationMatrix2x2(theta, format);
},
'number | BigNumber | Complex | Unit, Array': function (theta, v) {
const matrixV = matrix(v);
_validateVector(matrixV);
return _rotationMatrix3x3(theta, matrixV, undefined);
},
'number | BigNumber | Complex | Unit, Matrix': function (theta, v) {
_validateVector(v);
const storageType = v.storage() || (config.matrix === 'Matrix' ? 'dense' : undefined);
return _rotationMatrix3x3(theta, v, storageType);
},
'number | BigNumber | Complex | Unit, Array, string': function (theta, v, format) {
const matrixV = matrix(v);
_validateVector(matrixV);
return _rotationMatrix3x3(theta, matrixV, format);
},
'number | BigNumber | Complex | Unit, Matrix, string': function (theta, v, format) {
_validateVector(v);
return _rotationMatrix3x3(theta, v, format);
}
});
/**
* Returns 2x2 matrix of 2D rotation of angle theta
*
* @param {number | BigNumber | Complex | Unit} theta The rotation angle
* @param {string} format The result Matrix storage format
* @returns {Matrix}
* @private
*/
function _rotationMatrix2x2(theta, format) {
const Big = (0, _is.isBigNumber)(theta);
const minusOne = Big ? new BigNumber(-1) : -1;
const cosTheta = cos(theta);
const sinTheta = sin(theta);
const data = [[cosTheta, multiplyScalar(minusOne, sinTheta)], [sinTheta, cosTheta]];
return _convertToFormat(data, format);
}
function _validateVector(v) {
const size = v.size();
if (size.length < 1 || size[0] !== 3) {
throw new RangeError('Vector must be of dimensions 1x3');
}
}
function _mul(array) {
return array.reduce((p, curr) => multiplyScalar(p, curr));
}
function _convertToFormat(data, format) {
if (format) {
if (format === 'sparse') {
return new SparseMatrix(data);
}
if (format === 'dense') {
return new DenseMatrix(data);
}
throw new TypeError(`Unknown matrix type "${format}"`);
}
return data;
}
/**
* Returns a 3x3 matrix of rotation of angle theta around vector v
*
* @param {number | BigNumber | Complex | Unit} theta The rotation angle
* @param {Matrix} v The rotation axis vector
* @param {string} format The storage format of the resulting matrix
* @returns {Matrix}
* @private
*/
function _rotationMatrix3x3(theta, v, format) {
const normV = norm(v);
if (normV === 0) {
throw new RangeError('Rotation around zero vector');
}
const Big = (0, _is.isBigNumber)(theta) ? BigNumber : null;
const one = Big ? new Big(1) : 1;
const minusOne = Big ? new Big(-1) : -1;
const vx = Big ? new Big(v.get([0]) / normV) : v.get([0]) / normV;
const vy = Big ? new Big(v.get([1]) / normV) : v.get([1]) / normV;
const vz = Big ? new Big(v.get([2]) / normV) : v.get([2]) / normV;
const c = cos(theta);
const oneMinusC = addScalar(one, unaryMinus(c));
const s = sin(theta);
const r11 = addScalar(c, _mul([vx, vx, oneMinusC]));
const r12 = addScalar(_mul([vx, vy, oneMinusC]), _mul([minusOne, vz, s]));
const r13 = addScalar(_mul([vx, vz, oneMinusC]), _mul([vy, s]));
const r21 = addScalar(_mul([vx, vy, oneMinusC]), _mul([vz, s]));
const r22 = addScalar(c, _mul([vy, vy, oneMinusC]));
const r23 = addScalar(_mul([vy, vz, oneMinusC]), _mul([minusOne, vx, s]));
const r31 = addScalar(_mul([vx, vz, oneMinusC]), _mul([minusOne, vy, s]));
const r32 = addScalar(_mul([vy, vz, oneMinusC]), _mul([vx, s]));
const r33 = addScalar(c, _mul([vz, vz, oneMinusC]));
const data = [[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]];
return _convertToFormat(data, format);
}
});

65
node_modules/mathjs/lib/cjs/function/matrix/row.js generated vendored Normal file
View File

@@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createRow = void 0;
var _factory = require("../../utils/factory.js");
var _is = require("../../utils/is.js");
var _object = require("../../utils/object.js");
var _array = require("../../utils/array.js");
const name = 'row';
const dependencies = ['typed', 'Index', 'matrix', 'range'];
const createRow = exports.createRow = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
Index,
matrix,
range
} = _ref;
/**
* Return a row from a Matrix.
*
* Syntax:
*
* math.row(value, index)
*
* Example:
*
* // get a row
* const d = [[1, 2], [3, 4]]
* math.row(d, 1) // returns [[3, 4]]
*
* See also:
*
* column
*
* @param {Array | Matrix } value An array or matrix
* @param {number} row The index of the row
* @return {Array | Matrix} The retrieved row
*/
return typed(name, {
'Matrix, number': _row,
'Array, number': function (value, row) {
return _row(matrix((0, _object.clone)(value)), row).valueOf();
}
});
/**
* Retrieve a row of a matrix
* @param {Matrix } value A matrix
* @param {number} row The index of the row
* @return {Matrix} The retrieved row
*/
function _row(value, row) {
// check dimensions
if (value.size().length !== 2) {
throw new Error('Only two dimensional matrix is supported');
}
(0, _array.validateIndex)(row, value.size()[0]);
const columnRange = range(0, value.size()[1]);
const index = new Index(row, columnRange);
const result = value.subset(index);
return (0, _is.isMatrix)(result) ? result : matrix([[result]]);
}
});

54
node_modules/mathjs/lib/cjs/function/matrix/size.js generated vendored Normal file
View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createSize = void 0;
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
var _noop = require("../../utils/noop.js");
const name = 'size';
const dependencies = ['typed', 'config', '?matrix'];
const createSize = exports.createSize = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
config,
matrix
} = _ref;
/**
* Calculate the size of a matrix or scalar.
*
* Syntax:
*
* math.size(x)
*
* Examples:
*
* math.size(2.3) // returns []
* math.size('hello world') // returns [11]
*
* const A = [[1, 2, 3], [4, 5, 6]]
* math.size(A) // returns [2, 3]
* math.size(math.range(1,6).toArray()) // returns [5]
*
* See also:
*
* count, resize, squeeze, subset
*
* @param {boolean | number | Complex | Unit | string | Array | Matrix} x A matrix
* @return {Array | Matrix} A vector with size of `x`.
*/
return typed(name, {
Matrix: function (x) {
return x.create(x.size(), 'number');
},
Array: _array.arraySize,
string: function (x) {
return config.matrix === 'Array' ? [x.length] : matrix([x.length], 'dense', 'number');
},
'number | Complex | BigNumber | Unit | boolean | null': function (x) {
// scalar
return config.matrix === 'Array' ? [] : matrix ? matrix([], 'dense', 'number') : (0, _noop.noMatrix)();
}
});
});

119
node_modules/mathjs/lib/cjs/function/matrix/sort.js generated vendored Normal file
View File

@@ -0,0 +1,119 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createSort = void 0;
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'sort';
const dependencies = ['typed', 'matrix', 'compare', 'compareNatural'];
const createSort = exports.createSort = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
compare,
compareNatural
} = _ref;
const compareAsc = compare;
const compareDesc = (a, b) => -compare(a, b);
/**
* Sort the items in a matrix.
*
* Syntax:
*
* math.sort(x)
* math.sort(x, compare)
*
* Examples:
*
* math.sort([5, 10, 1]) // returns [1, 5, 10]
* math.sort(['C', 'B', 'A', 'D'], math.compareNatural)
* // returns ['A', 'B', 'C', 'D']
*
* function sortByLength (a, b) {
* return a.length - b.length
* }
* math.sort(['Langdon', 'Tom', 'Sara'], sortByLength)
* // returns ['Tom', 'Sara', 'Langdon']
*
* See also:
*
* filter, forEach, map, compare, compareNatural
*
* @param {Matrix | Array} x A one dimensional matrix or array to sort
* @param {Function | 'asc' | 'desc' | 'natural'} [compare='asc']
* An optional _comparator function or name. The function is called as
* `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
* and 0 when a == b.
* @return {Matrix | Array} Returns the sorted matrix.
*/
return typed(name, {
Array: function (x) {
_arrayIsVector(x);
return x.sort(compareAsc);
},
Matrix: function (x) {
_matrixIsVector(x);
return matrix(x.toArray().sort(compareAsc), x.storage());
},
'Array, function': function (x, _comparator) {
_arrayIsVector(x);
return x.sort(_comparator);
},
'Matrix, function': function (x, _comparator) {
_matrixIsVector(x);
return matrix(x.toArray().sort(_comparator), x.storage());
},
'Array, string': function (x, order) {
_arrayIsVector(x);
return x.sort(_comparator(order));
},
'Matrix, string': function (x, order) {
_matrixIsVector(x);
return matrix(x.toArray().sort(_comparator(order)), x.storage());
}
});
/**
* Get the comparator for given order ('asc', 'desc', 'natural')
* @param {'asc' | 'desc' | 'natural'} order
* @return {Function} Returns a _comparator function
*/
function _comparator(order) {
if (order === 'asc') {
return compareAsc;
} else if (order === 'desc') {
return compareDesc;
} else if (order === 'natural') {
return compareNatural;
} else {
throw new Error('String "asc", "desc", or "natural" expected');
}
}
/**
* Validate whether an array is one dimensional
* Throws an error when this is not the case
* @param {Array} array
* @private
*/
function _arrayIsVector(array) {
if ((0, _array.arraySize)(array).length !== 1) {
throw new Error('One dimensional array expected');
}
}
/**
* Validate whether a matrix is one dimensional
* Throws an error when this is not the case
* @param {Matrix} matrix
* @private
*/
function _matrixIsVector(matrix) {
if (matrix.size().length !== 1) {
throw new Error('One dimensional matrix expected');
}
}
});

105
node_modules/mathjs/lib/cjs/function/matrix/sqrtm.js generated vendored Normal file
View File

@@ -0,0 +1,105 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createSqrtm = void 0;
var _is = require("../../utils/is.js");
var _string = require("../../utils/string.js");
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'sqrtm';
const dependencies = ['typed', 'abs', 'add', 'multiply', 'map', 'sqrt', 'subtract', 'inv', 'size', 'max', 'identity'];
const createSqrtm = exports.createSqrtm = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
abs,
add,
multiply,
map,
sqrt,
subtract,
inv,
size,
max,
identity
} = _ref;
const _maxIterations = 1e3;
const _tolerance = 1e-6;
/**
* Calculate the principal square root matrix using the DenmanBeavers iterative method
*
* https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_DenmanBeavers_iteration
*
* @param {Array | Matrix} A The square matrix `A`
* @return {Array | Matrix} The principal square root of matrix `A`
* @private
*/
function _denmanBeavers(A) {
let error;
let iterations = 0;
let Y = A;
let Z = identity(size(A));
do {
const Yk = Y;
Y = multiply(0.5, add(Yk, inv(Z)));
Z = multiply(0.5, add(Z, inv(Yk)));
error = max(abs(subtract(Y, Yk)));
if (error > _tolerance && ++iterations > _maxIterations) {
throw new Error('computing square root of matrix: iterative method could not converge');
}
} while (error > _tolerance);
return Y;
}
/**
* Calculate the principal square root of a square matrix.
* The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.
*
* https://en.wikipedia.org/wiki/Square_root_of_a_matrix
*
* Syntax:
*
* math.sqrtm(A)
*
* Examples:
*
* math.sqrtm([[33, 24], [48, 57]]) // returns [[5, 2], [4, 7]]
*
* See also:
*
* sqrt, pow
*
* @param {Array | Matrix} A The square matrix `A`
* @return {Array | Matrix} The principal square root of matrix `A`
*/
return typed(name, {
'Array | Matrix': function (A) {
const size = (0, _is.isMatrix)(A) ? A.size() : (0, _array.arraySize)(A);
switch (size.length) {
case 1:
// Single element Array | Matrix
if (size[0] === 1) {
return map(A, sqrt);
} else {
throw new RangeError('Matrix must be square ' + '(size: ' + (0, _string.format)(size) + ')');
}
case 2:
{
// Two-dimensional Array | Matrix
const rows = size[0];
const cols = size[1];
if (rows === cols) {
return _denmanBeavers(A);
} else {
throw new RangeError('Matrix must be square ' + '(size: ' + (0, _string.format)(size) + ')');
}
}
default:
// Multi dimensional array
throw new RangeError('Matrix must be at most two dimensional ' + '(size: ' + (0, _string.format)(size) + ')');
}
}
});
});

59
node_modules/mathjs/lib/cjs/function/matrix/squeeze.js generated vendored Normal file
View File

@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createSqueeze = void 0;
var _object = require("../../utils/object.js");
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'squeeze';
const dependencies = ['typed'];
const createSqueeze = exports.createSqueeze = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed
} = _ref;
/**
* Squeeze a matrix, remove inner and outer singleton dimensions from a matrix.
*
* Syntax:
*
* math.squeeze(x)
*
* Examples:
*
* math.squeeze([3]) // returns 3
* math.squeeze([[3]]) // returns 3
*
* const A = math.zeros(3, 1) // returns [[0], [0], [0]] (size 3x1)
* math.squeeze(A) // returns [0, 0, 0] (size 3)
*
* const B = math.zeros(1, 3) // returns [[0, 0, 0]] (size 1x3)
* math.squeeze(B) // returns [0, 0, 0] (size 3)
*
* // only inner and outer dimensions are removed
* const C = math.zeros(2, 1, 3) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
* math.squeeze(C) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
*
* See also:
*
* subset
*
* @param {Matrix | Array} x Matrix to be squeezed
* @return {Matrix | Array} Squeezed matrix
*/
return typed(name, {
Array: function (x) {
return (0, _array.squeeze)((0, _object.clone)(x));
},
Matrix: function (x) {
const res = (0, _array.squeeze)(x.toArray());
// FIXME: return the same type of matrix as the input
return Array.isArray(res) ? x.create(res, x.datatype()) : res;
},
any: function (x) {
// scalar
return (0, _object.clone)(x);
}
});
});

279
node_modules/mathjs/lib/cjs/function/matrix/subset.js generated vendored Normal file
View File

@@ -0,0 +1,279 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createSubset = void 0;
var _is = require("../../utils/is.js");
var _object = require("../../utils/object.js");
var _array = require("../../utils/array.js");
var _customs = require("../../utils/customs.js");
var _DimensionError = require("../../error/DimensionError.js");
var _factory = require("../../utils/factory.js");
const name = 'subset';
const dependencies = ['typed', 'matrix', 'zeros', 'add'];
const createSubset = exports.createSubset = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
zeros,
add
} = _ref;
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* const d = [[1, 2], [3, 4]]
* math.subset(d, math.index(1, 0)) // returns 3
* math.subset(d, math.index([0, 1], 1)) // returns [[2], [4]]
* math.subset(d, math.index([false, true], 0)) // returns [[3]]
*
* // replace a subset
* const e = []
* const f = math.subset(e, math.index(0, [0, 2]), [5, 6]) // f = [[5, 0, 6]]
* const g = math.subset(f, math.index(1, 1), 7, 0) // g = [[5, 0, 6], [0, 7, 0]]
* math.subset(g, math.index([false, true], 1), 8) // returns [[5, 0, 6], [0, 8, 0]]
*
* // get submatrix using ranges
* const M = [
* [1,2,3],
* [4,5,6],
* [7,8,9]
* ]
* math.subset(M, math.index(math.range(0,2), math.range(0,3))) // [[1, 2, 3], [4, 5, 6]]
*
* See also:
*
* size, resize, squeeze, index
*
* @param {Array | Matrix | string} matrix An array, matrix, or string
* @param {Index} index
* For each dimension of the target, specifies an index or a list of
* indices to fetch or set. `subset` uses the cartesian product of
* the indices specified in each dimension.
* @param {*} [replacement] An array, matrix, or scalar.
* If provided, the subset is replaced with replacement.
* If not provided, the subset is returned
* @param {*} [defaultValue=undefined] Default value, filled in on new entries when
* the matrix is resized. If not provided,
* math.matrix elements will be left undefined.
* @return {Array | Matrix | string} Either the retrieved subset or the updated matrix.
*/
return typed(name, {
// get subset
'Matrix, Index': function (value, index) {
if ((0, _array.isEmptyIndex)(index)) {
return matrix();
}
(0, _array.validateIndexSourceSize)(value, index);
return value.subset(index);
},
'Array, Index': typed.referTo('Matrix, Index', function (subsetRef) {
return function (value, index) {
const subsetResult = subsetRef(matrix(value), index);
return index.isScalar() ? subsetResult : subsetResult.valueOf();
};
}),
'Object, Index': _getObjectProperty,
'string, Index': _getSubstring,
// set subset
'Matrix, Index, any, any': function (value, index, replacement, defaultValue) {
if ((0, _array.isEmptyIndex)(index)) {
return value;
}
(0, _array.validateIndexSourceSize)(value, index);
return value.clone().subset(index, _broadcastReplacement(replacement, index), defaultValue);
},
'Array, Index, any, any': typed.referTo('Matrix, Index, any, any', function (subsetRef) {
return function (value, index, replacement, defaultValue) {
const subsetResult = subsetRef(matrix(value), index, replacement, defaultValue);
return subsetResult.isMatrix ? subsetResult.valueOf() : subsetResult;
};
}),
'Array, Index, any': typed.referTo('Matrix, Index, any, any', function (subsetRef) {
return function (value, index, replacement) {
return subsetRef(matrix(value), index, replacement, undefined).valueOf();
};
}),
'Matrix, Index, any': typed.referTo('Matrix, Index, any, any', function (subsetRef) {
return function (value, index, replacement) {
return subsetRef(value, index, replacement, undefined);
};
}),
'string, Index, string': _setSubstring,
'string, Index, string, string': _setSubstring,
'Object, Index, any': _setObjectProperty
});
/**
* Broadcasts a replacment value to be the same size as index
* @param {number | BigNumber | Array | Matrix} replacement Replacement value to try to broadcast
* @param {*} index Index value
* @returns broadcasted replacement that matches the size of index
*/
function _broadcastReplacement(replacement, index) {
if (typeof replacement === 'string') {
throw new Error('can\'t boradcast a string');
}
if (index._isScalar) {
return replacement;
}
const indexSize = index.size();
if (indexSize.every(d => d > 0)) {
try {
return add(replacement, zeros(indexSize));
} catch (error) {
return replacement;
}
} else {
return replacement;
}
}
});
/**
* Retrieve a subset of a string
* @param {string} str string from which to get a substring
* @param {Index} index An index or list of indices (character positions)
* @returns {string} substring
* @private
*/
function _getSubstring(str, index) {
if (!(0, _is.isIndex)(index)) {
// TODO: better error message
throw new TypeError('Index expected');
}
if ((0, _array.isEmptyIndex)(index)) {
return '';
}
(0, _array.validateIndexSourceSize)(Array.from(str), index);
if (index.size().length !== 1) {
throw new _DimensionError.DimensionError(index.size().length, 1);
}
// validate whether the range is out of range
const strLen = str.length;
(0, _array.validateIndex)(index.min()[0], strLen);
(0, _array.validateIndex)(index.max()[0], strLen);
const range = index.dimension(0);
let substr = '';
range.forEach(function (v) {
substr += str.charAt(v);
});
return substr;
}
/**
* Replace a substring in a string
* @param {string} str string to be replaced
* @param {Index} index An index or list of indices (character positions)
* @param {string} replacement Replacement string
* @param {string} [defaultValue] Default value to be used when resizing
* the string. is ' ' by default
* @returns {string} result
* @private
*/
function _setSubstring(str, index, replacement, defaultValue) {
if (!index || index.isIndex !== true) {
// TODO: better error message
throw new TypeError('Index expected');
}
if ((0, _array.isEmptyIndex)(index)) {
return str;
}
(0, _array.validateIndexSourceSize)(Array.from(str), index);
if (index.size().length !== 1) {
throw new _DimensionError.DimensionError(index.size().length, 1);
}
if (defaultValue !== undefined) {
if (typeof defaultValue !== 'string' || defaultValue.length !== 1) {
throw new TypeError('Single character expected as defaultValue');
}
} else {
defaultValue = ' ';
}
const range = index.dimension(0);
const len = range.size()[0];
if (len !== replacement.length) {
throw new _DimensionError.DimensionError(range.size()[0], replacement.length);
}
// validate whether the range is out of range
const strLen = str.length;
(0, _array.validateIndex)(index.min()[0]);
(0, _array.validateIndex)(index.max()[0]);
// copy the string into an array with characters
const chars = [];
for (let i = 0; i < strLen; i++) {
chars[i] = str.charAt(i);
}
range.forEach(function (v, i) {
chars[v] = replacement.charAt(i[0]);
});
// initialize undefined characters with a space
if (chars.length > strLen) {
for (let i = strLen - 1, len = chars.length; i < len; i++) {
if (!chars[i]) {
chars[i] = defaultValue;
}
}
}
return chars.join('');
}
/**
* Retrieve a property from an object
* @param {Object} object
* @param {Index} index
* @return {*} Returns the value of the property
* @private
*/
function _getObjectProperty(object, index) {
if ((0, _array.isEmptyIndex)(index)) {
return undefined;
}
if (index.size().length !== 1) {
throw new _DimensionError.DimensionError(index.size(), 1);
}
const key = index.dimension(0);
if (typeof key !== 'string') {
throw new TypeError('String expected as index to retrieve an object property');
}
return (0, _customs.getSafeProperty)(object, key);
}
/**
* Set a property on an object
* @param {Object} object
* @param {Index} index
* @param {*} replacement
* @return {*} Returns the updated object
* @private
*/
function _setObjectProperty(object, index, replacement) {
if ((0, _array.isEmptyIndex)(index)) {
return object;
}
if (index.size().length !== 1) {
throw new _DimensionError.DimensionError(index.size(), 1);
}
const key = index.dimension(0);
if (typeof key !== 'string') {
throw new TypeError('String expected as index to retrieve an object property');
}
// clone the object, and apply the property to the clone
const updated = (0, _object.clone)(object);
(0, _customs.setSafeProperty)(updated, key, replacement);
return updated;
}

134
node_modules/mathjs/lib/cjs/function/matrix/trace.js generated vendored Normal file
View File

@@ -0,0 +1,134 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createTrace = void 0;
var _object = require("../../utils/object.js");
var _string = require("../../utils/string.js");
var _factory = require("../../utils/factory.js");
const name = 'trace';
const dependencies = ['typed', 'matrix', 'add'];
const createTrace = exports.createTrace = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix,
add
} = _ref;
/**
* Calculate the trace of a matrix: the sum of the elements on the main
* diagonal of a square matrix.
*
* Syntax:
*
* math.trace(x)
*
* Examples:
*
* math.trace([[1, 2], [3, 4]]) // returns 5
*
* const A = [
* [1, 2, 3],
* [-1, 2, 3],
* [2, 0, 3]
* ]
* math.trace(A) // returns 6
*
* See also:
*
* diag
*
* @param {Array | Matrix} x A matrix
*
* @return {number} The trace of `x`
*/
return typed('trace', {
Array: function _arrayTrace(x) {
// use dense matrix implementation
return _denseTrace(matrix(x));
},
SparseMatrix: _sparseTrace,
DenseMatrix: _denseTrace,
any: _object.clone
});
function _denseTrace(m) {
// matrix size & data
const size = m._size;
const data = m._data;
// process dimensions
switch (size.length) {
case 1:
// vector
if (size[0] === 1) {
// return data[0]
return (0, _object.clone)(data[0]);
}
throw new RangeError('Matrix must be square (size: ' + (0, _string.format)(size) + ')');
case 2:
{
// two dimensional
const rows = size[0];
const cols = size[1];
if (rows === cols) {
// calulate sum
let sum = 0;
// loop diagonal
for (let i = 0; i < rows; i++) {
sum = add(sum, data[i][i]);
}
// return trace
return sum;
} else {
throw new RangeError('Matrix must be square (size: ' + (0, _string.format)(size) + ')');
}
}
default:
// multi dimensional
throw new RangeError('Matrix must be two dimensional (size: ' + (0, _string.format)(size) + ')');
}
}
function _sparseTrace(m) {
// matrix arrays
const values = m._values;
const index = m._index;
const ptr = m._ptr;
const size = m._size;
// check dimensions
const rows = size[0];
const columns = size[1];
// matrix must be square
if (rows === columns) {
// calulate sum
let sum = 0;
// check we have data (avoid looping columns)
if (values.length > 0) {
// loop columns
for (let j = 0; j < columns; j++) {
// k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
const k0 = ptr[j];
const k1 = ptr[j + 1];
// loop k within [k0, k1[
for (let k = k0; k < k1; k++) {
// row index
const i = index[k];
// check row
if (i === j) {
// accumulate value
sum = add(sum, values[k]);
// exit loop
break;
}
if (i > j) {
// exit loop, no value on the diagonal for column j
break;
}
}
}
}
// return trace
return sum;
}
throw new RangeError('Matrix must be square (size: ' + (0, _string.format)(size) + ')');
}
});

View File

@@ -0,0 +1,166 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createTranspose = void 0;
var _object = require("../../utils/object.js");
var _string = require("../../utils/string.js");
var _factory = require("../../utils/factory.js");
const name = 'transpose';
const dependencies = ['typed', 'matrix'];
const createTranspose = exports.createTranspose = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
matrix
} = _ref;
/**
* Transpose a matrix. All values of the matrix are reflected over its
* main diagonal. Only applicable to two dimensional matrices containing
* a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
* vectors and scalars return the input unchanged.
*
* Syntax:
*
* math.transpose(x)
*
* Examples:
*
* const A = [[1, 2, 3], [4, 5, 6]]
* math.transpose(A) // returns [[1, 4], [2, 5], [3, 6]]
*
* See also:
*
* diag, inv, subset, squeeze
*
* @param {Array | Matrix} x Matrix to be transposed
* @return {Array | Matrix} The transposed matrix
*/
return typed(name, {
Array: x => transposeMatrix(matrix(x)).valueOf(),
Matrix: transposeMatrix,
any: _object.clone // scalars
});
function transposeMatrix(x) {
// matrix size
const size = x.size();
// result
let c;
// process dimensions
switch (size.length) {
case 1:
// vector
c = x.clone();
break;
case 2:
{
// rows and columns
const rows = size[0];
const columns = size[1];
// check columns
if (columns === 0) {
// throw exception
throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + (0, _string.format)(size) + ')');
}
// process storage format
switch (x.storage()) {
case 'dense':
c = _denseTranspose(x, rows, columns);
break;
case 'sparse':
c = _sparseTranspose(x, rows, columns);
break;
}
}
break;
default:
// multi dimensional
throw new RangeError('Matrix must be a vector or two dimensional (size: ' + (0, _string.format)(size) + ')');
}
return c;
}
function _denseTranspose(m, rows, columns) {
// matrix array
const data = m._data;
// transposed matrix data
const transposed = [];
let transposedRow;
// loop columns
for (let j = 0; j < columns; j++) {
// initialize row
transposedRow = transposed[j] = [];
// loop rows
for (let i = 0; i < rows; i++) {
// set data
transposedRow[i] = (0, _object.clone)(data[i][j]);
}
}
// return matrix
return m.createDenseMatrix({
data: transposed,
size: [columns, rows],
datatype: m._datatype
});
}
function _sparseTranspose(m, rows, columns) {
// matrix arrays
const values = m._values;
const index = m._index;
const ptr = m._ptr;
// result matrices
const cvalues = values ? [] : undefined;
const cindex = [];
const cptr = [];
// row counts
const w = [];
for (let x = 0; x < rows; x++) {
w[x] = 0;
}
// vars
let p, l, j;
// loop values in matrix
for (p = 0, l = index.length; p < l; p++) {
// number of values in row
w[index[p]]++;
}
// cumulative sum
let sum = 0;
// initialize cptr with the cummulative sum of row counts
for (let i = 0; i < rows; i++) {
// update cptr
cptr.push(sum);
// update sum
sum += w[i];
// update w
w[i] = cptr[i];
}
// update cptr
cptr.push(sum);
// loop columns
for (j = 0; j < columns; j++) {
// values & index in column
for (let k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
// C values & index
const q = w[index[k]]++;
// C[j, i] = A[i, j]
cindex[q] = j;
// check we need to process values (pattern matrix)
if (values) {
cvalues[q] = (0, _object.clone)(values[k]);
}
}
}
// return matrix
return m.createSparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [columns, rows],
datatype: m._datatype
});
}
});

129
node_modules/mathjs/lib/cjs/function/matrix/zeros.js generated vendored Normal file
View File

@@ -0,0 +1,129 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createZeros = void 0;
var _is = require("../../utils/is.js");
var _number = require("../../utils/number.js");
var _array = require("../../utils/array.js");
var _factory = require("../../utils/factory.js");
const name = 'zeros';
const dependencies = ['typed', 'config', 'matrix', 'BigNumber'];
const createZeros = exports.createZeros = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
let {
typed,
config,
matrix,
BigNumber
} = _ref;
/**
* Create a matrix filled with zeros. The created matrix can have one or
* multiple dimensions.
*
* Syntax:
*
* math.zeros(m)
* math.zeros(m, format)
* math.zeros(m, n)
* math.zeros(m, n, format)
* math.zeros([m, n])
* math.zeros([m, n], format)
*
* Examples:
*
* math.zeros() // returns []
* math.zeros(3) // returns [0, 0, 0]
* math.zeros(3, 2) // returns [[0, 0], [0, 0], [0, 0]]
* math.zeros(3, 'dense') // returns [0, 0, 0]
*
* const A = [[1, 2, 3], [4, 5, 6]]
* math.zeros(math.size(A)) // returns [[0, 0, 0], [0, 0, 0]]
*
* See also:
*
* ones, identity, size, range
*
* @param {...(number|BigNumber) | Array} size The size of each dimension of the matrix
* @param {string} [format] The Matrix storage format
*
* @return {Array | Matrix} A matrix filled with zeros
*/
return typed(name, {
'': function () {
return config.matrix === 'Array' ? _zeros([]) : _zeros([], 'default');
},
// math.zeros(m, n, p, ..., format)
// TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
'...number | BigNumber | string': function (size) {
const last = size[size.length - 1];
if (typeof last === 'string') {
const format = size.pop();
return _zeros(size, format);
} else if (config.matrix === 'Array') {
return _zeros(size);
} else {
return _zeros(size, 'default');
}
},
Array: _zeros,
Matrix: function (size) {
const format = size.storage();
return _zeros(size.valueOf(), format);
},
'Array | Matrix, string': function (size, format) {
return _zeros(size.valueOf(), format);
}
});
/**
* Create an Array or Matrix with zeros
* @param {Array} size
* @param {string} [format='default']
* @return {Array | Matrix}
* @private
*/
function _zeros(size, format) {
const hasBigNumbers = _normalize(size);
const defaultValue = hasBigNumbers ? new BigNumber(0) : 0;
_validate(size);
if (format) {
// return a matrix
const m = matrix(format);
if (size.length > 0) {
return m.resize(size, defaultValue);
}
return m;
} else {
// return an Array
const arr = [];
if (size.length > 0) {
return (0, _array.resize)(arr, size, defaultValue);
}
return arr;
}
}
// replace BigNumbers with numbers, returns true if size contained BigNumbers
function _normalize(size) {
let hasBigNumbers = false;
size.forEach(function (value, index, arr) {
if ((0, _is.isBigNumber)(value)) {
hasBigNumbers = true;
arr[index] = value.toNumber();
}
});
return hasBigNumbers;
}
// validate arguments
function _validate(size) {
size.forEach(function (value) {
if (typeof value !== 'number' || !(0, _number.isInteger)(value) || value < 0) {
throw new Error('Parameters in function zeros must be positive integers');
}
});
}
});
// TODO: zeros contains almost the same code as ones. Reuse this?