feat:node-modules
This commit is contained in:
111
node_modules/mathjs/lib/esm/function/matrix/apply.js
generated
vendored
Normal file
111
node_modules/mathjs/lib/esm/function/matrix/apply.js
generated
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { arraySize } from '../../utils/array.js';
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
import { IndexError } from '../../error/IndexError.js';
|
||||
var name = 'apply';
|
||||
var dependencies = ['typed', 'isInteger'];
|
||||
export var createApply = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array__Matrix_number__BigNumber_function(mat, dim, callback) {
|
||||
if (!isInteger(dim)) {
|
||||
throw new TypeError('Integer number expected for dimension');
|
||||
}
|
||||
var size = Array.isArray(mat) ? arraySize(mat) : mat.size();
|
||||
if (dim < 0 || dim >= size.length) {
|
||||
throw new IndexError(dim, size.length);
|
||||
}
|
||||
if (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) {
|
||||
var 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) {
|
||||
var I = mat.length;
|
||||
var J = mat[0].length;
|
||||
var i, j;
|
||||
var ret = [];
|
||||
for (j = 0; j < J; j++) {
|
||||
var tmp = [];
|
||||
for (i = 0; i < I; i++) {
|
||||
tmp.push(mat[i][j]);
|
||||
}
|
||||
ret.push(tmp);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
59
node_modules/mathjs/lib/esm/function/matrix/column.js
generated
vendored
Normal file
59
node_modules/mathjs/lib/esm/function/matrix/column.js
generated
vendored
Normal file
@@ -0,0 +1,59 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
import { clone } from '../../utils/object.js';
|
||||
import { validateIndex } from '../../utils/array.js';
|
||||
var name = 'column';
|
||||
var dependencies = ['typed', 'Index', 'matrix', 'range'];
|
||||
export var createColumn = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array_number(value, column) {
|
||||
return _column(matrix(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');
|
||||
}
|
||||
validateIndex(column, value.size()[1]);
|
||||
var rowRange = range(0, value.size()[0]);
|
||||
var index = new Index(rowRange, column);
|
||||
var result = value.subset(index);
|
||||
return isMatrix(result) ? result : matrix([[result]]);
|
||||
}
|
||||
});
|
||||
104
node_modules/mathjs/lib/esm/function/matrix/concat.js
generated
vendored
Normal file
104
node_modules/mathjs/lib/esm/function/matrix/concat.js
generated
vendored
Normal file
@@ -0,0 +1,104 @@
|
||||
import { isBigNumber, isMatrix, isNumber } from '../../utils/is.js';
|
||||
import { clone } from '../../utils/object.js';
|
||||
import { arraySize, concat as _concat } from '../../utils/array.js';
|
||||
import { IndexError } from '../../error/IndexError.js';
|
||||
import { DimensionError } from '../../error/DimensionError.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'concat';
|
||||
var dependencies = ['typed', 'matrix', 'isInteger'];
|
||||
export var createConcat = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array__Matrix__number__BigNumber(args) {
|
||||
var i;
|
||||
var len = args.length;
|
||||
var dim = -1; // zero-based dimension
|
||||
var prevDim;
|
||||
var asMatrix = false;
|
||||
var matrices = []; // contains multi dimensional arrays
|
||||
|
||||
for (i = 0; i < len; i++) {
|
||||
var arg = args[i];
|
||||
|
||||
// test whether we need to return a Matrix (if not we return an Array)
|
||||
if (isMatrix(arg)) {
|
||||
asMatrix = true;
|
||||
}
|
||||
if (isNumber(arg) || 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(dim, prevDim + 1);
|
||||
}
|
||||
} else {
|
||||
// this is a matrix or array
|
||||
var m = clone(arg).valueOf();
|
||||
var size = 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(prevDim + 1, dim + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (matrices.length === 0) {
|
||||
throw new SyntaxError('At least one matrix expected');
|
||||
}
|
||||
var res = matrices.shift();
|
||||
while (matrices.length) {
|
||||
res = _concat(res, matrices.shift(), dim);
|
||||
}
|
||||
return asMatrix ? matrix(res) : res;
|
||||
},
|
||||
'...string': function string(args) {
|
||||
return args.join('');
|
||||
}
|
||||
});
|
||||
});
|
||||
39
node_modules/mathjs/lib/esm/function/matrix/count.js
generated
vendored
Normal file
39
node_modules/mathjs/lib/esm/function/matrix/count.js
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'count';
|
||||
var dependencies = ['typed', 'size', 'prod'];
|
||||
export var createCount = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 string(x) {
|
||||
return x.length;
|
||||
},
|
||||
'Matrix | Array': function Matrix__Array(x) {
|
||||
return prod(size(x));
|
||||
}
|
||||
});
|
||||
});
|
||||
81
node_modules/mathjs/lib/esm/function/matrix/cross.js
generated
vendored
Normal file
81
node_modules/mathjs/lib/esm/function/matrix/cross.js
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
import { arraySize, squeeze } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'cross';
|
||||
var dependencies = ['typed', 'matrix', 'subtract', 'multiply'];
|
||||
export var createCross = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Matrix_Matrix(x, y) {
|
||||
return matrix(_cross(x.toArray(), y.toArray()));
|
||||
},
|
||||
'Matrix, Array': function Matrix_Array(x, y) {
|
||||
return matrix(_cross(x.toArray(), y));
|
||||
},
|
||||
'Array, Matrix': function Array_Matrix(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) {
|
||||
var highestDimension = Math.max(arraySize(x).length, arraySize(y).length);
|
||||
x = squeeze(x);
|
||||
y = squeeze(y);
|
||||
var xSize = arraySize(x);
|
||||
var ySize = 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(', ') + '])');
|
||||
}
|
||||
var 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;
|
||||
}
|
||||
}
|
||||
});
|
||||
37
node_modules/mathjs/lib/esm/function/matrix/ctranspose.js
generated
vendored
Normal file
37
node_modules/mathjs/lib/esm/function/matrix/ctranspose.js
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'ctranspose';
|
||||
var dependencies = ['typed', 'transpose', 'conj'];
|
||||
export var createCtranspose = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 any(x) {
|
||||
return conj(transpose(x));
|
||||
}
|
||||
});
|
||||
});
|
||||
142
node_modules/mathjs/lib/esm/function/matrix/det.js
generated
vendored
Normal file
142
node_modules/mathjs/lib/esm/function/matrix/det.js
generated
vendored
Normal file
@@ -0,0 +1,142 @@
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
import { clone } from '../../utils/object.js';
|
||||
import { format } from '../../utils/string.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'det';
|
||||
var dependencies = ['typed', 'matrix', 'subtractScalar', 'multiply', 'divideScalar', 'isZero', 'unaryMinus'];
|
||||
export var createDet = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 any(x) {
|
||||
return clone(x);
|
||||
},
|
||||
'Array | Matrix': function det(x) {
|
||||
var size;
|
||||
if (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 clone(x);
|
||||
case 1:
|
||||
// vector
|
||||
if (size[0] === 1) {
|
||||
return 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: ' + format(size) + ')');
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// two-dimensional array
|
||||
var rows = size[0];
|
||||
var 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: ' + format(size) + ')');
|
||||
}
|
||||
}
|
||||
default:
|
||||
// multi dimensional array
|
||||
throw new RangeError('Matrix must be two dimensional ' + '(size: ' + 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 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
|
||||
var negated = false;
|
||||
var rowIndices = new Array(rows).fill(0).map((_, i) => i); // matrix index of row i
|
||||
for (var k = 0; k < rows; k++) {
|
||||
var k_ = rowIndices[k];
|
||||
if (isZero(matrix[k_][k])) {
|
||||
var _k = void 0;
|
||||
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
|
||||
}
|
||||
var piv = matrix[k_][k];
|
||||
var piv_ = k === 0 ? 1 : matrix[rowIndices[k - 1]][k - 1];
|
||||
for (var i = k + 1; i < rows; i++) {
|
||||
var i_ = rowIndices[i];
|
||||
for (var j = k + 1; j < rows; j++) {
|
||||
matrix[i_][j] = divideScalar(subtractScalar(multiply(matrix[i_][j], piv), multiply(matrix[i_][k], matrix[k_][j])), piv_);
|
||||
}
|
||||
}
|
||||
}
|
||||
var det = matrix[rowIndices[rows - 1]][rows - 1];
|
||||
return negated ? unaryMinus(det) : det;
|
||||
}
|
||||
}
|
||||
});
|
||||
155
node_modules/mathjs/lib/esm/function/matrix/diag.js
generated
vendored
Normal file
155
node_modules/mathjs/lib/esm/function/matrix/diag.js
generated
vendored
Normal file
@@ -0,0 +1,155 @@
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
import { arraySize } from '../../utils/array.js';
|
||||
import { isInteger } from '../../utils/number.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'diag';
|
||||
var dependencies = ['typed', 'matrix', 'DenseMatrix', 'SparseMatrix'];
|
||||
export var createDiag = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array(x) {
|
||||
return _diag(x, 0, arraySize(x), null);
|
||||
},
|
||||
'Array, number': function Array_number(x, k) {
|
||||
return _diag(x, k, arraySize(x), null);
|
||||
},
|
||||
'Array, BigNumber': function Array_BigNumber(x, k) {
|
||||
return _diag(x, k.toNumber(), arraySize(x), null);
|
||||
},
|
||||
'Array, string': function Array_string(x, format) {
|
||||
return _diag(x, 0, arraySize(x), format);
|
||||
},
|
||||
'Array, number, string': function Array_number_string(x, k, format) {
|
||||
return _diag(x, k, arraySize(x), format);
|
||||
},
|
||||
'Array, BigNumber, string': function Array_BigNumber_string(x, k, format) {
|
||||
return _diag(x, k.toNumber(), arraySize(x), format);
|
||||
},
|
||||
Matrix: function Matrix(x) {
|
||||
return _diag(x, 0, x.size(), x.storage());
|
||||
},
|
||||
'Matrix, number': function Matrix_number(x, k) {
|
||||
return _diag(x, k, x.size(), x.storage());
|
||||
},
|
||||
'Matrix, BigNumber': function Matrix_BigNumber(x, k) {
|
||||
return _diag(x, k.toNumber(), x.size(), x.storage());
|
||||
},
|
||||
'Matrix, string': function Matrix_string(x, format) {
|
||||
return _diag(x, 0, x.size(), format);
|
||||
},
|
||||
'Matrix, number, string': function Matrix_number_string(x, k, format) {
|
||||
return _diag(x, k, x.size(), format);
|
||||
},
|
||||
'Matrix, BigNumber, string': function Matrix_BigNumber_string(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 (!isInteger(k)) {
|
||||
throw new TypeError('Second parameter in function diag must be an integer');
|
||||
}
|
||||
var kSuper = k > 0 ? k : 0;
|
||||
var 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
|
||||
var ms = [l + kSub, l + kSuper];
|
||||
if (format && format !== 'sparse' && format !== 'dense') {
|
||||
throw new TypeError("Unknown matrix type ".concat(format, "\""));
|
||||
}
|
||||
|
||||
// create diagonal matrix
|
||||
var 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 (isMatrix(x)) {
|
||||
// get diagonal matrix
|
||||
var 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
|
||||
var n = Math.min(s[0] - kSub, s[1] - kSuper);
|
||||
// diagonal values
|
||||
var vector = [];
|
||||
// loop diagonal
|
||||
for (var 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;
|
||||
}
|
||||
});
|
||||
163
node_modules/mathjs/lib/esm/function/matrix/diff.js
generated
vendored
Normal file
163
node_modules/mathjs/lib/esm/function/matrix/diff.js
generated
vendored
Normal file
@@ -0,0 +1,163 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { isInteger } from '../../utils/number.js';
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
var name = 'diff';
|
||||
var dependencies = ['typed', 'matrix', 'subtract', 'number'];
|
||||
export var createDiff = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array__Matrix(arr) {
|
||||
// No dimension specified => assume dimension 0
|
||||
if (isMatrix(arr)) {
|
||||
return matrix(_diff(arr.toArray()));
|
||||
} else {
|
||||
return _diff(arr);
|
||||
}
|
||||
},
|
||||
'Array | Matrix, number': function Array__Matrix_number(arr, dim) {
|
||||
if (!isInteger(dim)) throw new RangeError('Dimension must be a whole number');
|
||||
if (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 (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) {
|
||||
var 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) {
|
||||
var result = [];
|
||||
var size = arr.length;
|
||||
for (var 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 (isMatrix(obj1)) obj1 = obj1.toArray();
|
||||
if (isMatrix(obj2)) obj2 = obj2.toArray();
|
||||
var obj1IsArray = Array.isArray(obj1);
|
||||
var 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');
|
||||
}
|
||||
var result = [];
|
||||
var size = arr1.length;
|
||||
for (var i = 0; i < size; i++) {
|
||||
result.push(_ElementDiff(arr1[i], arr2[i]));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
});
|
||||
156
node_modules/mathjs/lib/esm/function/matrix/dot.js
generated
vendored
Normal file
156
node_modules/mathjs/lib/esm/function/matrix/dot.js
generated
vendored
Normal file
@@ -0,0 +1,156 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
var name = 'dot';
|
||||
var dependencies = ['typed', 'addScalar', 'multiplyScalar', 'conj', 'size'];
|
||||
export var createDot = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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) {
|
||||
var xSize = _size(x);
|
||||
var ySize = _size(y);
|
||||
var 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) {
|
||||
var N = _validateDim(a, b);
|
||||
var adata = isMatrix(a) ? a._data : a;
|
||||
var adt = isMatrix(a) ? a._datatype || a.getDataType() : undefined;
|
||||
var bdata = isMatrix(b) ? b._data : b;
|
||||
var bdt = isMatrix(b) ? b._datatype || b.getDataType() : undefined;
|
||||
|
||||
// are these 2-dimensional column vectors? (as opposed to 1-dimensional vectors)
|
||||
var aIsColumn = _size(a).length === 2;
|
||||
var bIsColumn = _size(b).length === 2;
|
||||
var add = addScalar;
|
||||
var mul = multiplyScalar;
|
||||
|
||||
// process data types
|
||||
if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
|
||||
var 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) {
|
||||
var c = mul(conj(adata[0]), bdata[0]);
|
||||
for (var 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) {
|
||||
var _c = mul(conj(adata[0]), bdata[0][0]);
|
||||
for (var _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) {
|
||||
var _c2 = mul(conj(adata[0][0]), bdata[0]);
|
||||
for (var _i2 = 1; _i2 < N; _i2++) {
|
||||
_c2 = add(_c2, mul(conj(adata[_i2][0]), bdata[_i2]));
|
||||
}
|
||||
return _c2;
|
||||
}
|
||||
|
||||
// both vectors are column
|
||||
if (aIsColumn && bIsColumn) {
|
||||
var _c3 = mul(conj(adata[0][0]), bdata[0][0]);
|
||||
for (var _i3 = 1; _i3 < N; _i3++) {
|
||||
_c3 = add(_c3, mul(conj(adata[_i3][0]), bdata[_i3][0]));
|
||||
}
|
||||
return _c3;
|
||||
}
|
||||
}
|
||||
function _sparseDot(x, y) {
|
||||
_validateDim(x, y);
|
||||
var xindex = x._index;
|
||||
var xvalues = x._values;
|
||||
var yindex = y._index;
|
||||
var yvalues = y._values;
|
||||
|
||||
// TODO optimize add & mul using datatype
|
||||
var c = 0;
|
||||
var add = addScalar;
|
||||
var mul = multiplyScalar;
|
||||
var i = 0;
|
||||
var j = 0;
|
||||
while (i < xindex.length && j < yindex.length) {
|
||||
var I = xindex[i];
|
||||
var 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 isMatrix(x) ? x.size() : size(x);
|
||||
}
|
||||
});
|
||||
328
node_modules/mathjs/lib/esm/function/matrix/eigs.js
generated
vendored
Normal file
328
node_modules/mathjs/lib/esm/function/matrix/eigs.js
generated
vendored
Normal file
@@ -0,0 +1,328 @@
|
||||
import _extends from "@babel/runtime/helpers/extends";
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { format } from '../../utils/string.js';
|
||||
import { createComplexEigs } from './eigs/complexEigs.js';
|
||||
import { createRealSymmetric } from './eigs/realSymmetric.js';
|
||||
import { typeOf, isNumber, isBigNumber, isComplex, isFraction } from '../../utils/is.js';
|
||||
var name = 'eigs';
|
||||
|
||||
// The absolute state of math.js's dependency system:
|
||||
var 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'];
|
||||
export var createEigs = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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;
|
||||
var doRealSymmetric = createRealSymmetric({
|
||||
config,
|
||||
addScalar,
|
||||
subtract,
|
||||
column,
|
||||
flatten,
|
||||
equal,
|
||||
abs,
|
||||
atan,
|
||||
cos,
|
||||
sin,
|
||||
multiplyScalar,
|
||||
inv,
|
||||
bignumber,
|
||||
complex,
|
||||
multiply,
|
||||
add
|
||||
});
|
||||
var doComplexEigs = 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 Array(x) {
|
||||
return doEigs(matrix(x));
|
||||
},
|
||||
'Array, number|BigNumber': function Array_numberBigNumber(x, prec) {
|
||||
return doEigs(matrix(x), {
|
||||
precision: prec
|
||||
});
|
||||
},
|
||||
'Array, Object'(x, opts) {
|
||||
return doEigs(matrix(x), opts);
|
||||
},
|
||||
Matrix: function Matrix(mat) {
|
||||
return doEigs(mat, {
|
||||
matricize: true
|
||||
});
|
||||
},
|
||||
'Matrix, number|BigNumber': function Matrix_numberBigNumber(mat, prec) {
|
||||
return doEigs(mat, {
|
||||
precision: prec,
|
||||
matricize: true
|
||||
});
|
||||
},
|
||||
'Matrix, Object': function Matrix_Object(mat, opts) {
|
||||
var useOpts = {
|
||||
matricize: true
|
||||
};
|
||||
_extends(useOpts, opts);
|
||||
return doEigs(mat, useOpts);
|
||||
}
|
||||
});
|
||||
function doEigs(mat) {
|
||||
var _opts$precision;
|
||||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
||||
var computeVectors = 'eigenvectors' in opts ? opts.eigenvectors : true;
|
||||
var prec = (_opts$precision = opts.precision) !== null && _opts$precision !== void 0 ? _opts$precision : config.relTol;
|
||||
var result = computeValuesAndVectors(mat, prec, computeVectors);
|
||||
if (opts.matricize) {
|
||||
result.values = matrix(result.values);
|
||||
if (computeVectors) {
|
||||
result.eigenvectors = result.eigenvectors.map(_ref2 => {
|
||||
var {
|
||||
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) {
|
||||
var arr = mat.toArray(); // NOTE: arr is guaranteed to be unaliased
|
||||
// and so safe to modify in place
|
||||
var asize = mat.size();
|
||||
if (asize.length !== 2 || asize[0] !== asize[1]) {
|
||||
throw new RangeError("Matrix must be square (size: ".concat(format(asize), ")"));
|
||||
}
|
||||
var N = asize[0];
|
||||
if (isReal(arr, N, prec)) {
|
||||
coerceReal(arr, N); // modifies arr by side effect
|
||||
|
||||
if (isSymmetric(arr, N, prec)) {
|
||||
var _type = coerceTypes(mat, arr, N); // modifies arr by side effect
|
||||
return doRealSymmetric(arr, N, prec, _type, computeVectors);
|
||||
}
|
||||
}
|
||||
var 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 (var i = 0; i < N; i++) {
|
||||
for (var 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 (var i = 0; i < N; i++) {
|
||||
for (var 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 (var i = 0; i < N; i++) {
|
||||
for (var j = 0; j < N; j++) {
|
||||
arr[i][j] = re(arr[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return {'number' | 'BigNumber' | 'Complex'} */
|
||||
function coerceTypes(mat, arr, N) {
|
||||
/** @type {string} */
|
||||
var type = mat.datatype();
|
||||
if (type === 'number' || type === 'BigNumber' || type === 'Complex') {
|
||||
return type;
|
||||
}
|
||||
var hasNumber = false;
|
||||
var hasBig = false;
|
||||
var hasComplex = false;
|
||||
for (var i = 0; i < N; i++) {
|
||||
for (var j = 0; j < N; j++) {
|
||||
var el = arr[i][j];
|
||||
if (isNumber(el) || isFraction(el)) {
|
||||
hasNumber = true;
|
||||
} else if (isBigNumber(el)) {
|
||||
hasBig = true;
|
||||
} else if (isComplex(el)) {
|
||||
hasComplex = true;
|
||||
} else {
|
||||
throw TypeError('Unsupported type in Matrix: ' + typeOf(el));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasBig && hasComplex) {
|
||||
console.warn('Complex BigNumbers not supported, this operation will lose precission.');
|
||||
}
|
||||
if (hasComplex) {
|
||||
for (var _i = 0; _i < N; _i++) {
|
||||
for (var _j = 0; _j < N; _j++) {
|
||||
arr[_i][_j] = complex(arr[_i][_j]);
|
||||
}
|
||||
}
|
||||
return 'Complex';
|
||||
}
|
||||
if (hasBig) {
|
||||
for (var _i2 = 0; _i2 < N; _i2++) {
|
||||
for (var _j2 = 0; _j2 < N; _j2++) {
|
||||
arr[_i2][_j2] = bignumber(arr[_i2][_j2]);
|
||||
}
|
||||
}
|
||||
return 'BigNumber';
|
||||
}
|
||||
if (hasNumber) {
|
||||
for (var _i3 = 0; _i3 < N; _i3++) {
|
||||
for (var _j3 = 0; _j3 < N; _j3++) {
|
||||
arr[_i3][_j3] = number(arr[_i3][_j3]);
|
||||
}
|
||||
}
|
||||
return 'number';
|
||||
} else {
|
||||
throw TypeError('Matrix contains unsupported types only.');
|
||||
}
|
||||
}
|
||||
});
|
||||
698
node_modules/mathjs/lib/esm/function/matrix/eigs/complexEigs.js
generated
vendored
Normal file
698
node_modules/mathjs/lib/esm/function/matrix/eigs/complexEigs.js
generated
vendored
Normal file
@@ -0,0 +1,698 @@
|
||||
import { clone } from '../../../utils/object.js';
|
||||
export function createComplexEigs(_ref) {
|
||||
var {
|
||||
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) {
|
||||
var 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!
|
||||
var 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
|
||||
var {
|
||||
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) {
|
||||
var 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) {
|
||||
var big = type === 'BigNumber';
|
||||
var cplx = type === 'Complex';
|
||||
var realzero = big ? bignumber(0) : 0;
|
||||
var one = big ? bignumber(1) : cplx ? complex(1) : 1;
|
||||
var realone = big ? bignumber(1) : 1;
|
||||
|
||||
// base of the floating-point arithmetic
|
||||
var radix = big ? bignumber(10) : 2;
|
||||
var radixSq = multiplyScalar(radix, radix);
|
||||
|
||||
// the diagonal transformation matrix R
|
||||
var Rdiag;
|
||||
if (findVectors) {
|
||||
Rdiag = Array(N).fill(one);
|
||||
}
|
||||
|
||||
// this isn't the only time we loop thru the matrix...
|
||||
var last = false;
|
||||
while (!last) {
|
||||
// ...haha I'm joking! unless...
|
||||
last = true;
|
||||
for (var i = 0; i < N; i++) {
|
||||
// compute the taxicab norm of i-th column and row
|
||||
// TODO optimize for complex numbers
|
||||
var colNorm = realzero;
|
||||
var rowNorm = realzero;
|
||||
for (var 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)
|
||||
|
||||
var f = realone;
|
||||
var c = colNorm;
|
||||
var rowDivRadix = divideScalar(rowNorm, radix);
|
||||
var 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)
|
||||
var 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;
|
||||
var g = divideScalar(1, f);
|
||||
for (var _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) {
|
||||
var big = type === 'BigNumber';
|
||||
var cplx = type === 'Complex';
|
||||
var zero = big ? bignumber(0) : cplx ? complex(0) : 0;
|
||||
if (big) {
|
||||
prec = bignumber(prec);
|
||||
}
|
||||
for (var i = 0; i < N - 2; i++) {
|
||||
// Find the largest subdiag element in the i-th col
|
||||
|
||||
var maxIndex = 0;
|
||||
var max = zero;
|
||||
for (var j = i + 1; j < N; j++) {
|
||||
var 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
|
||||
var tmp1 = arr[maxIndex];
|
||||
arr[maxIndex] = arr[i + 1];
|
||||
arr[i + 1] = tmp1;
|
||||
|
||||
// Interchange maxIndex-th and (i+1)-th column
|
||||
for (var _j2 = 0; _j2 < N; _j2++) {
|
||||
var tmp2 = arr[_j2][maxIndex];
|
||||
arr[_j2][maxIndex] = arr[_j2][i + 1];
|
||||
arr[_j2][i + 1] = tmp2;
|
||||
}
|
||||
|
||||
// keep track of transformations
|
||||
if (findVectors) {
|
||||
var tmp3 = R[maxIndex];
|
||||
R[maxIndex] = R[i + 1];
|
||||
R[i + 1] = tmp3;
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce following rows and columns
|
||||
for (var _j3 = i + 2; _j3 < N; _j3++) {
|
||||
var n = divideScalar(arr[_j3][i], max);
|
||||
if (n === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// from j-th row subtract n-times (i+1)th row
|
||||
for (var k = 0; k < N; k++) {
|
||||
arr[_j3][k] = subtract(arr[_j3][k], multiplyScalar(n, arr[i + 1][k]));
|
||||
}
|
||||
|
||||
// to (i+1)th column add n-times j-th column
|
||||
for (var _k = 0; _k < N; _k++) {
|
||||
arr[_k][i + 1] = addScalar(arr[_k][i + 1], multiplyScalar(n, arr[_k][_j3]));
|
||||
}
|
||||
|
||||
// keep track of transformations
|
||||
if (findVectors) {
|
||||
for (var _k2 = 0; _k2 < N; _k2++) {
|
||||
R[_j3][_k2] = subtract(R[_j3][_k2], multiplyScalar(n, R[i + 1][_k2]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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) {
|
||||
var big = type === 'BigNumber';
|
||||
var cplx = type === 'Complex';
|
||||
var 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.
|
||||
|
||||
var arr = clone(A);
|
||||
|
||||
// the list of converged eigenvalues
|
||||
var lambdas = [];
|
||||
|
||||
// size of arr, which will get smaller as eigenvalues converge
|
||||
var n = N;
|
||||
|
||||
// the diagonal of the block-diagonal matrix that turns
|
||||
// converged 2x2 matrices into upper triangular matrices
|
||||
var Sdiag = [];
|
||||
|
||||
// N×N matrix describing the overall transformation done during the QR algorithm
|
||||
var Qtotal = findVectors ? diag(Array(N).fill(one)) : undefined;
|
||||
|
||||
// nxn matrix describing the QR transformations done since last convergence
|
||||
var Qpartial = findVectors ? diag(Array(n).fill(one)) : undefined;
|
||||
|
||||
// last eigenvalue converged before this many steps
|
||||
var lastConvergenceBefore = 0;
|
||||
while (lastConvergenceBefore <= 100) {
|
||||
lastConvergenceBefore += 1;
|
||||
|
||||
// TODO if the convergence is slow, do something clever
|
||||
|
||||
// Perform the factorization
|
||||
|
||||
var 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 (var i = 0; i < n; i++) {
|
||||
arr[i][i] = subtract(arr[i][i], k);
|
||||
}
|
||||
|
||||
// TODO do an implicit QR transformation
|
||||
var {
|
||||
Q,
|
||||
R
|
||||
} = qr(arr);
|
||||
arr = multiply(R, Q);
|
||||
for (var _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 (var _i2 = 0; _i2 < n; _i2++) {
|
||||
arr[_i2].pop();
|
||||
}
|
||||
|
||||
// The rightmost diagonal 2x2 block converged
|
||||
} else if (n === 2 || smaller(abs(arr[n - 2][n - 3]), prec)) {
|
||||
lastConvergenceBefore = 0;
|
||||
var 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 (var _i3 = 0; _i3 < n; _i3++) {
|
||||
arr[_i3].pop();
|
||||
arr[_i3].pop();
|
||||
}
|
||||
}
|
||||
if (n === 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// standard sorting
|
||||
lambdas.sort((a, b) => +subtract(abs(a), abs(b)));
|
||||
|
||||
// the algorithm didn't converge
|
||||
if (lastConvergenceBefore > 100) {
|
||||
var 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
|
||||
var 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) {
|
||||
var Cinv = inv(C);
|
||||
var U = multiply(Cinv, A, C);
|
||||
var big = type === 'BigNumber';
|
||||
var cplx = type === 'Complex';
|
||||
var zero = big ? bignumber(0) : cplx ? complex(0) : 0;
|
||||
var one = big ? bignumber(1) : cplx ? complex(1) : 1;
|
||||
|
||||
// turn values into a kind of "multiset"
|
||||
// this way it is easier to find eigenvectors
|
||||
var uniqueValues = [];
|
||||
var multiplicities = [];
|
||||
for (var lambda of values) {
|
||||
var 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)
|
||||
|
||||
var vectors = [];
|
||||
var len = uniqueValues.length;
|
||||
var b = Array(N).fill(zero);
|
||||
var E = diag(Array(N).fill(one));
|
||||
var _loop = function _loop() {
|
||||
var lambda = uniqueValues[_i4];
|
||||
var S = subtract(U, multiply(lambda, E)); // the characteristic matrix
|
||||
|
||||
var 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[_i4]) {
|
||||
var 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
|
||||
var correction = multiply(inv(R), C);
|
||||
solutions = solutions.map(v => multiply(correction, v));
|
||||
vectors.push(...solutions.map(v => ({
|
||||
value: lambda,
|
||||
vector: flatten(v)
|
||||
})));
|
||||
};
|
||||
for (var _i4 = 0; _i4 < len; _i4++) {
|
||||
_loop();
|
||||
}
|
||||
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 )
|
||||
var trA = addScalar(a, d);
|
||||
var detA = subtract(multiplyScalar(a, d), multiplyScalar(b, c));
|
||||
var x = multiplyScalar(trA, 0.5);
|
||||
var 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) {
|
||||
var big = type === 'BigNumber';
|
||||
var cplx = type === 'Complex';
|
||||
var zero = big ? bignumber(0) : cplx ? complex(0) : 0;
|
||||
var 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
|
||||
var na = subtract(a, l1);
|
||||
var 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 (var i = 0; i < arr.length; i++) {
|
||||
arr[i].push(...Array(N - arr[i].length).fill(0));
|
||||
}
|
||||
|
||||
// add rows
|
||||
for (var _i5 = arr.length; _i5 < N; _i5++) {
|
||||
arr.push(Array(N).fill(0));
|
||||
arr[_i5][_i5] = 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) {
|
||||
var M = [];
|
||||
for (var i = 0; i < N; i++) {
|
||||
M[i] = Array(N).fill(0);
|
||||
}
|
||||
var I = 0;
|
||||
for (var sub of arr) {
|
||||
var n = sub.length;
|
||||
for (var _i6 = 0; _i6 < n; _i6++) {
|
||||
for (var j = 0; j < n; j++) {
|
||||
M[I + _i6][I + j] = sub[_i6][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 (var 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) {
|
||||
var largeNum = type === 'BigNumber' ? bignumber(1000) : 1000;
|
||||
var b; // the vector
|
||||
|
||||
// you better choose a random vector before I count to five
|
||||
var 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) {
|
||||
var 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) {
|
||||
var big = type === 'BigNumber';
|
||||
var cplx = type === 'Complex';
|
||||
|
||||
// generate random vector with the correct type
|
||||
var 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) {
|
||||
var vectorShape = size(v);
|
||||
for (var 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) {
|
||||
var big = type === 'BigNumber';
|
||||
var cplx = type === 'Complex';
|
||||
var one = big ? bignumber(1) : cplx ? complex(1) : 1;
|
||||
return multiply(divideScalar(one, norm(v)), v);
|
||||
}
|
||||
return complexEigs;
|
||||
}
|
||||
297
node_modules/mathjs/lib/esm/function/matrix/eigs/realSymmetric.js
generated
vendored
Normal file
297
node_modules/mathjs/lib/esm/function/matrix/eigs/realSymmetric.js
generated
vendored
Normal file
@@ -0,0 +1,297 @@
|
||||
import { clone } from '../../../utils/object.js';
|
||||
export function createRealSymmetric(_ref) {
|
||||
var {
|
||||
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) {
|
||||
var prec = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : config.relTol;
|
||||
var type = arguments.length > 3 ? arguments[3] : undefined;
|
||||
var 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) {
|
||||
var N = x.length;
|
||||
var e0 = Math.abs(precision / N);
|
||||
var psi;
|
||||
var Sij;
|
||||
if (computeVectors) {
|
||||
Sij = new Array(N);
|
||||
// Sij is Identity Matrix
|
||||
for (var i = 0; i < N; i++) {
|
||||
Sij[i] = Array(N).fill(0);
|
||||
Sij[i][i] = 1.0;
|
||||
}
|
||||
}
|
||||
// initial error
|
||||
var Vab = getAij(x);
|
||||
while (Math.abs(Vab[1]) >= Math.abs(e0)) {
|
||||
var _i = Vab[0][0];
|
||||
var 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);
|
||||
}
|
||||
var Ei = Array(N).fill(0); // eigenvalues
|
||||
for (var _i2 = 0; _i2 < N; _i2++) {
|
||||
Ei[_i2] = x[_i2][_i2];
|
||||
}
|
||||
return sorting(clone(Ei), Sij, computeVectors);
|
||||
}
|
||||
|
||||
// diagonalization implementation for bigNumber
|
||||
function diagBig(x, precision, computeVectors) {
|
||||
var N = x.length;
|
||||
var e0 = abs(precision / N);
|
||||
var psi;
|
||||
var Sij;
|
||||
if (computeVectors) {
|
||||
Sij = new Array(N);
|
||||
// Sij is Identity Matrix
|
||||
for (var i = 0; i < N; i++) {
|
||||
Sij[i] = Array(N).fill(0);
|
||||
Sij[i][i] = 1.0;
|
||||
}
|
||||
}
|
||||
// initial error
|
||||
var Vab = getAijBig(x);
|
||||
while (abs(Vab[1]) >= abs(e0)) {
|
||||
var _i3 = Vab[0][0];
|
||||
var j = Vab[0][1];
|
||||
psi = getThetaBig(x[_i3][_i3], x[j][j], x[_i3][j]);
|
||||
x = x1Big(x, psi, _i3, j);
|
||||
if (computeVectors) Sij = Sij1Big(Sij, psi, _i3, j);
|
||||
Vab = getAijBig(x);
|
||||
}
|
||||
var Ei = Array(N).fill(0); // eigenvalues
|
||||
for (var _i4 = 0; _i4 < N; _i4++) {
|
||||
Ei[_i4] = x[_i4][_i4];
|
||||
}
|
||||
// return [clone(Ei), clone(Sij)]
|
||||
return sorting(clone(Ei), Sij, computeVectors);
|
||||
}
|
||||
|
||||
// get angle
|
||||
function getTheta(aii, ajj, aij) {
|
||||
var 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) {
|
||||
var 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) {
|
||||
var N = Sij.length;
|
||||
var c = Math.cos(theta);
|
||||
var s = Math.sin(theta);
|
||||
var Ski = Array(N).fill(0);
|
||||
var Skj = Array(N).fill(0);
|
||||
for (var 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 (var _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) {
|
||||
var N = Sij.length;
|
||||
var c = cos(theta);
|
||||
var s = sin(theta);
|
||||
var Ski = Array(N).fill(bignumber(0));
|
||||
var Skj = Array(N).fill(bignumber(0));
|
||||
for (var 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 (var _k2 = 0; _k2 < N; _k2++) {
|
||||
Sij[_k2][i] = Ski[_k2];
|
||||
Sij[_k2][j] = Skj[_k2];
|
||||
}
|
||||
return Sij;
|
||||
}
|
||||
|
||||
// update matrix
|
||||
function x1Big(Hij, theta, i, j) {
|
||||
var N = Hij.length;
|
||||
var c = bignumber(cos(theta));
|
||||
var s = bignumber(sin(theta));
|
||||
var c2 = multiplyScalar(c, c);
|
||||
var s2 = multiplyScalar(s, s);
|
||||
var Aki = Array(N).fill(bignumber(0));
|
||||
var Akj = Array(N).fill(bignumber(0));
|
||||
// 2cs Hij
|
||||
var csHij = multiply(bignumber(2), c, s, Hij[i][j]);
|
||||
// Aii
|
||||
var Aii = addScalar(subtract(multiplyScalar(c2, Hij[i][i]), csHij), multiplyScalar(s2, Hij[j][j]));
|
||||
var Ajj = add(multiplyScalar(s2, Hij[i][i]), csHij, multiplyScalar(c2, Hij[j][j]));
|
||||
// 0 to i
|
||||
for (var 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 (var _k3 = 0; _k3 < N; _k3++) {
|
||||
if (_k3 !== i && _k3 !== j) {
|
||||
Hij[i][_k3] = Aki[_k3];
|
||||
Hij[_k3][i] = Aki[_k3];
|
||||
Hij[j][_k3] = Akj[_k3];
|
||||
Hij[_k3][j] = Akj[_k3];
|
||||
}
|
||||
}
|
||||
return Hij;
|
||||
}
|
||||
|
||||
// update matrix
|
||||
function x1(Hij, theta, i, j) {
|
||||
var N = Hij.length;
|
||||
var c = Math.cos(theta);
|
||||
var s = Math.sin(theta);
|
||||
var c2 = c * c;
|
||||
var s2 = s * s;
|
||||
var Aki = Array(N).fill(0);
|
||||
var Akj = Array(N).fill(0);
|
||||
// Aii
|
||||
var Aii = c2 * Hij[i][i] - 2 * c * s * Hij[i][j] + s2 * Hij[j][j];
|
||||
var Ajj = s2 * Hij[i][i] + 2 * c * s * Hij[i][j] + c2 * Hij[j][j];
|
||||
// 0 to i
|
||||
for (var 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 (var _k4 = 0; _k4 < N; _k4++) {
|
||||
if (_k4 !== i && _k4 !== j) {
|
||||
Hij[i][_k4] = Aki[_k4];
|
||||
Hij[_k4][i] = Aki[_k4];
|
||||
Hij[j][_k4] = Akj[_k4];
|
||||
Hij[_k4][j] = Akj[_k4];
|
||||
}
|
||||
}
|
||||
return Hij;
|
||||
}
|
||||
|
||||
// get max off-diagonal value from Upper Diagonal
|
||||
function getAij(Mij) {
|
||||
var N = Mij.length;
|
||||
var maxMij = 0;
|
||||
var maxIJ = [0, 1];
|
||||
for (var i = 0; i < N; i++) {
|
||||
for (var 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) {
|
||||
var N = Mij.length;
|
||||
var maxMij = 0;
|
||||
var maxIJ = [0, 1];
|
||||
for (var i = 0; i < N; i++) {
|
||||
for (var 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) {
|
||||
var N = E.length;
|
||||
var values = Array(N);
|
||||
var vecs;
|
||||
if (computeVectors) {
|
||||
vecs = Array(N);
|
||||
for (var k = 0; k < N; k++) {
|
||||
vecs[k] = Array(N);
|
||||
}
|
||||
}
|
||||
for (var i = 0; i < N; i++) {
|
||||
var minID = 0;
|
||||
var minE = E[0];
|
||||
for (var 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 (var _k5 = 0; _k5 < N; _k5++) {
|
||||
vecs[i][_k5] = S[_k5][minID];
|
||||
S[_k5].splice(minID, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!computeVectors) return {
|
||||
values
|
||||
};
|
||||
var eigenvectors = vecs.map((vector, i) => ({
|
||||
value: values[i],
|
||||
vector
|
||||
}));
|
||||
return {
|
||||
values,
|
||||
eigenvectors
|
||||
};
|
||||
}
|
||||
return main;
|
||||
}
|
||||
154
node_modules/mathjs/lib/esm/function/matrix/expm.js
generated
vendored
Normal file
154
node_modules/mathjs/lib/esm/function/matrix/expm.js
generated
vendored
Normal file
@@ -0,0 +1,154 @@
|
||||
import { isSparseMatrix } from '../../utils/is.js';
|
||||
import { format } from '../../utils/string.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'expm';
|
||||
var dependencies = ['typed', 'abs', 'add', 'identity', 'inv', 'multiply'];
|
||||
export var createExpm = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Matrix(A) {
|
||||
// Check matrix size
|
||||
var size = A.size();
|
||||
if (size.length !== 2 || size[0] !== size[1]) {
|
||||
throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
|
||||
}
|
||||
var n = size[0];
|
||||
|
||||
// Desired accuracy of the approximant (The actual accuracy
|
||||
// will be affected by round-off error)
|
||||
var 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
|
||||
var infNorm = infinityNorm(A);
|
||||
|
||||
// Find the optimal scaling factor and number of terms in the
|
||||
// Padé approximant to reach the desired accuracy
|
||||
var params = findParams(infNorm, eps);
|
||||
var q = params.q;
|
||||
var 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
|
||||
var Apos = multiply(A, Math.pow(2, -j));
|
||||
|
||||
// The i=0 term is just the identity matrix
|
||||
var N = identity(n);
|
||||
var D = identity(n);
|
||||
|
||||
// Initialization (i=0)
|
||||
var factor = 1;
|
||||
|
||||
// Initialization (i=1)
|
||||
var AposToI = Apos; // Cloning not necessary
|
||||
var alternate = -1;
|
||||
for (var 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));
|
||||
}
|
||||
var R = multiply(inv(D), N);
|
||||
|
||||
// Square j times
|
||||
for (var _i = 0; _i < j; _i++) {
|
||||
R = multiply(R, R);
|
||||
}
|
||||
return isSparseMatrix(A) ? A.createSparseMatrix(R) : R;
|
||||
}
|
||||
});
|
||||
function infinityNorm(A) {
|
||||
var n = A.size()[0];
|
||||
var infNorm = 0;
|
||||
for (var i = 0; i < n; i++) {
|
||||
var rowSum = 0;
|
||||
for (var 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) {
|
||||
var maxSearchSize = 30;
|
||||
for (var k = 0; k < maxSearchSize; k++) {
|
||||
for (var q = 0; q <= k; q++) {
|
||||
var 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) {
|
||||
var qfac = 1;
|
||||
for (var i = 2; i <= q; i++) {
|
||||
qfac *= i;
|
||||
}
|
||||
var twoqfac = qfac;
|
||||
for (var _i2 = q + 1; _i2 <= 2 * q; _i2++) {
|
||||
twoqfac *= _i2;
|
||||
}
|
||||
var twoqp1fac = twoqfac * (2 * q + 1);
|
||||
return 8.0 * Math.pow(infNorm / Math.pow(2, j), 2 * q) * qfac * qfac / (twoqfac * twoqp1fac);
|
||||
}
|
||||
});
|
||||
128
node_modules/mathjs/lib/esm/function/matrix/fft.js
generated
vendored
Normal file
128
node_modules/mathjs/lib/esm/function/matrix/fft.js
generated
vendored
Normal file
@@ -0,0 +1,128 @@
|
||||
import { arraySize } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'fft';
|
||||
var dependencies = ['typed', 'matrix', 'addScalar', 'multiplyScalar', 'divideScalar', 'exp', 'tau', 'i', 'dotDivide', 'conj', 'pow', 'ceil', 'log2'];
|
||||
export var createFft = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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(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) {
|
||||
var size = 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) {
|
||||
var size = 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
|
||||
var size = 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) {
|
||||
var n = arr.length;
|
||||
var w = exp(divideScalar(multiplyScalar(-1, multiplyScalar(I, tau)), n));
|
||||
var chirp = [];
|
||||
for (var i = 1 - n; i < n; i++) {
|
||||
chirp.push(pow(w, divideScalar(pow(i, 2), 2)));
|
||||
}
|
||||
var N2 = pow(2, ceil(log2(n + n - 1)));
|
||||
var xp = [...new Array(n).fill(0).map((_, i) => multiplyScalar(arr[i], chirp[n - 1 + i])), ...new Array(N2 - n).fill(0)];
|
||||
var ichirp = [...new Array(n + n - 1).fill(0).map((_, i) => divideScalar(1, chirp[i])), ...new Array(N2 - (n + n - 1)).fill(0)];
|
||||
var fftXp = _fft(xp);
|
||||
var fftIchirp = _fft(ichirp);
|
||||
var fftProduct = new Array(N2).fill(0).map((_, i) => multiplyScalar(fftXp[i], fftIchirp[i]));
|
||||
var ifftProduct = dotDivide(conj(_ndFft(conj(fftProduct))), N2);
|
||||
var ret = [];
|
||||
for (var _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) {
|
||||
var len = arr.length;
|
||||
if (len === 1) return [arr[0]];
|
||||
if (len % 2 === 0) {
|
||||
var ret = [..._fft(arr.filter((_, i) => i % 2 === 0), len / 2), ..._fft(arr.filter((_, i) => i % 2 === 1), len / 2)];
|
||||
for (var k = 0; k < len / 2; k++) {
|
||||
var p = ret[k];
|
||||
var 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')
|
||||
}
|
||||
});
|
||||
71
node_modules/mathjs/lib/esm/function/matrix/filter.js
generated
vendored
Normal file
71
node_modules/mathjs/lib/esm/function/matrix/filter.js
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
import { optimizeCallback } from '../../utils/optimizeCallback.js';
|
||||
import { filter, filterRegExp } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'filter';
|
||||
var dependencies = ['typed'];
|
||||
export var createFilter = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Matrix_function(x, test) {
|
||||
return x.create(_filterCallback(x.valueOf(), test), x.datatype());
|
||||
},
|
||||
'Array, RegExp': filterRegExp,
|
||||
'Matrix, RegExp': function Matrix_RegExp(x, test) {
|
||||
return x.create(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) {
|
||||
var fastCallback = optimizeCallback(callback, x, 'filter');
|
||||
return filter(x, function (value, index, array) {
|
||||
// invoke the callback function with the right number of arguments
|
||||
return fastCallback(value, [index], array);
|
||||
});
|
||||
}
|
||||
38
node_modules/mathjs/lib/esm/function/matrix/flatten.js
generated
vendored
Normal file
38
node_modules/mathjs/lib/esm/function/matrix/flatten.js
generated
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
import { flatten as flattenArray } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'flatten';
|
||||
var dependencies = ['typed'];
|
||||
export var createFlatten = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array(x) {
|
||||
return flattenArray(x);
|
||||
},
|
||||
Matrix: function Matrix(x) {
|
||||
// Return the same matrix type as x (Dense or Sparse Matrix)
|
||||
// Return the same data type as x
|
||||
return x.create(flattenArray(x.toArray()), x.datatype());
|
||||
}
|
||||
});
|
||||
});
|
||||
56
node_modules/mathjs/lib/esm/function/matrix/forEach.js
generated
vendored
Normal file
56
node_modules/mathjs/lib/esm/function/matrix/forEach.js
generated
vendored
Normal file
@@ -0,0 +1,56 @@
|
||||
import { optimizeCallback } from '../../utils/optimizeCallback.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { recurse } from '../../utils/array.js';
|
||||
var name = 'forEach';
|
||||
var dependencies = ['typed'];
|
||||
export var createForEach = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Matrix_function(x, callback) {
|
||||
x.forEach(callback);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* forEach for a multidimensional array
|
||||
* @param {Array} array
|
||||
* @param {Function} callback
|
||||
* @private
|
||||
*/
|
||||
function _forEach(array, callback) {
|
||||
recurse(array, [], array, optimizeCallback(callback, array, name));
|
||||
}
|
||||
52
node_modules/mathjs/lib/esm/function/matrix/getMatrixDataType.js
generated
vendored
Normal file
52
node_modules/mathjs/lib/esm/function/matrix/getMatrixDataType.js
generated
vendored
Normal file
@@ -0,0 +1,52 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { getArrayDataType } from '../../utils/array.js';
|
||||
import { typeOf } from '../../utils/is.js';
|
||||
var name = 'getMatrixDataType';
|
||||
var dependencies = ['typed'];
|
||||
export var createGetMatrixDataType = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array(x) {
|
||||
return getArrayDataType(x, typeOf);
|
||||
},
|
||||
Matrix: function Matrix(x) {
|
||||
return x.getDataType();
|
||||
}
|
||||
});
|
||||
});
|
||||
136
node_modules/mathjs/lib/esm/function/matrix/identity.js
generated
vendored
Normal file
136
node_modules/mathjs/lib/esm/function/matrix/identity.js
generated
vendored
Normal file
@@ -0,0 +1,136 @@
|
||||
import { isBigNumber } from '../../utils/is.js';
|
||||
import { resize } from '../../utils/array.js';
|
||||
import { isInteger } from '../../utils/number.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'identity';
|
||||
var dependencies = ['typed', 'config', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix'];
|
||||
export var createIdentity = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 string(format) {
|
||||
return matrix(format);
|
||||
},
|
||||
'number | BigNumber': function number__BigNumber(rows) {
|
||||
return _identity(rows, rows, config.matrix === 'Matrix' ? 'dense' : undefined);
|
||||
},
|
||||
'number | BigNumber, string': function number__BigNumber_string(rows, format) {
|
||||
return _identity(rows, rows, format);
|
||||
},
|
||||
'number | BigNumber, number | BigNumber': function number__BigNumber_number__BigNumber(rows, cols) {
|
||||
return _identity(rows, cols, config.matrix === 'Matrix' ? 'dense' : undefined);
|
||||
},
|
||||
'number | BigNumber, number | BigNumber, string': function number__BigNumber_number__BigNumber_string(rows, cols, format) {
|
||||
return _identity(rows, cols, format);
|
||||
},
|
||||
Array: function Array(size) {
|
||||
return _identityVector(size);
|
||||
},
|
||||
'Array, string': function Array_string(size, format) {
|
||||
return _identityVector(size, format);
|
||||
},
|
||||
Matrix: function Matrix(size) {
|
||||
return _identityVector(size.valueOf(), size.storage());
|
||||
},
|
||||
'Matrix, string': function Matrix_string(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
|
||||
var Big = isBigNumber(rows) || isBigNumber(cols) ? BigNumber : null;
|
||||
if (isBigNumber(rows)) rows = rows.toNumber();
|
||||
if (isBigNumber(cols)) cols = cols.toNumber();
|
||||
if (!isInteger(rows) || rows < 1) {
|
||||
throw new Error('Parameters in function identity must be positive integers');
|
||||
}
|
||||
if (!isInteger(cols) || cols < 1) {
|
||||
throw new Error('Parameters in function identity must be positive integers');
|
||||
}
|
||||
var one = Big ? new BigNumber(1) : 1;
|
||||
var defaultValue = Big ? new Big(0) : 0;
|
||||
var 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 \"".concat(format, "\""));
|
||||
}
|
||||
|
||||
// create and resize array
|
||||
var res = resize([], size, defaultValue);
|
||||
// fill in ones on the diagonal
|
||||
var minimum = rows < cols ? rows : cols;
|
||||
// fill diagonal
|
||||
for (var d = 0; d < minimum; d++) {
|
||||
res[d][d] = one;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
});
|
||||
37
node_modules/mathjs/lib/esm/function/matrix/ifft.js
generated
vendored
Normal file
37
node_modules/mathjs/lib/esm/function/matrix/ifft.js
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
import { arraySize } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
var name = 'ifft';
|
||||
var dependencies = ['typed', 'fft', 'dotDivide', 'conj'];
|
||||
export var createIfft = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array__Matrix(arr) {
|
||||
var size = isMatrix(arr) ? arr.size() : arraySize(arr);
|
||||
return dotDivide(conj(fft(conj(arr))), size.reduce((acc, curr) => acc * curr, 1));
|
||||
}
|
||||
});
|
||||
});
|
||||
184
node_modules/mathjs/lib/esm/function/matrix/inv.js
generated
vendored
Normal file
184
node_modules/mathjs/lib/esm/function/matrix/inv.js
generated
vendored
Normal file
@@ -0,0 +1,184 @@
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
import { arraySize } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { format } from '../../utils/string.js';
|
||||
var name = 'inv';
|
||||
var dependencies = ['typed', 'matrix', 'divideScalar', 'addScalar', 'multiply', 'unaryMinus', 'det', 'identity', 'abs'];
|
||||
export var createInv = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array__Matrix(x) {
|
||||
var size = isMatrix(x) ? x.size() : arraySize(x);
|
||||
switch (size.length) {
|
||||
case 1:
|
||||
// vector
|
||||
if (size[0] === 1) {
|
||||
if (isMatrix(x)) {
|
||||
return matrix([divideScalar(1, x.valueOf()[0])]);
|
||||
} else {
|
||||
return [divideScalar(1, x[0])];
|
||||
}
|
||||
} else {
|
||||
throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
|
||||
}
|
||||
case 2:
|
||||
// two dimensional array
|
||||
{
|
||||
var rows = size[0];
|
||||
var cols = size[1];
|
||||
if (rows === cols) {
|
||||
if (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: ' + format(size) + ')');
|
||||
}
|
||||
}
|
||||
default:
|
||||
// multi dimensional array
|
||||
throw new RangeError('Matrix must be two dimensional ' + '(size: ' + format(size) + ')');
|
||||
}
|
||||
},
|
||||
any: function any(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) {
|
||||
var 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
|
||||
var 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)
|
||||
var 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
|
||||
var B = identity(rows).valueOf();
|
||||
|
||||
// loop over all columns, and perform row reductions
|
||||
for (var c = 0; c < cols; c++) {
|
||||
// Pivoting: Swap row c with row r, where row r contains the largest element A[r][c]
|
||||
var ABig = abs(A[c][c]);
|
||||
var 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
|
||||
var Ac = A[c];
|
||||
var Bc = B[c];
|
||||
for (r = 0; r < rows; r++) {
|
||||
var Ar = A[r];
|
||||
var 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;
|
||||
}
|
||||
}
|
||||
});
|
||||
85
node_modules/mathjs/lib/esm/function/matrix/kron.js
generated
vendored
Normal file
85
node_modules/mathjs/lib/esm/function/matrix/kron.js
generated
vendored
Normal file
@@ -0,0 +1,85 @@
|
||||
import { arraySize as size } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'kron';
|
||||
var dependencies = ['typed', 'matrix', 'multiplyScalar'];
|
||||
export var createKron = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Matrix_Matrix(x, y) {
|
||||
return matrix(_kron(x.toArray(), y.toArray()));
|
||||
},
|
||||
'Matrix, Array': function Matrix_Array(x, y) {
|
||||
return matrix(_kron(x.toArray(), y));
|
||||
},
|
||||
'Array, Matrix': function Array_Matrix(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 (size(a).length === 1) {
|
||||
// Wrap it in a 2D Matrix
|
||||
a = [a];
|
||||
}
|
||||
if (size(b).length === 1) {
|
||||
// Wrap it in a 2D Matrix
|
||||
b = [b];
|
||||
}
|
||||
if (size(a).length > 2 || size(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) + ')');
|
||||
}
|
||||
var t = [];
|
||||
var 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;
|
||||
}
|
||||
});
|
||||
142
node_modules/mathjs/lib/esm/function/matrix/map.js
generated
vendored
Normal file
142
node_modules/mathjs/lib/esm/function/matrix/map.js
generated
vendored
Normal file
@@ -0,0 +1,142 @@
|
||||
import { optimizeCallback } from '../../utils/optimizeCallback.js';
|
||||
import { arraySize, broadcastSizes, broadcastTo, get, recurse } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'map';
|
||||
var dependencies = ['typed'];
|
||||
export var createMap = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Matrix_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');
|
||||
}
|
||||
var firstArrayIsMatrix = Arrays[0].isMatrix;
|
||||
var newSize = broadcastSizes(...Arrays.map(M => M.isMatrix ? M.size() : arraySize(M)));
|
||||
var _get = firstArrayIsMatrix ? (matrix, idx) => matrix.get(idx) : get;
|
||||
var broadcastedArrays = firstArrayIsMatrix ? Arrays.map(M => M.isMatrix ? M.create(broadcastTo(M.toArray(), newSize), M.datatype()) : Arrays[0].create(broadcastTo(M.valueOf(), newSize))) : Arrays.map(M => M.isMatrix ? broadcastTo(M.toArray(), newSize) : broadcastTo(M, newSize));
|
||||
var callback;
|
||||
if (typed.isTypedFunction(multiCallback)) {
|
||||
var firstIndex = newSize.map(() => 0);
|
||||
var firstValues = broadcastedArrays.map(array => _get(array, firstIndex));
|
||||
var callbackCase = _getTypedCallbackCase(multiCallback, firstValues, firstIndex, broadcastedArrays);
|
||||
callback = _getLimitedCallback(callbackCase);
|
||||
} else {
|
||||
var numberOfArrays = Arrays.length;
|
||||
var _callbackCase = _getCallbackCase(multiCallback, numberOfArrays);
|
||||
callback = _getLimitedCallback(_callbackCase);
|
||||
}
|
||||
var 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 recurse(array, [], array, optimizeCallback(callback, array, name));
|
||||
}
|
||||
});
|
||||
88
node_modules/mathjs/lib/esm/function/matrix/matrixFromColumns.js
generated
vendored
Normal file
88
node_modules/mathjs/lib/esm/function/matrix/matrixFromColumns.js
generated
vendored
Normal file
@@ -0,0 +1,88 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'matrixFromColumns';
|
||||
var dependencies = ['typed', 'matrix', 'flatten', 'size'];
|
||||
export var createMatrixFromColumns = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array(arr) {
|
||||
return _createArray(arr);
|
||||
},
|
||||
'...Matrix': function Matrix(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.');
|
||||
var N = checkVectorTypeAndReturnLength(arr[0]);
|
||||
|
||||
// create an array with empty rows
|
||||
var result = [];
|
||||
for (var i = 0; i < N; i++) {
|
||||
result[i] = [];
|
||||
}
|
||||
|
||||
// loop columns
|
||||
for (var col of arr) {
|
||||
var colLength = checkVectorTypeAndReturnLength(col);
|
||||
if (colLength !== N) {
|
||||
throw new TypeError('The vectors had different length: ' + (N | 0) + ' ≠ ' + (colLength | 0));
|
||||
}
|
||||
var f = flatten(col);
|
||||
|
||||
// push a value to each row
|
||||
for (var _i = 0; _i < N; _i++) {
|
||||
result[_i].push(f[_i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function checkVectorTypeAndReturnLength(vec) {
|
||||
var 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.');
|
||||
}
|
||||
}
|
||||
});
|
||||
74
node_modules/mathjs/lib/esm/function/matrix/matrixFromFunction.js
generated
vendored
Normal file
74
node_modules/mathjs/lib/esm/function/matrix/matrixFromFunction.js
generated
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'matrixFromFunction';
|
||||
var dependencies = ['typed', 'matrix', 'isZero'];
|
||||
export var createMatrixFromFunction = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array__Matrix_function_string_string(size, fn, format, datatype) {
|
||||
return _create(size, fn, format, datatype);
|
||||
},
|
||||
'Array | Matrix, function, string': function Array__Matrix_function_string(size, fn, format) {
|
||||
return _create(size, fn, format);
|
||||
},
|
||||
'Matrix, function': function Matrix_function(size, fn) {
|
||||
return _create(size, fn, 'dense');
|
||||
},
|
||||
'Array, function': function Array_function(size, fn) {
|
||||
return _create(size, fn, 'dense').toArray();
|
||||
},
|
||||
'Array | Matrix, string, function': function Array__Matrix_string_function(size, format, fn) {
|
||||
return _create(size, fn, format);
|
||||
},
|
||||
'Array | Matrix, string, string, function': function Array__Matrix_string_string_function(size, format, datatype, fn) {
|
||||
return _create(size, fn, format, datatype);
|
||||
}
|
||||
});
|
||||
function _create(size, fn, format, datatype) {
|
||||
var m;
|
||||
if (datatype !== undefined) {
|
||||
m = matrix(format, datatype);
|
||||
} else {
|
||||
m = matrix(format);
|
||||
}
|
||||
m.resize(size);
|
||||
m.forEach(function (_, index) {
|
||||
var val = fn(index);
|
||||
if (isZero(val)) return;
|
||||
m.set(index, val);
|
||||
});
|
||||
return m;
|
||||
}
|
||||
});
|
||||
76
node_modules/mathjs/lib/esm/function/matrix/matrixFromRows.js
generated
vendored
Normal file
76
node_modules/mathjs/lib/esm/function/matrix/matrixFromRows.js
generated
vendored
Normal file
@@ -0,0 +1,76 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'matrixFromRows';
|
||||
var dependencies = ['typed', 'matrix', 'flatten', 'size'];
|
||||
export var createMatrixFromRows = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array(arr) {
|
||||
return _createArray(arr);
|
||||
},
|
||||
'...Matrix': function Matrix(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.');
|
||||
var N = checkVectorTypeAndReturnLength(arr[0]);
|
||||
var result = [];
|
||||
for (var row of arr) {
|
||||
var 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) {
|
||||
var 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.');
|
||||
}
|
||||
}
|
||||
});
|
||||
123
node_modules/mathjs/lib/esm/function/matrix/ones.js
generated
vendored
Normal file
123
node_modules/mathjs/lib/esm/function/matrix/ones.js
generated
vendored
Normal file
@@ -0,0 +1,123 @@
|
||||
import { isBigNumber } from '../../utils/is.js';
|
||||
import { isInteger } from '../../utils/number.js';
|
||||
import { resize } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'ones';
|
||||
var dependencies = ['typed', 'config', 'matrix', 'BigNumber'];
|
||||
export var createOnes = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 number__BigNumber__string(size) {
|
||||
var last = size[size.length - 1];
|
||||
if (typeof last === 'string') {
|
||||
var format = size.pop();
|
||||
return _ones(size, format);
|
||||
} else if (config.matrix === 'Array') {
|
||||
return _ones(size);
|
||||
} else {
|
||||
return _ones(size, 'default');
|
||||
}
|
||||
},
|
||||
Array: _ones,
|
||||
Matrix: function Matrix(size) {
|
||||
var format = size.storage();
|
||||
return _ones(size.valueOf(), format);
|
||||
},
|
||||
'Array | Matrix, string': function Array__Matrix_string(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) {
|
||||
var hasBigNumbers = _normalize(size);
|
||||
var defaultValue = hasBigNumbers ? new BigNumber(1) : 1;
|
||||
_validate(size);
|
||||
if (format) {
|
||||
// return a matrix
|
||||
var m = matrix(format);
|
||||
if (size.length > 0) {
|
||||
return m.resize(size, defaultValue);
|
||||
}
|
||||
return m;
|
||||
} else {
|
||||
// return an Array
|
||||
var arr = [];
|
||||
if (size.length > 0) {
|
||||
return resize(arr, size, defaultValue);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
}
|
||||
|
||||
// replace BigNumbers with numbers, returns true if size contained BigNumbers
|
||||
function _normalize(size) {
|
||||
var hasBigNumbers = false;
|
||||
size.forEach(function (value, index, arr) {
|
||||
if (isBigNumber(value)) {
|
||||
hasBigNumbers = true;
|
||||
arr[index] = value.toNumber();
|
||||
}
|
||||
});
|
||||
return hasBigNumbers;
|
||||
}
|
||||
|
||||
// validate arguments
|
||||
function _validate(size) {
|
||||
size.forEach(function (value) {
|
||||
if (typeof value !== 'number' || !isInteger(value) || value < 0) {
|
||||
throw new Error('Parameters in function ones must be positive integers');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
143
node_modules/mathjs/lib/esm/function/matrix/partitionSelect.js
generated
vendored
Normal file
143
node_modules/mathjs/lib/esm/function/matrix/partitionSelect.js
generated
vendored
Normal file
@@ -0,0 +1,143 @@
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
import { isInteger } from '../../utils/number.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'partitionSelect';
|
||||
var dependencies = ['typed', 'isNumeric', 'isNaN', 'compare'];
|
||||
export var createPartitionSelect = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
typed,
|
||||
isNumeric,
|
||||
isNaN,
|
||||
compare
|
||||
} = _ref;
|
||||
var asc = compare;
|
||||
var 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 Array__Matrix_number(x, k) {
|
||||
return _partitionSelect(x, k, asc);
|
||||
},
|
||||
'Array | Matrix, number, string': function Array__Matrix_number_string(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 (!isInteger(k) || k < 0) {
|
||||
throw new Error('k must be a non-negative integer');
|
||||
}
|
||||
if (isMatrix(x)) {
|
||||
var 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 (var i = 0; i < arr.length; i++) {
|
||||
if (isNumeric(arr[i]) && isNaN(arr[i])) {
|
||||
return arr[i]; // return NaN
|
||||
}
|
||||
}
|
||||
var from = 0;
|
||||
var to = arr.length - 1;
|
||||
|
||||
// if from == to we reached the kth element
|
||||
while (from < to) {
|
||||
var r = from;
|
||||
var w = to;
|
||||
var 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
|
||||
var 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];
|
||||
}
|
||||
});
|
||||
179
node_modules/mathjs/lib/esm/function/matrix/pinv.js
generated
vendored
Normal file
179
node_modules/mathjs/lib/esm/function/matrix/pinv.js
generated
vendored
Normal file
@@ -0,0 +1,179 @@
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
import { arraySize } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { format } from '../../utils/string.js';
|
||||
import { clone } from '../../utils/object.js';
|
||||
var name = 'pinv';
|
||||
var dependencies = ['typed', 'matrix', 'inv', 'deepEqual', 'equal', 'dotDivide', 'dot', 'ctranspose', 'divideScalar', 'multiply', 'add', 'Complex'];
|
||||
export var createPinv = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
typed,
|
||||
matrix,
|
||||
inv,
|
||||
deepEqual,
|
||||
equal,
|
||||
dotDivide,
|
||||
dot,
|
||||
ctranspose,
|
||||
divideScalar,
|
||||
multiply,
|
||||
add,
|
||||
Complex
|
||||
} = _ref;
|
||||
/**
|
||||
* Calculate the Moore–Penrose 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 Array__Matrix(x) {
|
||||
var size = isMatrix(x) ? x.size() : 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
|
||||
var rows = size[0];
|
||||
var 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 (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: ' + format(size) + ')');
|
||||
}
|
||||
},
|
||||
any: function any(x) {
|
||||
// scalar
|
||||
if (equal(x, 0)) return clone(x); // zero
|
||||
return divideScalar(1, x);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Calculate the Moore–Penrose 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) {
|
||||
var {
|
||||
C,
|
||||
F
|
||||
} = _rankFact(mat, rows, cols); // TODO: Use SVD instead (may improve precision)
|
||||
var Cpinv = multiply(inv(multiply(ctranspose(C), C)), ctranspose(C));
|
||||
var 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) {
|
||||
var M = clone(mat);
|
||||
var lead = 0;
|
||||
for (var r = 0; r < rows; r++) {
|
||||
if (cols <= lead) {
|
||||
return M;
|
||||
}
|
||||
var 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]];
|
||||
var val = M[r][lead];
|
||||
for (var j = 0; j < cols; j++) {
|
||||
M[r][j] = dotDivide(M[r][j], val);
|
||||
}
|
||||
for (var _i = 0; _i < rows; _i++) {
|
||||
if (_i === r) continue;
|
||||
val = M[_i][lead];
|
||||
for (var _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) {
|
||||
var rref = _rref(mat, rows, cols);
|
||||
var C = mat.map((_, i) => _.filter((_, j) => j < rows && !_isZero(dot(rref[j], rref[j]))));
|
||||
var 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)));
|
||||
}
|
||||
});
|
||||
182
node_modules/mathjs/lib/esm/function/matrix/range.js
generated
vendored
Normal file
182
node_modules/mathjs/lib/esm/function/matrix/range.js
generated
vendored
Normal file
@@ -0,0 +1,182 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { noBignumber, noMatrix } from '../../utils/noop.js';
|
||||
var name = 'range';
|
||||
var dependencies = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq', 'add', 'isPositive'];
|
||||
export var createRange = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 number_number(start, end) {
|
||||
return _out(_range(start, end, 1, false));
|
||||
},
|
||||
'number, number, number': function number_number_number(start, end, step) {
|
||||
return _out(_range(start, end, step, false));
|
||||
},
|
||||
'number, number, boolean': function number_number_boolean(start, end, includeEnd) {
|
||||
return _out(_range(start, end, 1, includeEnd));
|
||||
},
|
||||
'number, number, number, boolean': function number_number_number_boolean(start, end, step, includeEnd) {
|
||||
return _out(_range(start, end, step, includeEnd));
|
||||
},
|
||||
'BigNumber, BigNumber': function BigNumber_BigNumber(start, end) {
|
||||
var BigNumber = start.constructor;
|
||||
return _out(_range(start, end, new BigNumber(1), false));
|
||||
},
|
||||
'BigNumber, BigNumber, BigNumber': function BigNumber_BigNumber_BigNumber(start, end, step) {
|
||||
return _out(_range(start, end, step, false));
|
||||
},
|
||||
'BigNumber, BigNumber, boolean': function BigNumber_BigNumber_boolean(start, end, includeEnd) {
|
||||
var BigNumber = start.constructor;
|
||||
return _out(_range(start, end, new BigNumber(1), includeEnd));
|
||||
},
|
||||
'BigNumber, BigNumber, BigNumber, boolean': function BigNumber_BigNumber_BigNumber_boolean(start, end, step, includeEnd) {
|
||||
return _out(_range(start, end, step, includeEnd));
|
||||
},
|
||||
'Unit, Unit, Unit': function Unit_Unit_Unit(start, end, step) {
|
||||
return _out(_range(start, end, step, false));
|
||||
},
|
||||
'Unit, Unit, Unit, boolean': function Unit_Unit_Unit_boolean(start, end, step, includeEnd) {
|
||||
return _out(_range(start, end, step, includeEnd));
|
||||
}
|
||||
});
|
||||
function _out(arr) {
|
||||
if (config.matrix === 'Matrix') {
|
||||
return matrix ? matrix(arr) : noMatrix();
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
function _strRange(str, includeEnd) {
|
||||
var r = _parse(str);
|
||||
if (!r) {
|
||||
throw new SyntaxError('String "' + str + '" is no valid range');
|
||||
}
|
||||
if (config.number === 'BigNumber') {
|
||||
if (bignumber === undefined) {
|
||||
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) {
|
||||
var array = [];
|
||||
var ongoing = isPositive(step) ? includeEnd ? smallerEq : smaller : includeEnd ? largerEq : larger;
|
||||
var 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) {
|
||||
var args = str.split(':');
|
||||
|
||||
// number
|
||||
var nums = args.map(function (arg) {
|
||||
// use Number and not parseFloat as Number returns NaN on invalid garbage in the string
|
||||
return Number(arg);
|
||||
});
|
||||
var 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;
|
||||
}
|
||||
}
|
||||
});
|
||||
63
node_modules/mathjs/lib/esm/function/matrix/reshape.js
generated
vendored
Normal file
63
node_modules/mathjs/lib/esm/function/matrix/reshape.js
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
import { reshape as arrayReshape } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'reshape';
|
||||
var dependencies = ['typed', 'isInteger', 'matrix'];
|
||||
export var createReshape = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Matrix_Array(x, sizes) {
|
||||
return x.reshape(sizes, true);
|
||||
},
|
||||
'Array, Array': function Array_Array(x, sizes) {
|
||||
sizes.forEach(function (size) {
|
||||
if (!isInteger(size)) {
|
||||
throw new TypeError('Invalid size for dimension: ' + size);
|
||||
}
|
||||
});
|
||||
return arrayReshape(x, sizes);
|
||||
}
|
||||
});
|
||||
});
|
||||
120
node_modules/mathjs/lib/esm/function/matrix/resize.js
generated
vendored
Normal file
120
node_modules/mathjs/lib/esm/function/matrix/resize.js
generated
vendored
Normal file
@@ -0,0 +1,120 @@
|
||||
import { isBigNumber, isMatrix } from '../../utils/is.js';
|
||||
import { DimensionError } from '../../error/DimensionError.js';
|
||||
import { ArgumentsError } from '../../error/ArgumentsError.js';
|
||||
import { isInteger } from '../../utils/number.js';
|
||||
import { format } from '../../utils/string.js';
|
||||
import { clone } from '../../utils/object.js';
|
||||
import { resize as arrayResize } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'resize';
|
||||
var dependencies = ['config', 'matrix'];
|
||||
export var createResize = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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('resize', arguments.length, 2, 3);
|
||||
}
|
||||
if (isMatrix(size)) {
|
||||
size = size.valueOf(); // get Array
|
||||
}
|
||||
if (isBigNumber(size[0])) {
|
||||
// convert bignumbers to numbers
|
||||
size = size.map(function (value) {
|
||||
return !isBigNumber(value) ? value : value.toNumber();
|
||||
});
|
||||
}
|
||||
|
||||
// check x is a Matrix
|
||||
if (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
|
||||
var asMatrix = Array.isArray(x) ? false : config.matrix !== 'Array';
|
||||
if (size.length === 0) {
|
||||
// output a scalar
|
||||
while (Array.isArray(x)) {
|
||||
x = x[0];
|
||||
}
|
||||
return clone(x);
|
||||
} else {
|
||||
// output an array/matrix
|
||||
if (!Array.isArray(x)) {
|
||||
x = [x];
|
||||
}
|
||||
x = clone(x);
|
||||
var res = arrayResize(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(size.length, 1);
|
||||
}
|
||||
var len = size[0];
|
||||
if (typeof len !== 'number' || !isInteger(len)) {
|
||||
throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + format(size) + ')');
|
||||
}
|
||||
if (str.length > len) {
|
||||
return str.substring(0, len);
|
||||
} else if (str.length < len) {
|
||||
var res = str;
|
||||
for (var i = 0, ii = len - str.length; i < ii; i++) {
|
||||
res += defaultChar;
|
||||
}
|
||||
return res;
|
||||
} else {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
});
|
||||
71
node_modules/mathjs/lib/esm/function/matrix/rotate.js
generated
vendored
Normal file
71
node_modules/mathjs/lib/esm/function/matrix/rotate.js
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { arraySize } from '../../utils/array.js';
|
||||
var name = 'rotate';
|
||||
var dependencies = ['typed', 'multiply', 'rotationMatrix'];
|
||||
export var createRotate = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array__number__BigNumber__Complex__Unit(w, theta) {
|
||||
_validateSize(w, 2);
|
||||
var matrixRes = multiply(rotationMatrix(theta), w);
|
||||
return matrixRes.toArray();
|
||||
},
|
||||
'Matrix , number | BigNumber | Complex | Unit': function Matrix__number__BigNumber__Complex__Unit(w, theta) {
|
||||
_validateSize(w, 2);
|
||||
return multiply(rotationMatrix(theta), w);
|
||||
},
|
||||
'Array, number | BigNumber | Complex | Unit, Array | Matrix': function Array_number__BigNumber__Complex__Unit_Array__Matrix(w, theta, v) {
|
||||
_validateSize(w, 3);
|
||||
var matrixRes = multiply(rotationMatrix(theta, v), w);
|
||||
return matrixRes;
|
||||
},
|
||||
'Matrix, number | BigNumber | Complex | Unit, Array | Matrix': function Matrix_number__BigNumber__Complex__Unit_Array__Matrix(w, theta, v) {
|
||||
_validateSize(w, 3);
|
||||
return multiply(rotationMatrix(theta, v), w);
|
||||
}
|
||||
});
|
||||
function _validateSize(v, expectedSize) {
|
||||
var actualSize = Array.isArray(v) ? arraySize(v) : v.size();
|
||||
if (actualSize.length > 2) {
|
||||
throw new RangeError("Vector must be of dimensions 1x".concat(expectedSize));
|
||||
}
|
||||
if (actualSize.length === 2 && actualSize[1] !== 1) {
|
||||
throw new RangeError("Vector must be of dimensions 1x".concat(expectedSize));
|
||||
}
|
||||
if (actualSize[0] !== expectedSize) {
|
||||
throw new RangeError("Vector must be of dimensions 1x".concat(expectedSize));
|
||||
}
|
||||
}
|
||||
});
|
||||
160
node_modules/mathjs/lib/esm/function/matrix/rotationMatrix.js
generated
vendored
Normal file
160
node_modules/mathjs/lib/esm/function/matrix/rotationMatrix.js
generated
vendored
Normal file
@@ -0,0 +1,160 @@
|
||||
import { isBigNumber } from '../../utils/is.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'rotationMatrix';
|
||||
var dependencies = ['typed', 'config', 'multiplyScalar', 'addScalar', 'unaryMinus', 'norm', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix', 'cos', 'sin'];
|
||||
export var createRotationMatrix = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 string(format) {
|
||||
return matrix(format);
|
||||
},
|
||||
'number | BigNumber | Complex | Unit': function number__BigNumber__Complex__Unit(theta) {
|
||||
return _rotationMatrix2x2(theta, config.matrix === 'Matrix' ? 'dense' : undefined);
|
||||
},
|
||||
'number | BigNumber | Complex | Unit, string': function number__BigNumber__Complex__Unit_string(theta, format) {
|
||||
return _rotationMatrix2x2(theta, format);
|
||||
},
|
||||
'number | BigNumber | Complex | Unit, Array': function number__BigNumber__Complex__Unit_Array(theta, v) {
|
||||
var matrixV = matrix(v);
|
||||
_validateVector(matrixV);
|
||||
return _rotationMatrix3x3(theta, matrixV, undefined);
|
||||
},
|
||||
'number | BigNumber | Complex | Unit, Matrix': function number__BigNumber__Complex__Unit_Matrix(theta, v) {
|
||||
_validateVector(v);
|
||||
var storageType = v.storage() || (config.matrix === 'Matrix' ? 'dense' : undefined);
|
||||
return _rotationMatrix3x3(theta, v, storageType);
|
||||
},
|
||||
'number | BigNumber | Complex | Unit, Array, string': function number__BigNumber__Complex__Unit_Array_string(theta, v, format) {
|
||||
var matrixV = matrix(v);
|
||||
_validateVector(matrixV);
|
||||
return _rotationMatrix3x3(theta, matrixV, format);
|
||||
},
|
||||
'number | BigNumber | Complex | Unit, Matrix, string': function number__BigNumber__Complex__Unit_Matrix_string(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) {
|
||||
var Big = isBigNumber(theta);
|
||||
var minusOne = Big ? new BigNumber(-1) : -1;
|
||||
var cosTheta = cos(theta);
|
||||
var sinTheta = sin(theta);
|
||||
var data = [[cosTheta, multiplyScalar(minusOne, sinTheta)], [sinTheta, cosTheta]];
|
||||
return _convertToFormat(data, format);
|
||||
}
|
||||
function _validateVector(v) {
|
||||
var 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 \"".concat(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) {
|
||||
var normV = norm(v);
|
||||
if (normV === 0) {
|
||||
throw new RangeError('Rotation around zero vector');
|
||||
}
|
||||
var Big = isBigNumber(theta) ? BigNumber : null;
|
||||
var one = Big ? new Big(1) : 1;
|
||||
var minusOne = Big ? new Big(-1) : -1;
|
||||
var vx = Big ? new Big(v.get([0]) / normV) : v.get([0]) / normV;
|
||||
var vy = Big ? new Big(v.get([1]) / normV) : v.get([1]) / normV;
|
||||
var vz = Big ? new Big(v.get([2]) / normV) : v.get([2]) / normV;
|
||||
var c = cos(theta);
|
||||
var oneMinusC = addScalar(one, unaryMinus(c));
|
||||
var s = sin(theta);
|
||||
var r11 = addScalar(c, _mul([vx, vx, oneMinusC]));
|
||||
var r12 = addScalar(_mul([vx, vy, oneMinusC]), _mul([minusOne, vz, s]));
|
||||
var r13 = addScalar(_mul([vx, vz, oneMinusC]), _mul([vy, s]));
|
||||
var r21 = addScalar(_mul([vx, vy, oneMinusC]), _mul([vz, s]));
|
||||
var r22 = addScalar(c, _mul([vy, vy, oneMinusC]));
|
||||
var r23 = addScalar(_mul([vy, vz, oneMinusC]), _mul([minusOne, vx, s]));
|
||||
var r31 = addScalar(_mul([vx, vz, oneMinusC]), _mul([minusOne, vy, s]));
|
||||
var r32 = addScalar(_mul([vy, vz, oneMinusC]), _mul([vx, s]));
|
||||
var r33 = addScalar(c, _mul([vz, vz, oneMinusC]));
|
||||
var data = [[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]];
|
||||
return _convertToFormat(data, format);
|
||||
}
|
||||
});
|
||||
59
node_modules/mathjs/lib/esm/function/matrix/row.js
generated
vendored
Normal file
59
node_modules/mathjs/lib/esm/function/matrix/row.js
generated
vendored
Normal file
@@ -0,0 +1,59 @@
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
import { clone } from '../../utils/object.js';
|
||||
import { validateIndex } from '../../utils/array.js';
|
||||
var name = 'row';
|
||||
var dependencies = ['typed', 'Index', 'matrix', 'range'];
|
||||
export var createRow = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array_number(value, row) {
|
||||
return _row(matrix(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');
|
||||
}
|
||||
validateIndex(row, value.size()[0]);
|
||||
var columnRange = range(0, value.size()[1]);
|
||||
var index = new Index(row, columnRange);
|
||||
var result = value.subset(index);
|
||||
return isMatrix(result) ? result : matrix([[result]]);
|
||||
}
|
||||
});
|
||||
48
node_modules/mathjs/lib/esm/function/matrix/size.js
generated
vendored
Normal file
48
node_modules/mathjs/lib/esm/function/matrix/size.js
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
import { arraySize } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
import { noMatrix } from '../../utils/noop.js';
|
||||
var name = 'size';
|
||||
var dependencies = ['typed', 'config', '?matrix'];
|
||||
export var createSize = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Matrix(x) {
|
||||
return x.create(x.size(), 'number');
|
||||
},
|
||||
Array: arraySize,
|
||||
string: function string(x) {
|
||||
return config.matrix === 'Array' ? [x.length] : matrix([x.length], 'dense', 'number');
|
||||
},
|
||||
'number | Complex | BigNumber | Unit | boolean | null': function number__Complex__BigNumber__Unit__boolean__null(x) {
|
||||
// scalar
|
||||
return config.matrix === 'Array' ? [] : matrix ? matrix([], 'dense', 'number') : noMatrix();
|
||||
}
|
||||
});
|
||||
});
|
||||
113
node_modules/mathjs/lib/esm/function/matrix/sort.js
generated
vendored
Normal file
113
node_modules/mathjs/lib/esm/function/matrix/sort.js
generated
vendored
Normal file
@@ -0,0 +1,113 @@
|
||||
import { arraySize as size } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'sort';
|
||||
var dependencies = ['typed', 'matrix', 'compare', 'compareNatural'];
|
||||
export var createSort = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
typed,
|
||||
matrix,
|
||||
compare,
|
||||
compareNatural
|
||||
} = _ref;
|
||||
var compareAsc = compare;
|
||||
var 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 Array(x) {
|
||||
_arrayIsVector(x);
|
||||
return x.sort(compareAsc);
|
||||
},
|
||||
Matrix: function Matrix(x) {
|
||||
_matrixIsVector(x);
|
||||
return matrix(x.toArray().sort(compareAsc), x.storage());
|
||||
},
|
||||
'Array, function': function Array_function(x, _comparator) {
|
||||
_arrayIsVector(x);
|
||||
return x.sort(_comparator);
|
||||
},
|
||||
'Matrix, function': function Matrix_function(x, _comparator) {
|
||||
_matrixIsVector(x);
|
||||
return matrix(x.toArray().sort(_comparator), x.storage());
|
||||
},
|
||||
'Array, string': function Array_string(x, order) {
|
||||
_arrayIsVector(x);
|
||||
return x.sort(_comparator(order));
|
||||
},
|
||||
'Matrix, string': function Matrix_string(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 (size(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');
|
||||
}
|
||||
}
|
||||
});
|
||||
99
node_modules/mathjs/lib/esm/function/matrix/sqrtm.js
generated
vendored
Normal file
99
node_modules/mathjs/lib/esm/function/matrix/sqrtm.js
generated
vendored
Normal file
@@ -0,0 +1,99 @@
|
||||
import { isMatrix } from '../../utils/is.js';
|
||||
import { format } from '../../utils/string.js';
|
||||
import { arraySize } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'sqrtm';
|
||||
var dependencies = ['typed', 'abs', 'add', 'multiply', 'map', 'sqrt', 'subtract', 'inv', 'size', 'max', 'identity'];
|
||||
export var createSqrtm = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
typed,
|
||||
abs,
|
||||
add,
|
||||
multiply,
|
||||
map,
|
||||
sqrt,
|
||||
subtract,
|
||||
inv,
|
||||
size,
|
||||
max,
|
||||
identity
|
||||
} = _ref;
|
||||
var _maxIterations = 1e3;
|
||||
var _tolerance = 1e-6;
|
||||
|
||||
/**
|
||||
* Calculate the principal square root matrix using the Denman–Beavers iterative method
|
||||
*
|
||||
* https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_Denman–Beavers_iteration
|
||||
*
|
||||
* @param {Array | Matrix} A The square matrix `A`
|
||||
* @return {Array | Matrix} The principal square root of matrix `A`
|
||||
* @private
|
||||
*/
|
||||
function _denmanBeavers(A) {
|
||||
var error;
|
||||
var iterations = 0;
|
||||
var Y = A;
|
||||
var Z = identity(size(A));
|
||||
do {
|
||||
var 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 Array__Matrix(A) {
|
||||
var size = isMatrix(A) ? A.size() : 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: ' + format(size) + ')');
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// Two-dimensional Array | Matrix
|
||||
var rows = size[0];
|
||||
var cols = size[1];
|
||||
if (rows === cols) {
|
||||
return _denmanBeavers(A);
|
||||
} else {
|
||||
throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
|
||||
}
|
||||
}
|
||||
default:
|
||||
// Multi dimensional array
|
||||
throw new RangeError('Matrix must be at most two dimensional ' + '(size: ' + format(size) + ')');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
53
node_modules/mathjs/lib/esm/function/matrix/squeeze.js
generated
vendored
Normal file
53
node_modules/mathjs/lib/esm/function/matrix/squeeze.js
generated
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
import { clone } from '../../utils/object.js';
|
||||
import { squeeze as arraySqueeze } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'squeeze';
|
||||
var dependencies = ['typed'];
|
||||
export var createSqueeze = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Array(x) {
|
||||
return arraySqueeze(clone(x));
|
||||
},
|
||||
Matrix: function Matrix(x) {
|
||||
var res = arraySqueeze(x.toArray());
|
||||
// FIXME: return the same type of matrix as the input
|
||||
return Array.isArray(res) ? x.create(res, x.datatype()) : res;
|
||||
},
|
||||
any: function any(x) {
|
||||
// scalar
|
||||
return clone(x);
|
||||
}
|
||||
});
|
||||
});
|
||||
273
node_modules/mathjs/lib/esm/function/matrix/subset.js
generated
vendored
Normal file
273
node_modules/mathjs/lib/esm/function/matrix/subset.js
generated
vendored
Normal file
@@ -0,0 +1,273 @@
|
||||
import { isIndex } from '../../utils/is.js';
|
||||
import { clone } from '../../utils/object.js';
|
||||
import { isEmptyIndex, validateIndex, validateIndexSourceSize } from '../../utils/array.js';
|
||||
import { getSafeProperty, setSafeProperty } from '../../utils/customs.js';
|
||||
import { DimensionError } from '../../error/DimensionError.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'subset';
|
||||
var dependencies = ['typed', 'matrix', 'zeros', 'add'];
|
||||
export var createSubset = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 Matrix_Index(value, index) {
|
||||
if (isEmptyIndex(index)) {
|
||||
return matrix();
|
||||
}
|
||||
validateIndexSourceSize(value, index);
|
||||
return value.subset(index);
|
||||
},
|
||||
'Array, Index': typed.referTo('Matrix, Index', function (subsetRef) {
|
||||
return function (value, index) {
|
||||
var subsetResult = subsetRef(matrix(value), index);
|
||||
return index.isScalar() ? subsetResult : subsetResult.valueOf();
|
||||
};
|
||||
}),
|
||||
'Object, Index': _getObjectProperty,
|
||||
'string, Index': _getSubstring,
|
||||
// set subset
|
||||
'Matrix, Index, any, any': function Matrix_Index_any_any(value, index, replacement, defaultValue) {
|
||||
if (isEmptyIndex(index)) {
|
||||
return value;
|
||||
}
|
||||
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) {
|
||||
var 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;
|
||||
}
|
||||
var 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 (!isIndex(index)) {
|
||||
// TODO: better error message
|
||||
throw new TypeError('Index expected');
|
||||
}
|
||||
if (isEmptyIndex(index)) {
|
||||
return '';
|
||||
}
|
||||
validateIndexSourceSize(Array.from(str), index);
|
||||
if (index.size().length !== 1) {
|
||||
throw new DimensionError(index.size().length, 1);
|
||||
}
|
||||
|
||||
// validate whether the range is out of range
|
||||
var strLen = str.length;
|
||||
validateIndex(index.min()[0], strLen);
|
||||
validateIndex(index.max()[0], strLen);
|
||||
var range = index.dimension(0);
|
||||
var 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 (isEmptyIndex(index)) {
|
||||
return str;
|
||||
}
|
||||
validateIndexSourceSize(Array.from(str), index);
|
||||
if (index.size().length !== 1) {
|
||||
throw new 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 = ' ';
|
||||
}
|
||||
var range = index.dimension(0);
|
||||
var len = range.size()[0];
|
||||
if (len !== replacement.length) {
|
||||
throw new DimensionError(range.size()[0], replacement.length);
|
||||
}
|
||||
|
||||
// validate whether the range is out of range
|
||||
var strLen = str.length;
|
||||
validateIndex(index.min()[0]);
|
||||
validateIndex(index.max()[0]);
|
||||
|
||||
// copy the string into an array with characters
|
||||
var chars = [];
|
||||
for (var 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 (var _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 (isEmptyIndex(index)) {
|
||||
return undefined;
|
||||
}
|
||||
if (index.size().length !== 1) {
|
||||
throw new DimensionError(index.size(), 1);
|
||||
}
|
||||
var key = index.dimension(0);
|
||||
if (typeof key !== 'string') {
|
||||
throw new TypeError('String expected as index to retrieve an object property');
|
||||
}
|
||||
return 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 (isEmptyIndex(index)) {
|
||||
return object;
|
||||
}
|
||||
if (index.size().length !== 1) {
|
||||
throw new DimensionError(index.size(), 1);
|
||||
}
|
||||
var 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
|
||||
var updated = clone(object);
|
||||
setSafeProperty(updated, key, replacement);
|
||||
return updated;
|
||||
}
|
||||
128
node_modules/mathjs/lib/esm/function/matrix/trace.js
generated
vendored
Normal file
128
node_modules/mathjs/lib/esm/function/matrix/trace.js
generated
vendored
Normal file
@@ -0,0 +1,128 @@
|
||||
import { clone } from '../../utils/object.js';
|
||||
import { format } from '../../utils/string.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'trace';
|
||||
var dependencies = ['typed', 'matrix', 'add'];
|
||||
export var createTrace = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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: clone
|
||||
});
|
||||
function _denseTrace(m) {
|
||||
// matrix size & data
|
||||
var size = m._size;
|
||||
var data = m._data;
|
||||
|
||||
// process dimensions
|
||||
switch (size.length) {
|
||||
case 1:
|
||||
// vector
|
||||
if (size[0] === 1) {
|
||||
// return data[0]
|
||||
return clone(data[0]);
|
||||
}
|
||||
throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
|
||||
case 2:
|
||||
{
|
||||
// two dimensional
|
||||
var rows = size[0];
|
||||
var cols = size[1];
|
||||
if (rows === cols) {
|
||||
// calulate sum
|
||||
var sum = 0;
|
||||
// loop diagonal
|
||||
for (var i = 0; i < rows; i++) {
|
||||
sum = add(sum, data[i][i]);
|
||||
}
|
||||
// return trace
|
||||
return sum;
|
||||
} else {
|
||||
throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
|
||||
}
|
||||
}
|
||||
default:
|
||||
// multi dimensional
|
||||
throw new RangeError('Matrix must be two dimensional (size: ' + format(size) + ')');
|
||||
}
|
||||
}
|
||||
function _sparseTrace(m) {
|
||||
// matrix arrays
|
||||
var values = m._values;
|
||||
var index = m._index;
|
||||
var ptr = m._ptr;
|
||||
var size = m._size;
|
||||
// check dimensions
|
||||
var rows = size[0];
|
||||
var columns = size[1];
|
||||
// matrix must be square
|
||||
if (rows === columns) {
|
||||
// calulate sum
|
||||
var sum = 0;
|
||||
// check we have data (avoid looping columns)
|
||||
if (values.length > 0) {
|
||||
// loop columns
|
||||
for (var j = 0; j < columns; j++) {
|
||||
// k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
|
||||
var k0 = ptr[j];
|
||||
var k1 = ptr[j + 1];
|
||||
// loop k within [k0, k1[
|
||||
for (var k = k0; k < k1; k++) {
|
||||
// row index
|
||||
var 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: ' + format(size) + ')');
|
||||
}
|
||||
});
|
||||
160
node_modules/mathjs/lib/esm/function/matrix/transpose.js
generated
vendored
Normal file
160
node_modules/mathjs/lib/esm/function/matrix/transpose.js
generated
vendored
Normal file
@@ -0,0 +1,160 @@
|
||||
import { clone } from '../../utils/object.js';
|
||||
import { format } from '../../utils/string.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'transpose';
|
||||
var dependencies = ['typed', 'matrix'];
|
||||
export var createTranspose = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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: clone // scalars
|
||||
});
|
||||
function transposeMatrix(x) {
|
||||
// matrix size
|
||||
var size = x.size();
|
||||
|
||||
// result
|
||||
var c;
|
||||
|
||||
// process dimensions
|
||||
switch (size.length) {
|
||||
case 1:
|
||||
// vector
|
||||
c = x.clone();
|
||||
break;
|
||||
case 2:
|
||||
{
|
||||
// rows and columns
|
||||
var rows = size[0];
|
||||
var columns = size[1];
|
||||
|
||||
// check columns
|
||||
if (columns === 0) {
|
||||
// throw exception
|
||||
throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + 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: ' + format(size) + ')');
|
||||
}
|
||||
return c;
|
||||
}
|
||||
function _denseTranspose(m, rows, columns) {
|
||||
// matrix array
|
||||
var data = m._data;
|
||||
// transposed matrix data
|
||||
var transposed = [];
|
||||
var transposedRow;
|
||||
// loop columns
|
||||
for (var j = 0; j < columns; j++) {
|
||||
// initialize row
|
||||
transposedRow = transposed[j] = [];
|
||||
// loop rows
|
||||
for (var i = 0; i < rows; i++) {
|
||||
// set data
|
||||
transposedRow[i] = clone(data[i][j]);
|
||||
}
|
||||
}
|
||||
// return matrix
|
||||
return m.createDenseMatrix({
|
||||
data: transposed,
|
||||
size: [columns, rows],
|
||||
datatype: m._datatype
|
||||
});
|
||||
}
|
||||
function _sparseTranspose(m, rows, columns) {
|
||||
// matrix arrays
|
||||
var values = m._values;
|
||||
var index = m._index;
|
||||
var ptr = m._ptr;
|
||||
// result matrices
|
||||
var cvalues = values ? [] : undefined;
|
||||
var cindex = [];
|
||||
var cptr = [];
|
||||
// row counts
|
||||
var w = [];
|
||||
for (var x = 0; x < rows; x++) {
|
||||
w[x] = 0;
|
||||
}
|
||||
// vars
|
||||
var 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
|
||||
var sum = 0;
|
||||
// initialize cptr with the cummulative sum of row counts
|
||||
for (var 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 (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
|
||||
// C values & index
|
||||
var 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] = clone(values[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// return matrix
|
||||
return m.createSparseMatrix({
|
||||
values: cvalues,
|
||||
index: cindex,
|
||||
ptr: cptr,
|
||||
size: [columns, rows],
|
||||
datatype: m._datatype
|
||||
});
|
||||
}
|
||||
});
|
||||
123
node_modules/mathjs/lib/esm/function/matrix/zeros.js
generated
vendored
Normal file
123
node_modules/mathjs/lib/esm/function/matrix/zeros.js
generated
vendored
Normal file
@@ -0,0 +1,123 @@
|
||||
import { isBigNumber } from '../../utils/is.js';
|
||||
import { isInteger } from '../../utils/number.js';
|
||||
import { resize } from '../../utils/array.js';
|
||||
import { factory } from '../../utils/factory.js';
|
||||
var name = 'zeros';
|
||||
var dependencies = ['typed', 'config', 'matrix', 'BigNumber'];
|
||||
export var createZeros = /* #__PURE__ */factory(name, dependencies, _ref => {
|
||||
var {
|
||||
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 number__BigNumber__string(size) {
|
||||
var last = size[size.length - 1];
|
||||
if (typeof last === 'string') {
|
||||
var format = size.pop();
|
||||
return _zeros(size, format);
|
||||
} else if (config.matrix === 'Array') {
|
||||
return _zeros(size);
|
||||
} else {
|
||||
return _zeros(size, 'default');
|
||||
}
|
||||
},
|
||||
Array: _zeros,
|
||||
Matrix: function Matrix(size) {
|
||||
var format = size.storage();
|
||||
return _zeros(size.valueOf(), format);
|
||||
},
|
||||
'Array | Matrix, string': function Array__Matrix_string(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) {
|
||||
var hasBigNumbers = _normalize(size);
|
||||
var defaultValue = hasBigNumbers ? new BigNumber(0) : 0;
|
||||
_validate(size);
|
||||
if (format) {
|
||||
// return a matrix
|
||||
var m = matrix(format);
|
||||
if (size.length > 0) {
|
||||
return m.resize(size, defaultValue);
|
||||
}
|
||||
return m;
|
||||
} else {
|
||||
// return an Array
|
||||
var arr = [];
|
||||
if (size.length > 0) {
|
||||
return resize(arr, size, defaultValue);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
}
|
||||
|
||||
// replace BigNumbers with numbers, returns true if size contained BigNumbers
|
||||
function _normalize(size) {
|
||||
var hasBigNumbers = false;
|
||||
size.forEach(function (value, index, arr) {
|
||||
if (isBigNumber(value)) {
|
||||
hasBigNumbers = true;
|
||||
arr[index] = value.toNumber();
|
||||
}
|
||||
});
|
||||
return hasBigNumbers;
|
||||
}
|
||||
|
||||
// validate arguments
|
||||
function _validate(size) {
|
||||
size.forEach(function (value) {
|
||||
if (typeof value !== '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?
|
||||
Reference in New Issue
Block a user