feat:node-modules

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

View File

@@ -0,0 +1,379 @@
import { clone } from '../../../utils/object.js';
import { factory } from '../../../utils/factory.js';
var name = 'lup';
var dependencies = ['typed', 'matrix', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'larger', 'equalScalar', 'unaryMinus', 'DenseMatrix', 'SparseMatrix', 'Spa'];
export var createLup = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
abs,
addScalar,
divideScalar,
multiplyScalar,
subtractScalar,
larger,
equalScalar,
unaryMinus,
DenseMatrix,
SparseMatrix,
Spa
} = _ref;
/**
* Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a
* row permutation vector `p` where `A[p,:] = L * U`
*
* Syntax:
*
* math.lup(A)
*
* Example:
*
* const m = [[2, 1], [1, 4]]
* const r = math.lup(m)
* // r = {
* // L: [[1, 0], [0.5, 1]],
* // U: [[2, 1], [0, 3.5]],
* // P: [0, 1]
* // }
*
* See also:
*
* slu, lsolve, lusolve, usolve
*
* @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition.
*
* @return {{L: Array | Matrix, U: Array | Matrix, P: Array.<number>}} The lower triangular matrix, the upper triangular matrix and the permutation matrix.
*/
return typed(name, {
DenseMatrix: function DenseMatrix(m) {
return _denseLUP(m);
},
SparseMatrix: function SparseMatrix(m) {
return _sparseLUP(m);
},
Array: function Array(a) {
// create dense matrix from array
var m = matrix(a);
// lup, use matrix implementation
var r = _denseLUP(m);
// result
return {
L: r.L.valueOf(),
U: r.U.valueOf(),
p: r.p
};
}
});
function _denseLUP(m) {
// rows & columns
var rows = m._size[0];
var columns = m._size[1];
// minimum rows and columns
var n = Math.min(rows, columns);
// matrix array, clone original data
var data = clone(m._data);
// l matrix arrays
var ldata = [];
var lsize = [rows, n];
// u matrix arrays
var udata = [];
var usize = [n, columns];
// vars
var i, j, k;
// permutation vector
var p = [];
for (i = 0; i < rows; i++) {
p[i] = i;
}
// loop columns
for (j = 0; j < columns; j++) {
// skip first column in upper triangular matrix
if (j > 0) {
// loop rows
for (i = 0; i < rows; i++) {
// min i,j
var min = Math.min(i, j);
// v[i, j]
var s = 0;
// loop up to min
for (k = 0; k < min; k++) {
// s = l[i, k] - data[k, j]
s = addScalar(s, multiplyScalar(data[i][k], data[k][j]));
}
data[i][j] = subtractScalar(data[i][j], s);
}
}
// row with larger value in cvector, row >= j
var pi = j;
var pabsv = 0;
var vjj = 0;
// loop rows
for (i = j; i < rows; i++) {
// data @ i, j
var v = data[i][j];
// absolute value
var absv = abs(v);
// value is greater than pivote value
if (larger(absv, pabsv)) {
// store row
pi = i;
// update max value
pabsv = absv;
// value @ [j, j]
vjj = v;
}
}
// swap rows (j <-> pi)
if (j !== pi) {
// swap values j <-> pi in p
p[j] = [p[pi], p[pi] = p[j]][0];
// swap j <-> pi in data
DenseMatrix._swapRows(j, pi, data);
}
// check column is in lower triangular matrix
if (j < rows) {
// loop rows (lower triangular matrix)
for (i = j + 1; i < rows; i++) {
// value @ i, j
var vij = data[i][j];
if (!equalScalar(vij, 0)) {
// update data
data[i][j] = divideScalar(data[i][j], vjj);
}
}
}
}
// loop columns
for (j = 0; j < columns; j++) {
// loop rows
for (i = 0; i < rows; i++) {
// initialize row in arrays
if (j === 0) {
// check row exists in upper triangular matrix
if (i < columns) {
// U
udata[i] = [];
}
// L
ldata[i] = [];
}
// check we are in the upper triangular matrix
if (i < j) {
// check row exists in upper triangular matrix
if (i < columns) {
// U
udata[i][j] = data[i][j];
}
// check column exists in lower triangular matrix
if (j < rows) {
// L
ldata[i][j] = 0;
}
continue;
}
// diagonal value
if (i === j) {
// check row exists in upper triangular matrix
if (i < columns) {
// U
udata[i][j] = data[i][j];
}
// check column exists in lower triangular matrix
if (j < rows) {
// L
ldata[i][j] = 1;
}
continue;
}
// check row exists in upper triangular matrix
if (i < columns) {
// U
udata[i][j] = 0;
}
// check column exists in lower triangular matrix
if (j < rows) {
// L
ldata[i][j] = data[i][j];
}
}
}
// l matrix
var l = new DenseMatrix({
data: ldata,
size: lsize
});
// u matrix
var u = new DenseMatrix({
data: udata,
size: usize
});
// p vector
var pv = [];
for (i = 0, n = p.length; i < n; i++) {
pv[p[i]] = i;
}
// return matrices
return {
L: l,
U: u,
p: pv,
toString: function toString() {
return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
}
};
}
function _sparseLUP(m) {
// rows & columns
var rows = m._size[0];
var columns = m._size[1];
// minimum rows and columns
var n = Math.min(rows, columns);
// matrix arrays (will not be modified, thanks to permutation vector)
var values = m._values;
var index = m._index;
var ptr = m._ptr;
// l matrix arrays
var lvalues = [];
var lindex = [];
var lptr = [];
var lsize = [rows, n];
// u matrix arrays
var uvalues = [];
var uindex = [];
var uptr = [];
var usize = [n, columns];
// vars
var i, j, k;
// permutation vectors, (current index -> original index) and (original index -> current index)
var pvCo = [];
var pvOc = [];
for (i = 0; i < rows; i++) {
pvCo[i] = i;
pvOc[i] = i;
}
// swap indices in permutation vectors (condition x < y)!
var swapIndeces = function swapIndeces(x, y) {
// find pv indeces getting data from x and y
var kx = pvOc[x];
var ky = pvOc[y];
// update permutation vector current -> original
pvCo[kx] = y;
pvCo[ky] = x;
// update permutation vector original -> current
pvOc[x] = ky;
pvOc[y] = kx;
};
// loop columns
var _loop = function _loop() {
// sparse accumulator
var spa = new Spa();
// check lower triangular matrix has a value @ column j
if (j < rows) {
// update ptr
lptr.push(lvalues.length);
// first value in j column for lower triangular matrix
lvalues.push(1);
lindex.push(j);
}
// update ptr
uptr.push(uvalues.length);
// k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
var k0 = ptr[j];
var k1 = ptr[j + 1];
// copy column j into sparse accumulator
for (k = k0; k < k1; k++) {
// row
i = index[k];
// copy column values into sparse accumulator (use permutation vector)
spa.set(pvCo[i], values[k]);
}
// skip first column in upper triangular matrix
if (j > 0) {
// loop rows in column j (above diagonal)
spa.forEach(0, j - 1, function (k, vkj) {
// loop rows in column k (L)
SparseMatrix._forEachRow(k, lvalues, lindex, lptr, function (i, vik) {
// check row is below k
if (i > k) {
// update spa value
spa.accumulate(i, unaryMinus(multiplyScalar(vik, vkj)));
}
});
});
}
// row with larger value in spa, row >= j
var pi = j;
var vjj = spa.get(j);
var pabsv = abs(vjj);
// loop values in spa (order by row, below diagonal)
spa.forEach(j + 1, rows - 1, function (x, v) {
// absolute value
var absv = abs(v);
// value is greater than pivote value
if (larger(absv, pabsv)) {
// store row
pi = x;
// update max value
pabsv = absv;
// value @ [j, j]
vjj = v;
}
});
// swap rows (j <-> pi)
if (j !== pi) {
// swap values j <-> pi in L
SparseMatrix._swapRows(j, pi, lsize[1], lvalues, lindex, lptr);
// swap values j <-> pi in U
SparseMatrix._swapRows(j, pi, usize[1], uvalues, uindex, uptr);
// swap values in spa
spa.swap(j, pi);
// update permutation vector (swap values @ j, pi)
swapIndeces(j, pi);
}
// loop values in spa (order by row)
spa.forEach(0, rows - 1, function (x, v) {
// check we are above diagonal
if (x <= j) {
// update upper triangular matrix
uvalues.push(v);
uindex.push(x);
} else {
// update value
v = divideScalar(v, vjj);
// check value is non zero
if (!equalScalar(v, 0)) {
// update lower triangular matrix
lvalues.push(v);
lindex.push(x);
}
}
});
};
for (j = 0; j < columns; j++) {
_loop();
}
// update ptrs
uptr.push(uvalues.length);
lptr.push(lvalues.length);
// return matrices
return {
L: new SparseMatrix({
values: lvalues,
index: lindex,
ptr: lptr,
size: lsize
}),
U: new SparseMatrix({
values: uvalues,
index: uindex,
ptr: uptr,
size: usize
}),
p: pvCo,
toString: function toString() {
return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
}
};
}
});

View File

@@ -0,0 +1,222 @@
import _extends from "@babel/runtime/helpers/extends";
import { factory } from '../../../utils/factory.js';
var name = 'qr';
var dependencies = ['typed', 'matrix', 'zeros', 'identity', 'isZero', 'equal', 'sign', 'sqrt', 'conj', 'unaryMinus', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'complex'];
export var createQr = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
zeros,
identity,
isZero,
equal,
sign,
sqrt,
conj,
unaryMinus,
addScalar,
divideScalar,
multiplyScalar,
subtractScalar,
complex
} = _ref;
/**
* Calculate the Matrix QR decomposition. Matrix `A` is decomposed in
* two matrices (`Q`, `R`) where `Q` is an
* orthogonal matrix and `R` is an upper triangular matrix.
*
* Syntax:
*
* math.qr(A)
*
* Example:
*
* const m = [
* [1, -1, 4],
* [1, 4, -2],
* [1, 4, 2],
* [1, -1, 0]
* ]
* const result = math.qr(m)
* // r = {
* // Q: [
* // [0.5, -0.5, 0.5],
* // [0.5, 0.5, -0.5],
* // [0.5, 0.5, 0.5],
* // [0.5, -0.5, -0.5],
* // ],
* // R: [
* // [2, 3, 2],
* // [0, 5, -2],
* // [0, 0, 4],
* // [0, 0, 0]
* // ]
* // }
*
* See also:
*
* lup, lusolve
*
* @param {Matrix | Array} A A two dimensional matrix or array
* for which to get the QR decomposition.
*
* @return {{Q: Array | Matrix, R: Array | Matrix}} Q: the orthogonal
* matrix and R: the upper triangular matrix
*/
return _extends(typed(name, {
DenseMatrix: function DenseMatrix(m) {
return _denseQR(m);
},
SparseMatrix: function SparseMatrix(m) {
return _sparseQR(m);
},
Array: function Array(a) {
// create dense matrix from array
var m = matrix(a);
// lup, use matrix implementation
var r = _denseQR(m);
// result
return {
Q: r.Q.valueOf(),
R: r.R.valueOf()
};
}
}), {
_denseQRimpl
});
function _denseQRimpl(m) {
// rows & columns (m x n)
var rows = m._size[0]; // m
var cols = m._size[1]; // n
var Q = identity([rows], 'dense');
var Qdata = Q._data;
var R = m.clone();
var Rdata = R._data;
// vars
var i, j, k;
var w = zeros([rows], '');
for (k = 0; k < Math.min(cols, rows); ++k) {
/*
* **k-th Household matrix**
*
* The matrix I - 2*v*transpose(v)
* x = first column of A
* x1 = first element of x
* alpha = x1 / |x1| * |x|
* e1 = tranpose([1, 0, 0, ...])
* u = x - alpha * e1
* v = u / |u|
*
* Household matrix = I - 2 * v * tranpose(v)
*
* * Initially Q = I and R = A.
* * Household matrix is a reflection in a plane normal to v which
* will zero out all but the top right element in R.
* * Appplying reflection to both Q and R will not change product.
* * Repeat this process on the (1,1) minor to get R as an upper
* triangular matrix.
* * Reflections leave the magnitude of the columns of Q unchanged
* so Q remains othoganal.
*
*/
var pivot = Rdata[k][k];
var sgn = unaryMinus(equal(pivot, 0) ? 1 : sign(pivot));
var conjSgn = conj(sgn);
var alphaSquared = 0;
for (i = k; i < rows; i++) {
alphaSquared = addScalar(alphaSquared, multiplyScalar(Rdata[i][k], conj(Rdata[i][k])));
}
var alpha = multiplyScalar(sgn, sqrt(alphaSquared));
if (!isZero(alpha)) {
// first element in vector u
var u1 = subtractScalar(pivot, alpha);
// w = v * u1 / |u| (only elements k to (rows-1) are used)
w[k] = 1;
for (i = k + 1; i < rows; i++) {
w[i] = divideScalar(Rdata[i][k], u1);
}
// tau = - conj(u1 / alpha)
var tau = unaryMinus(conj(divideScalar(u1, alpha)));
var s = void 0;
/*
* tau and w have been choosen so that
*
* 2 * v * tranpose(v) = tau * w * tranpose(w)
*/
/*
* -- calculate R = R - tau * w * tranpose(w) * R --
* Only do calculation with rows k to (rows-1)
* Additionally columns 0 to (k-1) will not be changed by this
* multiplication so do not bother recalculating them
*/
for (j = k; j < cols; j++) {
s = 0.0;
// calculate jth element of [tranpose(w) * R]
for (i = k; i < rows; i++) {
s = addScalar(s, multiplyScalar(conj(w[i]), Rdata[i][j]));
}
// calculate the jth element of [tau * transpose(w) * R]
s = multiplyScalar(s, tau);
for (i = k; i < rows; i++) {
Rdata[i][j] = multiplyScalar(subtractScalar(Rdata[i][j], multiplyScalar(w[i], s)), conjSgn);
}
}
/*
* -- calculate Q = Q - tau * Q * w * transpose(w) --
* Q is a square matrix (rows x rows)
* Only do calculation with columns k to (rows-1)
* Additionally rows 0 to (k-1) will not be changed by this
* multiplication so do not bother recalculating them
*/
for (i = 0; i < rows; i++) {
s = 0.0;
// calculate ith element of [Q * w]
for (j = k; j < rows; j++) {
s = addScalar(s, multiplyScalar(Qdata[i][j], w[j]));
}
// calculate the ith element of [tau * Q * w]
s = multiplyScalar(s, tau);
for (j = k; j < rows; ++j) {
Qdata[i][j] = divideScalar(subtractScalar(Qdata[i][j], multiplyScalar(s, conj(w[j]))), conjSgn);
}
}
}
}
// return matrices
return {
Q,
R,
toString: function toString() {
return 'Q: ' + this.Q.toString() + '\nR: ' + this.R.toString();
}
};
}
function _denseQR(m) {
var ret = _denseQRimpl(m);
var Rdata = ret.R._data;
if (m._data.length > 0) {
var zero = Rdata[0][0].type === 'Complex' ? complex(0) : 0;
for (var i = 0; i < Rdata.length; ++i) {
for (var j = 0; j < i && j < (Rdata[0] || []).length; ++j) {
Rdata[i][j] = zero;
}
}
}
return ret;
}
function _sparseQR(m) {
throw new Error('qr not implemented for sparse matrices yet');
}
});

View File

@@ -0,0 +1,70 @@
import { factory } from '../../../utils/factory.js';
var name = 'schur';
var dependencies = ['typed', 'matrix', 'identity', 'multiply', 'qr', 'norm', 'subtract'];
export var createSchur = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
identity,
multiply,
qr,
norm,
subtract
} = _ref;
/**
*
* Performs a real Schur decomposition of the real matrix A = UTU' where U is orthogonal
* and T is upper quasi-triangular.
* https://en.wikipedia.org/wiki/Schur_decomposition
*
* Syntax:
*
* math.schur(A)
*
* Examples:
*
* const A = [[1, 0], [-4, 3]]
* math.schur(A) // returns {T: [[3, 4], [0, 1]], R: [[0, 1], [-1, 0]]}
*
* See also:
*
* sylvester, lyap, qr
*
* @param {Array | Matrix} A Matrix A
* @return {{U: Array | Matrix, T: Array | Matrix}} Object containing both matrix U and T of the Schur Decomposition A=UTU'
*/
return typed(name, {
Array: function Array(X) {
var r = _schur(matrix(X));
return {
U: r.U.valueOf(),
T: r.T.valueOf()
};
},
Matrix: function Matrix(X) {
return _schur(X);
}
});
function _schur(X) {
var n = X.size()[0];
var A = X;
var U = identity(n);
var k = 0;
var A0;
do {
A0 = A;
var QR = qr(A);
var Q = QR.Q;
var R = QR.R;
A = multiply(R, Q);
U = multiply(U, Q);
if (k++ > 100) {
break;
}
} while (norm(subtract(A, A0)) > 1e-4);
return {
U,
T: A
};
}
});

View File

@@ -0,0 +1,101 @@
import { isInteger } from '../../../utils/number.js';
import { factory } from '../../../utils/factory.js';
import { createCsSqr } from '../sparse/csSqr.js';
import { createCsLu } from '../sparse/csLu.js';
var name = 'slu';
var dependencies = ['typed', 'abs', 'add', 'multiply', 'transpose', 'divideScalar', 'subtract', 'larger', 'largerEq', 'SparseMatrix'];
export var createSlu = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
abs,
add,
multiply,
transpose,
divideScalar,
subtract,
larger,
largerEq,
SparseMatrix
} = _ref;
var csSqr = createCsSqr({
add,
multiply,
transpose
});
var csLu = createCsLu({
abs,
divideScalar,
multiply,
subtract,
larger,
largerEq,
SparseMatrix
});
/**
* Calculate the Sparse Matrix LU decomposition with full pivoting. Sparse Matrix `A` is decomposed in two matrices (`L`, `U`) and two permutation vectors (`pinv`, `q`) where
*
* `P * A * Q = L * U`
*
* Syntax:
*
* math.slu(A, order, threshold)
*
* Examples:
*
* const A = math.sparse([[4,3], [6, 3]])
* math.slu(A, 1, 0.001)
* // returns:
* // {
* // L: [[1, 0], [1.5, 1]]
* // U: [[4, 3], [0, -1.5]]
* // p: [0, 1]
* // q: [0, 1]
* // }
*
* See also:
*
* lup, lsolve, usolve, lusolve
*
* @param {SparseMatrix} A A two dimensional sparse matrix for which to get the LU decomposition.
* @param {Number} order The Symbolic Ordering and Analysis order:
* 0 - Natural ordering, no permutation vector q is returned
* 1 - Matrix must be square, symbolic ordering and analisis is performed on M = A + A'
* 2 - Symbolic ordering and analisis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'.
* This is appropriatefor LU factorization of unsymmetric matrices.
* 3 - Symbolic ordering and analisis is performed on M = A' * A. This is best used for LU factorization is matrix M has no dense rows.
* A dense row is a row with more than 10*sqr(columns) entries.
* @param {Number} threshold Partial pivoting threshold (1 for partial pivoting)
*
* @return {Object} The lower triangular matrix, the upper triangular matrix and the permutation vectors.
*/
return typed(name, {
'SparseMatrix, number, number': function SparseMatrix_number_number(a, order, threshold) {
// verify order
if (!isInteger(order) || order < 0 || order > 3) {
throw new Error('Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]');
}
// verify threshold
if (threshold < 0 || threshold > 1) {
throw new Error('Partial pivoting threshold must be a number from 0 to 1');
}
// perform symbolic ordering and analysis
var s = csSqr(order, a, false);
// perform lu decomposition
var f = csLu(a, s, threshold);
// return decomposition
return {
L: f.L,
U: f.U,
p: f.pinv,
q: s.q,
toString: function toString() {
return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\np: ' + this.p.toString() + (this.q ? '\nq: ' + this.q.toString() : '') + '\n';
}
};
}
});
});

View File

@@ -0,0 +1,519 @@
import { isConstantNode, typeOf } from '../../utils/is.js';
import { factory } from '../../utils/factory.js';
import { safeNumberType } from '../../utils/number.js';
var name = 'derivative';
var dependencies = ['typed', 'config', 'parse', 'simplify', 'equal', 'isZero', 'numeric', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
export var createDerivative = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
parse,
simplify,
equal,
isZero,
numeric,
ConstantNode,
FunctionNode,
OperatorNode,
ParenthesisNode,
SymbolNode
} = _ref;
/**
* Takes the derivative of an expression expressed in parser Nodes.
* The derivative will be taken over the supplied variable in the
* second parameter. If there are multiple variables in the expression,
* it will return a partial derivative.
*
* This uses rules of differentiation which can be found here:
*
* - [Differentiation rules (Wikipedia)](https://en.wikipedia.org/wiki/Differentiation_rules)
*
* Syntax:
*
* math.derivative(expr, variable)
* math.derivative(expr, variable, options)
*
* Examples:
*
* math.derivative('x^2', 'x') // Node '2 * x'
* math.derivative('x^2', 'x', {simplify: false}) // Node '2 * 1 * x ^ (2 - 1)'
* math.derivative('sin(2x)', 'x')) // Node '2 * cos(2 * x)'
* math.derivative('2*x', 'x').evaluate() // number 2
* math.derivative('x^2', 'x').evaluate({x: 4}) // number 8
* const f = math.parse('x^2')
* const x = math.parse('x')
* math.derivative(f, x) // Node {2 * x}
*
* See also:
*
* simplify, parse, evaluate
*
* @param {Node | string} expr The expression to differentiate
* @param {SymbolNode | string} variable The variable over which to differentiate
* @param {{simplify: boolean}} [options]
* There is one option available, `simplify`, which
* is true by default. When false, output will not
* be simplified.
* @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr`
*/
function plainDerivative(expr, variable) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
simplify: true
};
var constNodes = {};
constTag(constNodes, expr, variable.name);
var res = _derivative(expr, constNodes);
return options.simplify ? simplify(res) : res;
}
function parseIdentifier(string) {
var symbol = parse(string);
if (!symbol.isSymbolNode) {
throw new TypeError('Invalid variable. ' + "Cannot parse ".concat(JSON.stringify(string), " into a variable in function derivative"));
}
return symbol;
}
var derivative = typed(name, {
'Node, SymbolNode': plainDerivative,
'Node, SymbolNode, Object': plainDerivative,
'Node, string': (node, symbol) => plainDerivative(node, parseIdentifier(symbol)),
'Node, string, Object': (node, symbol, options) => plainDerivative(node, parseIdentifier(symbol), options)
/* TODO: implement and test syntax with order of derivatives -> implement as an option {order: number}
'Node, SymbolNode, ConstantNode': function (expr, variable, {order}) {
let res = expr
for (let i = 0; i < order; i++) {
let constNodes = {}
constTag(constNodes, expr, variable.name)
res = _derivative(res, constNodes)
}
return res
}
*/
});
derivative._simplify = true;
derivative.toTex = function (deriv) {
return _derivTex.apply(null, deriv.args);
};
// FIXME: move the toTex method of derivative to latex.js. Difficulty is that it relies on parse.
// NOTE: the optional "order" parameter here is currently unused
var _derivTex = typed('_derivTex', {
'Node, SymbolNode': function Node_SymbolNode(expr, x) {
if (isConstantNode(expr) && typeOf(expr.value) === 'string') {
return _derivTex(parse(expr.value).toString(), x.toString(), 1);
} else {
return _derivTex(expr.toTex(), x.toString(), 1);
}
},
'Node, ConstantNode': function Node_ConstantNode(expr, x) {
if (typeOf(x.value) === 'string') {
return _derivTex(expr, parse(x.value));
} else {
throw new Error("The second parameter to 'derivative' is a non-string constant");
}
},
'Node, SymbolNode, ConstantNode': function Node_SymbolNode_ConstantNode(expr, x, order) {
return _derivTex(expr.toString(), x.name, order.value);
},
'string, string, number': function string_string_number(expr, x, order) {
var d;
if (order === 1) {
d = '{d\\over d' + x + '}';
} else {
d = '{d^{' + order + '}\\over d' + x + '^{' + order + '}}';
}
return d + "\\left[".concat(expr, "\\right]");
}
});
/**
* Does a depth-first search on the expression tree to identify what Nodes
* are constants (e.g. 2 + 2), and stores the ones that are constants in
* constNodes. Classification is done as follows:
*
* 1. ConstantNodes are constants.
* 2. If there exists a SymbolNode, of which we are differentiating over,
* in the subtree it is not constant.
*
* @param {Object} constNodes Holds the nodes that are constant
* @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
* @param {string} varName Variable that we are differentiating
* @return {boolean} if node is constant
*/
// TODO: can we rewrite constTag into a pure function?
var constTag = typed('constTag', {
'Object, ConstantNode, string': function Object_ConstantNode_string(constNodes, node) {
constNodes[node] = true;
return true;
},
'Object, SymbolNode, string': function Object_SymbolNode_string(constNodes, node, varName) {
// Treat other variables like constants. For reasoning, see:
// https://en.wikipedia.org/wiki/Partial_derivative
if (node.name !== varName) {
constNodes[node] = true;
return true;
}
return false;
},
'Object, ParenthesisNode, string': function Object_ParenthesisNode_string(constNodes, node, varName) {
return constTag(constNodes, node.content, varName);
},
'Object, FunctionAssignmentNode, string': function Object_FunctionAssignmentNode_string(constNodes, node, varName) {
if (!node.params.includes(varName)) {
constNodes[node] = true;
return true;
}
return constTag(constNodes, node.expr, varName);
},
'Object, FunctionNode | OperatorNode, string': function Object_FunctionNode__OperatorNode_string(constNodes, node, varName) {
if (node.args.length > 0) {
var isConst = constTag(constNodes, node.args[0], varName);
for (var i = 1; i < node.args.length; ++i) {
isConst = constTag(constNodes, node.args[i], varName) && isConst;
}
if (isConst) {
constNodes[node] = true;
return true;
}
}
return false;
}
});
/**
* Applies differentiation rules.
*
* @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
* @param {Object} constNodes Holds the nodes that are constant
* @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr`
*/
var _derivative = typed('_derivative', {
'ConstantNode, Object': function ConstantNode_Object(node) {
return createConstantNode(0);
},
'SymbolNode, Object': function SymbolNode_Object(node, constNodes) {
if (constNodes[node] !== undefined) {
return createConstantNode(0);
}
return createConstantNode(1);
},
'ParenthesisNode, Object': function ParenthesisNode_Object(node, constNodes) {
return new ParenthesisNode(_derivative(node.content, constNodes));
},
'FunctionAssignmentNode, Object': function FunctionAssignmentNode_Object(node, constNodes) {
if (constNodes[node] !== undefined) {
return createConstantNode(0);
}
return _derivative(node.expr, constNodes);
},
'FunctionNode, Object': function FunctionNode_Object(node, constNodes) {
if (constNodes[node] !== undefined) {
return createConstantNode(0);
}
var arg0 = node.args[0];
var arg1;
var div = false; // is output a fraction?
var negative = false; // is output negative?
var funcDerivative;
switch (node.name) {
case 'cbrt':
// d/dx(cbrt(x)) = 1 / (3x^(2/3))
div = true;
funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(3), new OperatorNode('^', 'pow', [arg0, new OperatorNode('/', 'divide', [createConstantNode(2), createConstantNode(3)])])]);
break;
case 'sqrt':
case 'nthRoot':
// d/dx(sqrt(x)) = 1 / (2*sqrt(x))
if (node.args.length === 1) {
div = true;
funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(2), new FunctionNode('sqrt', [arg0])]);
} else if (node.args.length === 2) {
// Rearrange from nthRoot(x, a) -> x^(1/a)
arg1 = new OperatorNode('/', 'divide', [createConstantNode(1), node.args[1]]);
// Is a variable?
constNodes[arg1] = constNodes[node.args[1]];
return _derivative(new OperatorNode('^', 'pow', [arg0, arg1]), constNodes);
}
break;
case 'log10':
arg1 = createConstantNode(10);
/* fall through! */
case 'log':
if (!arg1 && node.args.length === 1) {
// d/dx(log(x)) = 1 / x
funcDerivative = arg0.clone();
div = true;
} else if (node.args.length === 1 && arg1 || node.args.length === 2 && constNodes[node.args[1]] !== undefined) {
// d/dx(log(x, c)) = 1 / (x*ln(c))
funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('log', [arg1 || node.args[1]])]);
div = true;
} else if (node.args.length === 2) {
// d/dx(log(f(x), g(x))) = d/dx(log(f(x)) / log(g(x)))
return _derivative(new OperatorNode('/', 'divide', [new FunctionNode('log', [arg0]), new FunctionNode('log', [node.args[1]])]), constNodes);
}
break;
case 'pow':
if (node.args.length === 2) {
constNodes[arg1] = constNodes[node.args[1]];
// Pass to pow operator node parser
return _derivative(new OperatorNode('^', 'pow', [arg0, node.args[1]]), constNodes);
}
break;
case 'exp':
// d/dx(e^x) = e^x
funcDerivative = new FunctionNode('exp', [arg0.clone()]);
break;
case 'sin':
// d/dx(sin(x)) = cos(x)
funcDerivative = new FunctionNode('cos', [arg0.clone()]);
break;
case 'cos':
// d/dx(cos(x)) = -sin(x)
funcDerivative = new OperatorNode('-', 'unaryMinus', [new FunctionNode('sin', [arg0.clone()])]);
break;
case 'tan':
// d/dx(tan(x)) = sec(x)^2
funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sec', [arg0.clone()]), createConstantNode(2)]);
break;
case 'sec':
// d/dx(sec(x)) = sec(x)tan(x)
funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tan', [arg0.clone()])]);
break;
case 'csc':
// d/dx(csc(x)) = -csc(x)cot(x)
negative = true;
funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('cot', [arg0.clone()])]);
break;
case 'cot':
// d/dx(cot(x)) = -csc(x)^2
negative = true;
funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csc', [arg0.clone()]), createConstantNode(2)]);
break;
case 'asin':
// d/dx(asin(x)) = 1 / sqrt(1 - x^2)
div = true;
funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]);
break;
case 'acos':
// d/dx(acos(x)) = -1 / sqrt(1 - x^2)
div = true;
negative = true;
funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]);
break;
case 'atan':
// d/dx(atan(x)) = 1 / (x^2 + 1)
div = true;
funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]);
break;
case 'asec':
// d/dx(asec(x)) = 1 / (|x|*sqrt(x^2 - 1))
div = true;
funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
break;
case 'acsc':
// d/dx(acsc(x)) = -1 / (|x|*sqrt(x^2 - 1))
div = true;
negative = true;
funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
break;
case 'acot':
// d/dx(acot(x)) = -1 / (x^2 + 1)
div = true;
negative = true;
funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]);
break;
case 'sinh':
// d/dx(sinh(x)) = cosh(x)
funcDerivative = new FunctionNode('cosh', [arg0.clone()]);
break;
case 'cosh':
// d/dx(cosh(x)) = sinh(x)
funcDerivative = new FunctionNode('sinh', [arg0.clone()]);
break;
case 'tanh':
// d/dx(tanh(x)) = sech(x)^2
funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sech', [arg0.clone()]), createConstantNode(2)]);
break;
case 'sech':
// d/dx(sech(x)) = -sech(x)tanh(x)
negative = true;
funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tanh', [arg0.clone()])]);
break;
case 'csch':
// d/dx(csch(x)) = -csch(x)coth(x)
negative = true;
funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('coth', [arg0.clone()])]);
break;
case 'coth':
// d/dx(coth(x)) = -csch(x)^2
negative = true;
funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csch', [arg0.clone()]), createConstantNode(2)]);
break;
case 'asinh':
// d/dx(asinh(x)) = 1 / sqrt(x^2 + 1)
div = true;
funcDerivative = new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]);
break;
case 'acosh':
// d/dx(acosh(x)) = 1 / sqrt(x^2 - 1); XXX potentially only for x >= 1 (the real spectrum)
div = true;
funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]);
break;
case 'atanh':
// d/dx(atanh(x)) = 1 / (1 - x^2)
div = true;
funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]);
break;
case 'asech':
// d/dx(asech(x)) = -1 / (x*sqrt(1 - x^2))
div = true;
negative = true;
funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])])]);
break;
case 'acsch':
// d/dx(acsch(x)) = -1 / (|x|*sqrt(x^2 + 1))
div = true;
negative = true;
funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
break;
case 'acoth':
// d/dx(acoth(x)) = -1 / (1 - x^2)
div = true;
negative = true;
funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]);
break;
case 'abs':
// d/dx(abs(x)) = abs(x)/x
funcDerivative = new OperatorNode('/', 'divide', [new FunctionNode(new SymbolNode('abs'), [arg0.clone()]), arg0.clone()]);
break;
case 'gamma': // Needs digamma function, d/dx(gamma(x)) = gamma(x)digamma(x)
default:
throw new Error('Cannot process function "' + node.name + '" in derivative: ' + 'the function is not supported, undefined, or the number of arguments passed to it are not supported');
}
var op, func;
if (div) {
op = '/';
func = 'divide';
} else {
op = '*';
func = 'multiply';
}
/* Apply chain rule to all functions:
F(x) = f(g(x))
F'(x) = g'(x)*f'(g(x)) */
var chainDerivative = _derivative(arg0, constNodes);
if (negative) {
chainDerivative = new OperatorNode('-', 'unaryMinus', [chainDerivative]);
}
return new OperatorNode(op, func, [chainDerivative, funcDerivative]);
},
'OperatorNode, Object': function OperatorNode_Object(node, constNodes) {
if (constNodes[node] !== undefined) {
return createConstantNode(0);
}
if (node.op === '+') {
// d/dx(sum(f(x)) = sum(f'(x))
return new OperatorNode(node.op, node.fn, node.args.map(function (arg) {
return _derivative(arg, constNodes);
}));
}
if (node.op === '-') {
// d/dx(+/-f(x)) = +/-f'(x)
if (node.isUnary()) {
return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes)]);
}
// Linearity of differentiation, d/dx(f(x) +/- g(x)) = f'(x) +/- g'(x)
if (node.isBinary()) {
return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes), _derivative(node.args[1], constNodes)]);
}
}
if (node.op === '*') {
// d/dx(c*f(x)) = c*f'(x)
var constantTerms = node.args.filter(function (arg) {
return constNodes[arg] !== undefined;
});
if (constantTerms.length > 0) {
var nonConstantTerms = node.args.filter(function (arg) {
return constNodes[arg] === undefined;
});
var nonConstantNode = nonConstantTerms.length === 1 ? nonConstantTerms[0] : new OperatorNode('*', 'multiply', nonConstantTerms);
var newArgs = constantTerms.concat(_derivative(nonConstantNode, constNodes));
return new OperatorNode('*', 'multiply', newArgs);
}
// Product Rule, d/dx(f(x)*g(x)) = f'(x)*g(x) + f(x)*g'(x)
return new OperatorNode('+', 'add', node.args.map(function (argOuter) {
return new OperatorNode('*', 'multiply', node.args.map(function (argInner) {
return argInner === argOuter ? _derivative(argInner, constNodes) : argInner.clone();
}));
}));
}
if (node.op === '/' && node.isBinary()) {
var arg0 = node.args[0];
var arg1 = node.args[1];
// d/dx(f(x) / c) = f'(x) / c
if (constNodes[arg1] !== undefined) {
return new OperatorNode('/', 'divide', [_derivative(arg0, constNodes), arg1]);
}
// Reciprocal Rule, d/dx(c / f(x)) = -c(f'(x)/f(x)^2)
if (constNodes[arg0] !== undefined) {
return new OperatorNode('*', 'multiply', [new OperatorNode('-', 'unaryMinus', [arg0]), new OperatorNode('/', 'divide', [_derivative(arg1, constNodes), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])])]);
}
// Quotient rule, d/dx(f(x) / g(x)) = (f'(x)g(x) - f(x)g'(x)) / g(x)^2
return new OperatorNode('/', 'divide', [new OperatorNode('-', 'subtract', [new OperatorNode('*', 'multiply', [_derivative(arg0, constNodes), arg1.clone()]), new OperatorNode('*', 'multiply', [arg0.clone(), _derivative(arg1, constNodes)])]), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])]);
}
if (node.op === '^' && node.isBinary()) {
var _arg = node.args[0];
var _arg2 = node.args[1];
if (constNodes[_arg] !== undefined) {
// If is secretly constant; 0^f(x) = 1 (in JS), 1^f(x) = 1
if (isConstantNode(_arg) && (isZero(_arg.value) || equal(_arg.value, 1))) {
return createConstantNode(0);
}
// d/dx(c^f(x)) = c^f(x)*ln(c)*f'(x)
return new OperatorNode('*', 'multiply', [node, new OperatorNode('*', 'multiply', [new FunctionNode('log', [_arg.clone()]), _derivative(_arg2.clone(), constNodes)])]);
}
if (constNodes[_arg2] !== undefined) {
if (isConstantNode(_arg2)) {
// If is secretly constant; f(x)^0 = 1 -> d/dx(1) = 0
if (isZero(_arg2.value)) {
return createConstantNode(0);
}
// Ignore exponent; f(x)^1 = f(x)
if (equal(_arg2.value, 1)) {
return _derivative(_arg, constNodes);
}
}
// Elementary Power Rule, d/dx(f(x)^c) = c*f'(x)*f(x)^(c-1)
var powMinusOne = new OperatorNode('^', 'pow', [_arg.clone(), new OperatorNode('-', 'subtract', [_arg2, createConstantNode(1)])]);
return new OperatorNode('*', 'multiply', [_arg2.clone(), new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), powMinusOne])]);
}
// Functional Power Rule, d/dx(f^g) = f^g*[f'*(g/f) + g'ln(f)]
return new OperatorNode('*', 'multiply', [new OperatorNode('^', 'pow', [_arg.clone(), _arg2.clone()]), new OperatorNode('+', 'add', [new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), new OperatorNode('/', 'divide', [_arg2.clone(), _arg.clone()])]), new OperatorNode('*', 'multiply', [_derivative(_arg2, constNodes), new FunctionNode('log', [_arg.clone()])])])]);
}
throw new Error('Cannot process operator "' + node.op + '" in derivative: ' + 'the operator is not supported, undefined, or the number of arguments passed to it are not supported');
}
});
/**
* Helper function to create a constant node with a specific type
* (number, BigNumber, Fraction)
* @param {number} value
* @param {string} [valueType]
* @return {ConstantNode}
*/
function createConstantNode(value, valueType) {
return new ConstantNode(numeric(value, valueType || safeNumberType(String(value), config)));
}
return derivative;
});

View File

@@ -0,0 +1,54 @@
import { factory } from '../../utils/factory.js';
var name = 'leafCount';
var dependencies = ['parse', 'typed'];
export var createLeafCount = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
parse,
typed
} = _ref;
// This does the real work, but we don't have to recurse through
// a typed call if we separate it out
function countLeaves(node) {
var count = 0;
node.forEach(n => {
count += countLeaves(n);
});
return count || 1;
}
/**
* Gives the number of "leaf nodes" in the parse tree of the given expression
* A leaf node is one that has no subexpressions, essentially either a
* symbol or a constant. Note that `5!` has just one leaf, the '5'; the
* unary factorial operator does not add a leaf. On the other hand,
* function symbols do add leaves, so `sin(x)/cos(x)` has four leaves.
*
* The `simplify()` function should generally not increase the `leafCount()`
* of an expression, although currently there is no guarantee that it never
* does so. In many cases, `simplify()` reduces the leaf count.
*
* Syntax:
*
* math.leafCount(expr)
*
* Examples:
*
* math.leafCount('x') // 1
* math.leafCount(math.parse('a*d-b*c')) // 4
* math.leafCount('[a,b;c,d][0,1]') // 6
*
* See also:
*
* simplify
*
* @param {Node|string} expr The expression to count the leaves of
*
* @return {number} The number of leaves of `expr`
*
*/
return typed(name, {
Node: function Node(expr) {
return countLeaves(expr);
}
});
});

52
node_modules/mathjs/lib/esm/function/algebra/lyap.js generated vendored Normal file
View File

@@ -0,0 +1,52 @@
import { factory } from '../../utils/factory.js';
var name = 'lyap';
var dependencies = ['typed', 'matrix', 'sylvester', 'multiply', 'transpose'];
export var createLyap = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
sylvester,
multiply,
transpose
} = _ref;
/**
*
* Solves the Continuous-time Lyapunov equation AP+PA'+Q=0 for P, where
* Q is an input matrix. When Q is symmetric, P is also symmetric. Notice
* that different equivalent definitions exist for the Continuous-time
* Lyapunov equation.
* https://en.wikipedia.org/wiki/Lyapunov_equation
*
* Syntax:
*
* math.lyap(A, Q)
*
* Examples:
*
* const A = [[-2, 0], [1, -4]]
* const Q = [[3, 1], [1, 3]]
* const P = math.lyap(A, Q)
*
* See also:
*
* sylvester, schur
*
* @param {Matrix | Array} A Matrix A
* @param {Matrix | Array} Q Matrix Q
* @return {Matrix | Array} Matrix P solution to the Continuous-time Lyapunov equation AP+PA'=Q
*/
return typed(name, {
'Matrix, Matrix': function Matrix_Matrix(A, Q) {
return sylvester(A, transpose(A), multiply(-1, Q));
},
'Array, Matrix': function Array_Matrix(A, Q) {
return sylvester(matrix(A), transpose(matrix(A)), multiply(-1, Q));
},
'Matrix, Array': function Matrix_Array(A, Q) {
return sylvester(A, transpose(matrix(A)), matrix(multiply(-1, Q)));
},
'Array, Array': function Array_Array(A, Q) {
return sylvester(matrix(A), transpose(matrix(A)), matrix(multiply(-1, Q))).toArray();
}
});
});

View File

@@ -0,0 +1,122 @@
import { factory } from '../../utils/factory.js';
var name = 'polynomialRoot';
var dependencies = ['typed', 'isZero', 'equalScalar', 'add', 'subtract', 'multiply', 'divide', 'sqrt', 'unaryMinus', 'cbrt', 'typeOf', 'im', 're'];
export var createPolynomialRoot = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
isZero,
equalScalar,
add,
subtract,
multiply,
divide,
sqrt,
unaryMinus,
cbrt,
typeOf,
im,
re
} = _ref;
/**
* Finds the numerical values of the distinct roots of a polynomial with real or complex coefficients.
* Currently operates only on linear, quadratic, and cubic polynomials using the standard
* formulas for the roots.
*
* Syntax:
*
* math.polynomialRoot(constant, linearCoeff, quadraticCoeff, cubicCoeff)
*
* Examples:
* // linear
* math.polynomialRoot(6, 3) // [-2]
* math.polynomialRoot(math.complex(6,3), 3) // [-2 - i]
* math.polynomialRoot(math.complex(6,3), math.complex(2,1)) // [-3 + 0i]
* // quadratic
* math.polynomialRoot(2, -3, 1) // [2, 1]
* math.polynomialRoot(8, 8, 2) // [-2]
* math.polynomialRoot(-2, 0, 1) // [1.4142135623730951, -1.4142135623730951]
* math.polynomialRoot(2, -2, 1) // [1 + i, 1 - i]
* math.polynomialRoot(math.complex(1,3), math.complex(-3, -2), 1) // [2 + i, 1 + i]
* // cubic
* math.polynomialRoot(-6, 11, -6, 1) // [1, 3, 2]
* math.polynomialRoot(-8, 0, 0, 1) // [-1 - 1.7320508075688774i, 2, -1 + 1.7320508075688774i]
* math.polynomialRoot(0, 8, 8, 2) // [0, -2]
* math.polynomialRoot(1, 1, 1, 1) // [-1 + 0i, 0 - i, 0 + i]
*
* See also:
* cbrt, sqrt
*
* @param {... number | Complex} coeffs
* The coefficients of the polynomial, starting with with the constant coefficent, followed
* by the linear coefficient and subsequent coefficients of increasing powers.
* @return {Array} The distinct roots of the polynomial
*/
return typed(name, {
'number|Complex, ...number|Complex': (constant, restCoeffs) => {
var coeffs = [constant, ...restCoeffs];
while (coeffs.length > 0 && isZero(coeffs[coeffs.length - 1])) {
coeffs.pop();
}
if (coeffs.length < 2) {
throw new RangeError("Polynomial [".concat(constant, ", ").concat(restCoeffs, "] must have a non-zero non-constant coefficient"));
}
switch (coeffs.length) {
case 2:
// linear
return [unaryMinus(divide(coeffs[0], coeffs[1]))];
case 3:
{
// quadratic
var [c, b, a] = coeffs;
var denom = multiply(2, a);
var d1 = multiply(b, b);
var d2 = multiply(4, a, c);
if (equalScalar(d1, d2)) return [divide(unaryMinus(b), denom)];
var discriminant = sqrt(subtract(d1, d2));
return [divide(subtract(discriminant, b), denom), divide(subtract(unaryMinus(discriminant), b), denom)];
}
case 4:
{
// cubic, cf. https://en.wikipedia.org/wiki/Cubic_equation
var [d, _c, _b, _a] = coeffs;
var _denom = unaryMinus(multiply(3, _a));
var D0_1 = multiply(_b, _b);
var D0_2 = multiply(3, _a, _c);
var D1_1 = add(multiply(2, _b, _b, _b), multiply(27, _a, _a, d));
var D1_2 = multiply(9, _a, _b, _c);
if (equalScalar(D0_1, D0_2) && equalScalar(D1_1, D1_2)) {
return [divide(_b, _denom)];
}
var Delta0 = subtract(D0_1, D0_2);
var Delta1 = subtract(D1_1, D1_2);
var discriminant1 = add(multiply(18, _a, _b, _c, d), multiply(_b, _b, _c, _c));
var discriminant2 = add(multiply(4, _b, _b, _b, d), multiply(4, _a, _c, _c, _c), multiply(27, _a, _a, d, d));
if (equalScalar(discriminant1, discriminant2)) {
return [divide(subtract(multiply(4, _a, _b, _c), add(multiply(9, _a, _a, d), multiply(_b, _b, _b))), multiply(_a, Delta0)),
// simple root
divide(subtract(multiply(9, _a, d), multiply(_b, _c)), multiply(2, Delta0)) // double root
];
}
// OK, we have three distinct roots
var Ccubed;
if (equalScalar(D0_1, D0_2)) {
Ccubed = Delta1;
} else {
Ccubed = divide(add(Delta1, sqrt(subtract(multiply(Delta1, Delta1), multiply(4, Delta0, Delta0, Delta0)))), 2);
}
var allRoots = true;
var rawRoots = cbrt(Ccubed, allRoots).toArray().map(C => divide(add(_b, C, divide(Delta0, C)), _denom));
return rawRoots.map(r => {
if (typeOf(r) === 'Complex' && equalScalar(re(r), re(r) + im(r))) {
return re(r);
}
return r;
});
}
default:
throw new RangeError("only implemented for cubic or lower-order polynomials, not ".concat(coeffs));
}
}
});
});

View File

@@ -0,0 +1,819 @@
import { isInteger } from '../../utils/number.js';
import { factory } from '../../utils/factory.js';
var name = 'rationalize';
var dependencies = ['config', 'typed', 'equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'parse', 'simplifyConstant', 'simplifyCore', 'simplify', '?bignumber', '?fraction', 'mathWithTransform', 'matrix', 'AccessorNode', 'ArrayNode', 'ConstantNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'SymbolNode', 'ParenthesisNode'];
export var createRationalize = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
config,
typed,
equal,
isZero,
add,
subtract,
multiply,
divide,
pow,
parse,
simplifyConstant,
simplifyCore,
simplify,
fraction,
bignumber,
mathWithTransform,
matrix,
AccessorNode,
ArrayNode,
ConstantNode,
FunctionNode,
IndexNode,
ObjectNode,
OperatorNode,
SymbolNode,
ParenthesisNode
} = _ref;
/**
* Transform a rationalizable expression in a rational fraction.
* If rational fraction is one variable polynomial then converts
* the numerator and denominator in canonical form, with decreasing
* exponents, returning the coefficients of numerator.
*
* Syntax:
*
* math.rationalize(expr)
* math.rationalize(expr, detailed)
* math.rationalize(expr, scope)
* math.rationalize(expr, scope, detailed)
*
* Examples:
*
* math.rationalize('sin(x)+y')
* // Error: There is an unsolved function call
* math.rationalize('2x/y - y/(x+1)')
* // (2*x^2-y^2+2*x)/(x*y+y)
* math.rationalize('(2x+1)^6')
* // 64*x^6+192*x^5+240*x^4+160*x^3+60*x^2+12*x+1
* math.rationalize('2x/( (2x-1) / (3x+2) ) - 5x/ ( (3x+4) / (2x^2-5) ) + 3')
* // -20*x^4+28*x^3+104*x^2+6*x-12)/(6*x^2+5*x-4)
* math.rationalize('x/(1-x)/(x-2)/(x-3)/(x-4) + 2x/ ( (1-2x)/(2-3x) )/ ((3-4x)/(4-5x) )') =
* // (-30*x^7+344*x^6-1506*x^5+3200*x^4-3472*x^3+1846*x^2-381*x)/
* // (-8*x^6+90*x^5-383*x^4+780*x^3-797*x^2+390*x-72)
*
* math.rationalize('x+x+x+y',{y:1}) // 3*x+1
* math.rationalize('x+x+x+y',{}) // 3*x+y
*
* const ret = math.rationalize('x+x+x+y',{},true)
* // ret.expression=3*x+y, ret.variables = ["x","y"]
* const ret = math.rationalize('-2+5x^2',{},true)
* // ret.expression=5*x^2-2, ret.variables = ["x"], ret.coefficients=[-2,0,5]
*
* See also:
*
* simplify
*
* @param {Node|string} expr The expression to check if is a polynomial expression
* @param {Object|boolean} optional scope of expression or true for already evaluated rational expression at input
* @param {Boolean} detailed optional True if return an object, false if return expression node (default)
*
* @return {Object | Node} The rational polynomial of `expr` or an object
* `{expression, numerator, denominator, variables, coefficients}`, where
* `expression` is a `Node` with the node simplified expression,
* `numerator` is a `Node` with the simplified numerator of expression,
* `denominator` is a `Node` or `boolean` with the simplified denominator or `false` (if there is no denominator),
* `variables` is an array with variable names,
* and `coefficients` is an array with coefficients of numerator sorted by increased exponent
* {Expression Node} node simplified expression
*
*/
function _rationalize(expr) {
var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var detailed = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var setRules = rulesRationalize(); // Rules for change polynomial in near canonical form
var polyRet = polynomial(expr, scope, true, setRules.firstRules); // Check if expression is a rationalizable polynomial
var nVars = polyRet.variables.length;
var noExactFractions = {
exactFractions: false
};
var withExactFractions = {
exactFractions: true
};
expr = polyRet.expression;
if (nVars >= 1) {
// If expression in not a constant
expr = expandPower(expr); // First expand power of polynomials (cannot be made from rules!)
var sBefore; // Previous expression
var rules;
var eDistrDiv = true;
var redoInic = false;
// Apply the initial rules, including succ div rules:
expr = simplify(expr, setRules.firstRules, {}, noExactFractions);
var s;
while (true) {
// Alternate applying successive division rules and distr.div.rules
// until there are no more changes:
rules = eDistrDiv ? setRules.distrDivRules : setRules.sucDivRules;
expr = simplify(expr, rules, {}, withExactFractions);
eDistrDiv = !eDistrDiv; // Swap between Distr.Div and Succ. Div. Rules
s = expr.toString();
if (s === sBefore) {
break; // No changes : end of the loop
}
redoInic = true;
sBefore = s;
}
if (redoInic) {
// Apply first rules again without succ div rules (if there are changes)
expr = simplify(expr, setRules.firstRulesAgain, {}, noExactFractions);
}
// Apply final rules:
expr = simplify(expr, setRules.finalRules, {}, noExactFractions);
} // NVars >= 1
var coefficients = [];
var retRationalize = {};
if (expr.type === 'OperatorNode' && expr.isBinary() && expr.op === '/') {
// Separate numerator from denominator
if (nVars === 1) {
expr.args[0] = polyToCanonical(expr.args[0], coefficients);
expr.args[1] = polyToCanonical(expr.args[1]);
}
if (detailed) {
retRationalize.numerator = expr.args[0];
retRationalize.denominator = expr.args[1];
}
} else {
if (nVars === 1) {
expr = polyToCanonical(expr, coefficients);
}
if (detailed) {
retRationalize.numerator = expr;
retRationalize.denominator = null;
}
}
// nVars
if (!detailed) return expr;
retRationalize.coefficients = coefficients;
retRationalize.variables = polyRet.variables;
retRationalize.expression = expr;
return retRationalize;
}
return typed(name, {
Node: _rationalize,
'Node, boolean': (expr, detailed) => _rationalize(expr, {}, detailed),
'Node, Object': _rationalize,
'Node, Object, boolean': _rationalize
}); // end of typed rationalize
/**
* Function to simplify an expression using an optional scope and
* return it if the expression is a polynomial expression, i.e.
* an expression with one or more variables and the operators
* +, -, *, and ^, where the exponent can only be a positive integer.
*
* Syntax:
*
* polynomial(expr,scope,extended, rules)
*
* @param {Node | string} expr The expression to simplify and check if is polynomial expression
* @param {object} scope Optional scope for expression simplification
* @param {boolean} extended Optional. Default is false. When true allows divide operator.
* @param {array} rules Optional. Default is no rule.
*
*
* @return {Object}
* {Object} node: node simplified expression
* {Array} variables: variable names
*/
function polynomial(expr, scope, extended, rules) {
var variables = [];
var node = simplify(expr, rules, scope, {
exactFractions: false
}); // Resolves any variables and functions with all defined parameters
extended = !!extended;
var oper = '+-*' + (extended ? '/' : '');
recPoly(node);
var retFunc = {};
retFunc.expression = node;
retFunc.variables = variables;
return retFunc;
// -------------------------------------------------------------------------------------------------------
/**
* Function to simplify an expression using an optional scope and
* return it if the expression is a polynomial expression, i.e.
* an expression with one or more variables and the operators
* +, -, *, and ^, where the exponent can only be a positive integer.
*
* Syntax:
*
* recPoly(node)
*
*
* @param {Node} node The current sub tree expression in recursion
*
* @return nothing, throw an exception if error
*/
function recPoly(node) {
var tp = node.type; // node type
if (tp === 'FunctionNode') {
// No function call in polynomial expression
throw new Error('There is an unsolved function call');
} else if (tp === 'OperatorNode') {
if (node.op === '^') {
// TODO: handle negative exponents like in '1/x^(-2)'
if (node.args[1].type !== 'ConstantNode' || !isInteger(parseFloat(node.args[1].value))) {
throw new Error('There is a non-integer exponent');
} else {
recPoly(node.args[0]);
}
} else {
if (!oper.includes(node.op)) {
throw new Error('Operator ' + node.op + ' invalid in polynomial expression');
}
for (var i = 0; i < node.args.length; i++) {
recPoly(node.args[i]);
}
} // type of operator
} else if (tp === 'SymbolNode') {
var _name = node.name; // variable name
var pos = variables.indexOf(_name);
if (pos === -1) {
// new variable in expression
variables.push(_name);
}
} else if (tp === 'ParenthesisNode') {
recPoly(node.content);
} else if (tp !== 'ConstantNode') {
throw new Error('type ' + tp + ' is not allowed in polynomial expression');
}
} // end of recPoly
} // end of polynomial
// ---------------------------------------------------------------------------------------
/**
* Return a rule set to rationalize an polynomial expression in rationalize
*
* Syntax:
*
* rulesRationalize()
*
* @return {array} rule set to rationalize an polynomial expression
*/
function rulesRationalize() {
var oldRules = [simplifyCore,
// sCore
{
l: 'n+n',
r: '2*n'
}, {
l: 'n+-n',
r: '0'
}, simplifyConstant,
// sConstant
{
l: 'n*(n1^-1)',
r: 'n/n1'
}, {
l: 'n*n1^-n2',
r: 'n/n1^n2'
}, {
l: 'n1^-1',
r: '1/n1'
}, {
l: 'n*(n1/n2)',
r: '(n*n1)/n2'
}, {
l: '1*n',
r: 'n'
}];
var rulesFirst = [{
l: '(-n1)/(-n2)',
r: 'n1/n2'
},
// Unary division
{
l: '(-n1)*(-n2)',
r: 'n1*n2'
},
// Unary multiplication
{
l: 'n1--n2',
r: 'n1+n2'
},
// '--' elimination
{
l: 'n1-n2',
r: 'n1+(-n2)'
},
// Subtraction turn into add with un<75>ry minus
{
l: '(n1+n2)*n3',
r: '(n1*n3 + n2*n3)'
},
// Distributive 1
{
l: 'n1*(n2+n3)',
r: '(n1*n2+n1*n3)'
},
// Distributive 2
{
l: 'c1*n + c2*n',
r: '(c1+c2)*n'
},
// Joining constants
{
l: 'c1*n + n',
r: '(c1+1)*n'
},
// Joining constants
{
l: 'c1*n - c2*n',
r: '(c1-c2)*n'
},
// Joining constants
{
l: 'c1*n - n',
r: '(c1-1)*n'
},
// Joining constants
{
l: 'v/c',
r: '(1/c)*v'
},
// variable/constant (new!)
{
l: 'v/-c',
r: '-(1/c)*v'
},
// variable/constant (new!)
{
l: '-v*-c',
r: 'c*v'
},
// Inversion constant and variable 1
{
l: '-v*c',
r: '-c*v'
},
// Inversion constant and variable 2
{
l: 'v*-c',
r: '-c*v'
},
// Inversion constant and variable 3
{
l: 'v*c',
r: 'c*v'
},
// Inversion constant and variable 4
{
l: '-(-n1*n2)',
r: '(n1*n2)'
},
// Unary propagation
{
l: '-(n1*n2)',
r: '(-n1*n2)'
},
// Unary propagation
{
l: '-(-n1+n2)',
r: '(n1-n2)'
},
// Unary propagation
{
l: '-(n1+n2)',
r: '(-n1-n2)'
},
// Unary propagation
{
l: '(n1^n2)^n3',
r: '(n1^(n2*n3))'
},
// Power to Power
{
l: '-(-n1/n2)',
r: '(n1/n2)'
},
// Division and Unary
{
l: '-(n1/n2)',
r: '(-n1/n2)'
}]; // Divisao and Unary
var rulesDistrDiv = [{
l: '(n1/n2 + n3/n4)',
r: '((n1*n4 + n3*n2)/(n2*n4))'
},
// Sum of fractions
{
l: '(n1/n2 + n3)',
r: '((n1 + n3*n2)/n2)'
},
// Sum fraction with number 1
{
l: '(n1 + n2/n3)',
r: '((n1*n3 + n2)/n3)'
}]; // Sum fraction with number 1
var rulesSucDiv = [{
l: '(n1/(n2/n3))',
r: '((n1*n3)/n2)'
},
// Division simplification
{
l: '(n1/n2/n3)',
r: '(n1/(n2*n3))'
}];
var setRules = {}; // rules set in 4 steps.
// All rules => infinite loop
// setRules.allRules =oldRules.concat(rulesFirst,rulesDistrDiv,rulesSucDiv)
setRules.firstRules = oldRules.concat(rulesFirst, rulesSucDiv); // First rule set
setRules.distrDivRules = rulesDistrDiv; // Just distr. div. rules
setRules.sucDivRules = rulesSucDiv; // Jus succ. div. rules
setRules.firstRulesAgain = oldRules.concat(rulesFirst); // Last rules set without succ. div.
// Division simplification
// Second rule set.
// There is no aggregate expression with parentesis, but the only variable can be scattered.
setRules.finalRules = [simplifyCore,
// simplify.rules[0]
{
l: 'n*-n',
r: '-n^2'
},
// Joining multiply with power 1
{
l: 'n*n',
r: 'n^2'
},
// Joining multiply with power 2
simplifyConstant,
// simplify.rules[14] old 3rd index in oldRules
{
l: 'n*-n^n1',
r: '-n^(n1+1)'
},
// Joining multiply with power 3
{
l: 'n*n^n1',
r: 'n^(n1+1)'
},
// Joining multiply with power 4
{
l: 'n^n1*-n^n2',
r: '-n^(n1+n2)'
},
// Joining multiply with power 5
{
l: 'n^n1*n^n2',
r: 'n^(n1+n2)'
},
// Joining multiply with power 6
{
l: 'n^n1*-n',
r: '-n^(n1+1)'
},
// Joining multiply with power 7
{
l: 'n^n1*n',
r: 'n^(n1+1)'
},
// Joining multiply with power 8
{
l: 'n^n1/-n',
r: '-n^(n1-1)'
},
// Joining multiply with power 8
{
l: 'n^n1/n',
r: 'n^(n1-1)'
},
// Joining division with power 1
{
l: 'n/-n^n1',
r: '-n^(1-n1)'
},
// Joining division with power 2
{
l: 'n/n^n1',
r: 'n^(1-n1)'
},
// Joining division with power 3
{
l: 'n^n1/-n^n2',
r: 'n^(n1-n2)'
},
// Joining division with power 4
{
l: 'n^n1/n^n2',
r: 'n^(n1-n2)'
},
// Joining division with power 5
{
l: 'n1+(-n2*n3)',
r: 'n1-n2*n3'
},
// Solving useless parenthesis 1
{
l: 'v*(-c)',
r: '-c*v'
},
// Solving useless unary 2
{
l: 'n1+-n2',
r: 'n1-n2'
},
// Solving +- together (new!)
{
l: 'v*c',
r: 'c*v'
},
// inversion constant with variable
{
l: '(n1^n2)^n3',
r: '(n1^(n2*n3))'
} // Power to Power
];
return setRules;
} // End rulesRationalize
// ---------------------------------------------------------------------------------------
/**
* Expand recursively a tree node for handling with expressions with exponents
* (it's not for constants, symbols or functions with exponents)
* PS: The other parameters are internal for recursion
*
* Syntax:
*
* expandPower(node)
*
* @param {Node} node Current expression node
* @param {node} parent Parent current node inside the recursion
* @param (int} Parent number of chid inside the rercursion
*
* @return {node} node expression with all powers expanded.
*/
function expandPower(node, parent, indParent) {
var tp = node.type;
var internal = arguments.length > 1; // TRUE in internal calls
if (tp === 'OperatorNode' && node.isBinary()) {
var does = false;
var val;
if (node.op === '^') {
// First operator: Parenthesis or UnaryMinus
if ((node.args[0].type === 'ParenthesisNode' || node.args[0].type === 'OperatorNode') && node.args[1].type === 'ConstantNode') {
// Second operator: Constant
val = parseFloat(node.args[1].value);
does = val >= 2 && isInteger(val);
}
}
if (does) {
// Exponent >= 2
// Before:
// operator A --> Subtree
// parent pow
// constant
//
if (val > 2) {
// Exponent > 2,
// AFTER: (exponent > 2)
// operator A --> Subtree
// parent *
// deep clone (operator A --> Subtree
// pow
// constant - 1
//
var nEsqTopo = node.args[0];
var nDirTopo = new OperatorNode('^', 'pow', [node.args[0].cloneDeep(), new ConstantNode(val - 1)]);
node = new OperatorNode('*', 'multiply', [nEsqTopo, nDirTopo]);
} else {
// Expo = 2 - no power
// AFTER: (exponent = 2)
// operator A --> Subtree
// parent oper
// deep clone (operator A --> Subtree)
//
node = new OperatorNode('*', 'multiply', [node.args[0], node.args[0].cloneDeep()]);
}
if (internal) {
// Change parent references in internal recursive calls
if (indParent === 'content') {
parent.content = node;
} else {
parent.args[indParent] = node;
}
}
} // does
} // binary OperatorNode
if (tp === 'ParenthesisNode') {
// Recursion
expandPower(node.content, node, 'content');
} else if (tp !== 'ConstantNode' && tp !== 'SymbolNode') {
for (var i = 0; i < node.args.length; i++) {
expandPower(node.args[i], node, i);
}
}
if (!internal) {
// return the root node
return node;
}
} // End expandPower
// ---------------------------------------------------------------------------------------
/**
* Auxilary function for rationalize
* Convert near canonical polynomial in one variable in a canonical polynomial
* with one term for each exponent in decreasing order
*
* Syntax:
*
* polyToCanonical(node [, coefficients])
*
* @param {Node | string} expr The near canonical polynomial expression to convert in a a canonical polynomial expression
*
* The string or tree expression needs to be at below syntax, with free spaces:
* ( (^(-)? | [+-]? )cte (*)? var (^expo)? | cte )+
* Where 'var' is one variable with any valid name
* 'cte' are real numeric constants with any value. It can be omitted if equal than 1
* 'expo' are integers greater than 0. It can be omitted if equal than 1.
*
* @param {array} coefficients Optional returns coefficients sorted by increased exponent
*
*
* @return {node} new node tree with one variable polynomial or string error.
*/
function polyToCanonical(node, coefficients) {
if (coefficients === undefined) {
coefficients = [];
} // coefficients.
coefficients[0] = 0; // index is the exponent
var o = {};
o.cte = 1;
o.oper = '+';
// fire: mark with * or ^ when finds * or ^ down tree, reset to "" with + and -.
// It is used to deduce the exponent: 1 for *, 0 for "".
o.fire = '';
var maxExpo = 0; // maximum exponent
var varname = ''; // variable name
recurPol(node, null, o);
maxExpo = coefficients.length - 1;
var first = true;
var no;
for (var i = maxExpo; i >= 0; i--) {
if (coefficients[i] === 0) continue;
var n1 = new ConstantNode(first ? coefficients[i] : Math.abs(coefficients[i]));
var op = coefficients[i] < 0 ? '-' : '+';
if (i > 0) {
// Is not a constant without variable
var n2 = new SymbolNode(varname);
if (i > 1) {
var n3 = new ConstantNode(i);
n2 = new OperatorNode('^', 'pow', [n2, n3]);
}
if (coefficients[i] === -1 && first) {
n1 = new OperatorNode('-', 'unaryMinus', [n2]);
} else if (Math.abs(coefficients[i]) === 1) {
n1 = n2;
} else {
n1 = new OperatorNode('*', 'multiply', [n1, n2]);
}
}
if (first) {
no = n1;
} else if (op === '+') {
no = new OperatorNode('+', 'add', [no, n1]);
} else {
no = new OperatorNode('-', 'subtract', [no, n1]);
}
first = false;
} // for
if (first) {
return new ConstantNode(0);
} else {
return no;
}
/**
* Recursive auxilary function inside polyToCanonical for
* converting expression in canonical form
*
* Syntax:
*
* recurPol(node, noPai, obj)
*
* @param {Node} node The current subpolynomial expression
* @param {Node | Null} noPai The current parent node
* @param {object} obj Object with many internal flags
*
* @return {} No return. If error, throws an exception
*/
function recurPol(node, noPai, o) {
var tp = node.type;
if (tp === 'FunctionNode') {
// ***** FunctionName *****
// No function call in polynomial expression
throw new Error('There is an unsolved function call');
} else if (tp === 'OperatorNode') {
// ***** OperatorName *****
if (!'+-*^'.includes(node.op)) throw new Error('Operator ' + node.op + ' invalid');
if (noPai !== null) {
// -(unary),^ : children of *,+,-
if ((node.fn === 'unaryMinus' || node.fn === 'pow') && noPai.fn !== 'add' && noPai.fn !== 'subtract' && noPai.fn !== 'multiply') {
throw new Error('Invalid ' + node.op + ' placing');
}
// -,+,* : children of +,-
if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'multiply') && noPai.fn !== 'add' && noPai.fn !== 'subtract') {
throw new Error('Invalid ' + node.op + ' placing');
}
// -,+ : first child
if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'unaryMinus') && o.noFil !== 0) {
throw new Error('Invalid ' + node.op + ' placing');
}
} // Has parent
// Firers: ^,* Old: ^,&,-(unary): firers
if (node.op === '^' || node.op === '*') {
o.fire = node.op;
}
for (var _i = 0; _i < node.args.length; _i++) {
// +,-: reset fire
if (node.fn === 'unaryMinus') o.oper = '-';
if (node.op === '+' || node.fn === 'subtract') {
o.fire = '';
o.cte = 1; // default if there is no constant
o.oper = _i === 0 ? '+' : node.op;
}
o.noFil = _i; // number of son
recurPol(node.args[_i], node, o);
} // for in children
} else if (tp === 'SymbolNode') {
// ***** SymbolName *****
if (node.name !== varname && varname !== '') {
throw new Error('There is more than one variable');
}
varname = node.name;
if (noPai === null) {
coefficients[1] = 1;
return;
}
// ^: Symbol is First child
if (noPai.op === '^' && o.noFil !== 0) {
throw new Error('In power the variable should be the first parameter');
}
// *: Symbol is Second child
if (noPai.op === '*' && o.noFil !== 1) {
throw new Error('In multiply the variable should be the second parameter');
}
// Symbol: firers '',* => it means there is no exponent above, so it's 1 (cte * var)
if (o.fire === '' || o.fire === '*') {
if (maxExpo < 1) coefficients[1] = 0;
coefficients[1] += o.cte * (o.oper === '+' ? 1 : -1);
maxExpo = Math.max(1, maxExpo);
}
} else if (tp === 'ConstantNode') {
var valor = parseFloat(node.value);
if (noPai === null) {
coefficients[0] = valor;
return;
}
if (noPai.op === '^') {
// cte: second child of power
if (o.noFil !== 1) throw new Error('Constant cannot be powered');
if (!isInteger(valor) || valor <= 0) {
throw new Error('Non-integer exponent is not allowed');
}
for (var _i2 = maxExpo + 1; _i2 < valor; _i2++) coefficients[_i2] = 0;
if (valor > maxExpo) coefficients[valor] = 0;
coefficients[valor] += o.cte * (o.oper === '+' ? 1 : -1);
maxExpo = Math.max(valor, maxExpo);
return;
}
o.cte = valor;
// Cte: firer '' => There is no exponent and no multiplication, so the exponent is 0.
if (o.fire === '') {
coefficients[0] += o.cte * (o.oper === '+' ? 1 : -1);
}
} else {
throw new Error('Type ' + tp + ' is not allowed');
}
} // End of recurPol
} // End of polyToCanonical
});

View File

@@ -0,0 +1,97 @@
import { createMap } from '../../utils/map.js';
import { isFunctionNode, isNode, isOperatorNode, isParenthesisNode, isSymbolNode } from '../../utils/is.js';
import { factory } from '../../utils/factory.js';
var name = 'resolve';
var dependencies = ['typed', 'parse', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode'];
export var createResolve = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
parse,
ConstantNode,
FunctionNode,
OperatorNode,
ParenthesisNode
} = _ref;
/**
* resolve(expr, scope) replaces variable nodes with their scoped values
*
* Syntax:
*
* math.resolve(expr, scope)
*
* Examples:
*
* math.resolve('x + y', {x:1, y:2}) // Node '1 + 2'
* math.resolve(math.parse('x+y'), {x:1, y:2}) // Node '1 + 2'
* math.simplify('x+y', {x:2, y: math.parse('x+x')}).toString() // "6"
*
* See also:
*
* simplify, evaluate
*
* @param {Node | Node[]} node
* The expression tree (or trees) to be simplified
* @param {Object} scope
* Scope specifying variables to be resolved
* @return {Node | Node[]} Returns `node` with variables recursively substituted.
* @throws {ReferenceError}
* If there is a cyclic dependency among the variables in `scope`,
* resolution is impossible and a ReferenceError is thrown.
*/
function _resolve(node, scope) {
var within = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
// note `within`:
// `within` is not documented, since it is for internal cycle
// detection only
if (!scope) {
return node;
}
if (isSymbolNode(node)) {
if (within.has(node.name)) {
var variables = Array.from(within).join(', ');
throw new ReferenceError("recursive loop of variable definitions among {".concat(variables, "}"));
}
var value = scope.get(node.name);
if (isNode(value)) {
var nextWithin = new Set(within);
nextWithin.add(node.name);
return _resolve(value, scope, nextWithin);
} else if (typeof value === 'number') {
return parse(String(value));
} else if (value !== undefined) {
return new ConstantNode(value);
} else {
return node;
}
} else if (isOperatorNode(node)) {
var args = node.args.map(function (arg) {
return _resolve(arg, scope, within);
});
return new OperatorNode(node.op, node.fn, args, node.implicit);
} else if (isParenthesisNode(node)) {
return new ParenthesisNode(_resolve(node.content, scope, within));
} else if (isFunctionNode(node)) {
var _args = node.args.map(function (arg) {
return _resolve(arg, scope, within);
});
return new FunctionNode(node.name, _args);
}
// Otherwise just recursively resolve any children (might also work
// for some of the above special cases)
return node.map(child => _resolve(child, scope, within));
}
return typed('resolve', {
Node: _resolve,
'Node, Map | null | undefined': _resolve,
'Node, Object': (n, scope) => _resolve(n, createMap(scope)),
// For arrays and matrices, we map `self` rather than `_resolve`
// because resolve is fairly expensive anyway, and this way
// we get nice error messages if one entry in the array has wrong type.
'Array | Matrix': typed.referToSelf(self => A => A.map(n => self(n))),
'Array | Matrix, null | undefined': typed.referToSelf(self => A => A.map(n => self(n))),
'Array, Object': typed.referTo('Array,Map', selfAM => (A, scope) => selfAM(A, createMap(scope))),
'Matrix, Object': typed.referTo('Matrix,Map', selfMM => (A, scope) => selfMM(A, createMap(scope))),
'Array | Matrix, Map': typed.referToSelf(self => (A, scope) => A.map(n => self(n, scope)))
});
});

1245
node_modules/mathjs/lib/esm/function/algebra/simplify.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,261 @@
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import { isFunctionNode, isOperatorNode, isParenthesisNode } from '../../../utils/is.js';
import { factory } from '../../../utils/factory.js';
import { hasOwnProperty } from '../../../utils/object.js';
var name = 'simplifyUtil';
var dependencies = ['FunctionNode', 'OperatorNode', 'SymbolNode'];
export var createUtil = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
FunctionNode,
OperatorNode,
SymbolNode
} = _ref;
// TODO commutative/associative properties rely on the arguments
// e.g. multiply is not commutative for matrices
// The properties should be calculated from an argument to simplify, or possibly something in math.config
// the other option is for typed() to specify a return type so that we can evaluate the type of arguments
/* So that properties of an operator fit on one line: */
var T = true;
var F = false;
var defaultName = 'defaultF';
var defaultContext = {
/* */add: {
trivial: T,
total: T,
commutative: T,
associative: T
},
/**/unaryPlus: {
trivial: T,
total: T,
commutative: T,
associative: T
},
/* */subtract: {
trivial: F,
total: T,
commutative: F,
associative: F
},
/* */multiply: {
trivial: T,
total: T,
commutative: T,
associative: T
},
/* */divide: {
trivial: F,
total: T,
commutative: F,
associative: F
},
/* */paren: {
trivial: T,
total: T,
commutative: T,
associative: F
},
/* */defaultF: {
trivial: F,
total: T,
commutative: F,
associative: F
}
};
var realContext = {
divide: {
total: F
},
log: {
total: F
}
};
var positiveContext = {
subtract: {
total: F
},
abs: {
trivial: T
},
log: {
total: T
}
};
function hasProperty(nodeOrName, property) {
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultContext;
var name = defaultName;
if (typeof nodeOrName === 'string') {
name = nodeOrName;
} else if (isOperatorNode(nodeOrName)) {
name = nodeOrName.fn.toString();
} else if (isFunctionNode(nodeOrName)) {
name = nodeOrName.name;
} else if (isParenthesisNode(nodeOrName)) {
name = 'paren';
}
if (hasOwnProperty(context, name)) {
var properties = context[name];
if (hasOwnProperty(properties, property)) {
return properties[property];
}
if (hasOwnProperty(defaultContext, name)) {
return defaultContext[name][property];
}
}
if (hasOwnProperty(context, defaultName)) {
var _properties = context[defaultName];
if (hasOwnProperty(_properties, property)) {
return _properties[property];
}
return defaultContext[defaultName][property];
}
/* name not found in context and context has no global default */
/* So use default context. */
if (hasOwnProperty(defaultContext, name)) {
var _properties2 = defaultContext[name];
if (hasOwnProperty(_properties2, property)) {
return _properties2[property];
}
}
return defaultContext[defaultName][property];
}
function isCommutative(node) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultContext;
return hasProperty(node, 'commutative', context);
}
function isAssociative(node) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultContext;
return hasProperty(node, 'associative', context);
}
/**
* Merge the given contexts, with primary overriding secondary
* wherever they might conflict
*/
function mergeContext(primary, secondary) {
var merged = _objectSpread({}, primary);
for (var prop in secondary) {
if (hasOwnProperty(primary, prop)) {
merged[prop] = _objectSpread(_objectSpread({}, secondary[prop]), primary[prop]);
} else {
merged[prop] = secondary[prop];
}
}
return merged;
}
/**
* Flatten all associative operators in an expression tree.
* Assumes parentheses have already been removed.
*/
function flatten(node, context) {
if (!node.args || node.args.length === 0) {
return node;
}
node.args = allChildren(node, context);
for (var i = 0; i < node.args.length; i++) {
flatten(node.args[i], context);
}
}
/**
* Get the children of a node as if it has been flattened.
* TODO implement for FunctionNodes
*/
function allChildren(node, context) {
var op;
var children = [];
var _findChildren = function findChildren(node) {
for (var i = 0; i < node.args.length; i++) {
var child = node.args[i];
if (isOperatorNode(child) && op === child.op) {
_findChildren(child);
} else {
children.push(child);
}
}
};
if (isAssociative(node, context)) {
op = node.op;
_findChildren(node);
return children;
} else {
return node.args;
}
}
/**
* Unflatten all flattened operators to a right-heavy binary tree.
*/
function unflattenr(node, context) {
if (!node.args || node.args.length === 0) {
return;
}
var makeNode = createMakeNodeFunction(node);
var l = node.args.length;
for (var i = 0; i < l; i++) {
unflattenr(node.args[i], context);
}
if (l > 2 && isAssociative(node, context)) {
var curnode = node.args.pop();
while (node.args.length > 0) {
curnode = makeNode([node.args.pop(), curnode]);
}
node.args = curnode.args;
}
}
/**
* Unflatten all flattened operators to a left-heavy binary tree.
*/
function unflattenl(node, context) {
if (!node.args || node.args.length === 0) {
return;
}
var makeNode = createMakeNodeFunction(node);
var l = node.args.length;
for (var i = 0; i < l; i++) {
unflattenl(node.args[i], context);
}
if (l > 2 && isAssociative(node, context)) {
var curnode = node.args.shift();
while (node.args.length > 0) {
curnode = makeNode([curnode, node.args.shift()]);
}
node.args = curnode.args;
}
}
function createMakeNodeFunction(node) {
if (isOperatorNode(node)) {
return function (args) {
try {
return new OperatorNode(node.op, node.fn, args, node.implicit);
} catch (err) {
console.error(err);
return [];
}
};
} else {
return function (args) {
return new FunctionNode(new SymbolNode(node.name), args);
};
}
}
return {
createMakeNodeFunction,
hasProperty,
isCommutative,
isAssociative,
mergeContext,
flatten,
allChildren,
unflattenr,
unflattenl,
defaultContext,
realContext,
positiveContext
};
});

View File

@@ -0,0 +1,20 @@
import { isConstantNode, isFunctionNode, isOperatorNode, isParenthesisNode } from '../../../utils/is.js';
export { isConstantNode, isSymbolNode as isVariableNode } from '../../../utils/is.js';
export function isNumericNode(x) {
return isConstantNode(x) || isOperatorNode(x) && x.isUnary() && isConstantNode(x.args[0]);
}
export function isConstantExpression(x) {
if (isConstantNode(x)) {
// Basic Constant types
return true;
}
if ((isFunctionNode(x) || isOperatorNode(x)) && x.args.every(isConstantExpression)) {
// Can be constant depending on arguments
return true;
}
if (isParenthesisNode(x) && isConstantExpression(x.content)) {
// Parenthesis are transparent
return true;
}
return false; // Probably missing some edge cases
}

View File

@@ -0,0 +1,472 @@
import { isFraction, isMatrix, isNode, isArrayNode, isConstantNode, isIndexNode, isObjectNode, isOperatorNode } from '../../utils/is.js';
import { factory } from '../../utils/factory.js';
import { safeNumberType } from '../../utils/number.js';
import { createUtil } from './simplify/util.js';
import { noBignumber, noFraction } from '../../utils/noop.js';
var name = 'simplifyConstant';
var dependencies = ['typed', 'config', 'mathWithTransform', 'matrix', '?fraction', '?bignumber', 'AccessorNode', 'ArrayNode', 'ConstantNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'SymbolNode'];
export var createSimplifyConstant = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
mathWithTransform,
matrix,
fraction,
bignumber,
AccessorNode,
ArrayNode,
ConstantNode,
FunctionNode,
IndexNode,
ObjectNode,
OperatorNode,
SymbolNode
} = _ref;
var {
isCommutative,
isAssociative,
allChildren,
createMakeNodeFunction
} = createUtil({
FunctionNode,
OperatorNode,
SymbolNode
});
/**
* simplifyConstant() takes a mathjs expression (either a Node representing
* a parse tree or a string which it parses to produce a node), and replaces
* any subexpression of it consisting entirely of constants with the computed
* value of that subexpression.
*
* Syntax:
*
* math.simplifyConstant(expr)
* math.simplifyConstant(expr, options)
*
* Examples:
*
* math.simplifyConstant('x + 4*3/6') // Node "x + 2"
* math.simplifyConstant('z cos(0)') // Node "z 1"
* math.simplifyConstant('(5.2 + 1.08)t', {exactFractions: false}) // Node "6.28 t"
*
* See also:
*
* simplify, simplifyCore, resolve, derivative
*
* @param {Node | string} node
* The expression to be simplified
* @param {Object} options
* Simplification options, as per simplify()
* @return {Node} Returns expression with constant subexpressions evaluated
*/
var simplifyConstant = typed('simplifyConstant', {
Node: node => _ensureNode(foldFraction(node, {})),
'Node, Object': function Node_Object(expr, options) {
return _ensureNode(foldFraction(expr, options));
}
});
function _removeFractions(thing) {
if (isFraction(thing)) {
return thing.valueOf();
}
if (thing instanceof Array) {
return thing.map(_removeFractions);
}
if (isMatrix(thing)) {
return matrix(_removeFractions(thing.valueOf()));
}
return thing;
}
function _eval(fnname, args, options) {
try {
return mathWithTransform[fnname].apply(null, args);
} catch (ignore) {
// sometimes the implicit type conversion causes the evaluation to fail, so we'll try again after removing Fractions
args = args.map(_removeFractions);
return _toNumber(mathWithTransform[fnname].apply(null, args), options);
}
}
var _toNode = typed({
Fraction: _fractionToNode,
number: function number(n) {
if (n < 0) {
return unaryMinusNode(new ConstantNode(-n));
}
return new ConstantNode(n);
},
BigNumber: function BigNumber(n) {
if (n < 0) {
return unaryMinusNode(new ConstantNode(-n));
}
return new ConstantNode(n); // old parameters: (n.toString(), 'number')
},
bigint: function bigint(n) {
if (n < 0n) {
return unaryMinusNode(new ConstantNode(-n));
}
return new ConstantNode(n);
},
Complex: function Complex(s) {
throw new Error('Cannot convert Complex number to Node');
},
string: function string(s) {
return new ConstantNode(s);
},
Matrix: function Matrix(m) {
return new ArrayNode(m.valueOf().map(e => _toNode(e)));
}
});
function _ensureNode(thing) {
if (isNode(thing)) {
return thing;
}
return _toNode(thing);
}
// convert a number to a fraction only if it can be expressed exactly,
// and when both numerator and denominator are small enough
function _exactFraction(n, options) {
var exactFractions = options && options.exactFractions !== false;
if (exactFractions && isFinite(n) && fraction) {
var f = fraction(n);
var fractionsLimit = options && typeof options.fractionsLimit === 'number' ? options.fractionsLimit : Infinity; // no limit by default
if (f.valueOf() === n && f.n < fractionsLimit && f.d < fractionsLimit) {
return f;
}
}
return n;
}
// Convert numbers to a preferred number type in preference order: Fraction, number, Complex
// BigNumbers are left alone
var _toNumber = typed({
'string, Object': function string_Object(s, options) {
var numericType = safeNumberType(s, config);
if (numericType === 'BigNumber') {
if (bignumber === undefined) {
noBignumber();
}
return bignumber(s);
} else if (numericType === 'bigint') {
return BigInt(s);
} else if (numericType === 'Fraction') {
if (fraction === undefined) {
noFraction();
}
return fraction(s);
} else {
var n = parseFloat(s);
return _exactFraction(n, options);
}
},
'Fraction, Object': function Fraction_Object(s, options) {
return s;
},
// we don't need options here
'BigNumber, Object': function BigNumber_Object(s, options) {
return s;
},
// we don't need options here
'number, Object': function number_Object(s, options) {
return _exactFraction(s, options);
},
'bigint, Object': function bigint_Object(s, options) {
return s;
},
'Complex, Object': function Complex_Object(s, options) {
if (s.im !== 0) {
return s;
}
return _exactFraction(s.re, options);
},
'Matrix, Object': function Matrix_Object(s, options) {
return matrix(_exactFraction(s.valueOf()));
},
'Array, Object': function Array_Object(s, options) {
return s.map(_exactFraction);
}
});
function unaryMinusNode(n) {
return new OperatorNode('-', 'unaryMinus', [n]);
}
function _fractionToNode(f) {
var n;
var vn = f.s * f.n;
if (vn < 0) {
n = new OperatorNode('-', 'unaryMinus', [new ConstantNode(-vn)]);
} else {
n = new ConstantNode(vn);
}
if (f.d === 1) {
return n;
}
return new OperatorNode('/', 'divide', [n, new ConstantNode(f.d)]);
}
/* Handles constant indexing of ArrayNodes, matrices, and ObjectNodes */
function _foldAccessor(obj, index, options) {
if (!isIndexNode(index)) {
// don't know what to do with that...
return new AccessorNode(_ensureNode(obj), _ensureNode(index));
}
if (isArrayNode(obj) || isMatrix(obj)) {
var remainingDims = Array.from(index.dimensions);
/* We will resolve constant indices one at a time, looking
* just in the first or second dimensions because (a) arrays
* of more than two dimensions are likely rare, and (b) pulling
* out the third or higher dimension would be pretty intricate.
* The price is that we miss simplifying [..3d array][x,y,1]
*/
while (remainingDims.length > 0) {
if (isConstantNode(remainingDims[0]) && typeof remainingDims[0].value !== 'string') {
var first = _toNumber(remainingDims.shift().value, options);
if (isArrayNode(obj)) {
obj = obj.items[first - 1];
} else {
// matrix
obj = obj.valueOf()[first - 1];
if (obj instanceof Array) {
obj = matrix(obj);
}
}
} else if (remainingDims.length > 1 && isConstantNode(remainingDims[1]) && typeof remainingDims[1].value !== 'string') {
var second = _toNumber(remainingDims[1].value, options);
var tryItems = [];
var fromItems = isArrayNode(obj) ? obj.items : obj.valueOf();
for (var item of fromItems) {
if (isArrayNode(item)) {
tryItems.push(item.items[second - 1]);
} else if (isMatrix(obj)) {
tryItems.push(item[second - 1]);
} else {
break;
}
}
if (tryItems.length === fromItems.length) {
if (isArrayNode(obj)) {
obj = new ArrayNode(tryItems);
} else {
// matrix
obj = matrix(tryItems);
}
remainingDims.splice(1, 1);
} else {
// extracting slice along 2nd dimension failed, give up
break;
}
} else {
// neither 1st or 2nd dimension is constant, give up
break;
}
}
if (remainingDims.length === index.dimensions.length) {
/* No successful constant indexing */
return new AccessorNode(_ensureNode(obj), index);
}
if (remainingDims.length > 0) {
/* Indexed some but not all dimensions */
index = new IndexNode(remainingDims);
return new AccessorNode(_ensureNode(obj), index);
}
/* All dimensions were constant, access completely resolved */
return obj;
}
if (isObjectNode(obj) && index.dimensions.length === 1 && isConstantNode(index.dimensions[0])) {
var key = index.dimensions[0].value;
if (key in obj.properties) {
return obj.properties[key];
}
return new ConstantNode(); // undefined
}
/* Don't know how to index this sort of obj, at least not with this index */
return new AccessorNode(_ensureNode(obj), index);
}
/*
* Create a binary tree from a list of Fractions and Nodes.
* Tries to fold Fractions by evaluating them until the first Node in the list is hit, so
* `args` should be sorted to have the Fractions at the start (if the operator is commutative).
* @param args - list of Fractions and Nodes
* @param fn - evaluator for the binary operation evaluator that accepts two Fractions
* @param makeNode - creates a binary OperatorNode/FunctionNode from a list of child Nodes
* if args.length is 1, returns args[0]
* @return - Either a Node representing a binary expression or Fraction
*/
function foldOp(fn, args, makeNode, options) {
var first = args.shift();
// In the following reduction, sofar always has one of the three following
// forms: [NODE], [CONSTANT], or [NODE, CONSTANT]
var reduction = args.reduce((sofar, next) => {
if (!isNode(next)) {
var last = sofar.pop();
if (isNode(last)) {
return [last, next];
}
// Two constants in a row, try to fold them into one
try {
sofar.push(_eval(fn, [last, next], options));
return sofar;
} catch (ignoreandcontinue) {
sofar.push(last);
// fall through to Node case
}
}
// Encountered a Node, or failed folding --
// collapse everything so far into a single tree:
sofar.push(_ensureNode(sofar.pop()));
var newtree = sofar.length === 1 ? sofar[0] : makeNode(sofar);
return [makeNode([newtree, _ensureNode(next)])];
}, [first]);
if (reduction.length === 1) {
return reduction[0];
}
// Might end up with a tree and a constant at the end:
return makeNode([reduction[0], _toNode(reduction[1])]);
}
// destroys the original node and returns a folded one
function foldFraction(node, options) {
switch (node.type) {
case 'SymbolNode':
return node;
case 'ConstantNode':
switch (typeof node.value) {
case 'number':
return _toNumber(node.value, options);
case 'bigint':
return _toNumber(node.value, options);
case 'string':
return node.value;
default:
if (!isNaN(node.value)) return _toNumber(node.value, options);
}
return node;
case 'FunctionNode':
if (mathWithTransform[node.name] && mathWithTransform[node.name].rawArgs) {
return node;
}
{
// Process operators as OperatorNode
var operatorFunctions = ['add', 'multiply'];
if (!operatorFunctions.includes(node.name)) {
var args = node.args.map(arg => foldFraction(arg, options));
// If all args are numbers
if (!args.some(isNode)) {
try {
return _eval(node.name, args, options);
} catch (ignoreandcontinue) {}
}
// Size of a matrix does not depend on entries
if (node.name === 'size' && args.length === 1 && isArrayNode(args[0])) {
var sz = [];
var section = args[0];
while (isArrayNode(section)) {
sz.push(section.items.length);
section = section.items[0];
}
return matrix(sz);
}
// Convert all args to nodes and construct a symbolic function call
return new FunctionNode(node.name, args.map(_ensureNode));
} else {
// treat as operator
}
}
/* falls through */
case 'OperatorNode':
{
var fn = node.fn.toString();
var _args;
var res;
var makeNode = createMakeNodeFunction(node);
if (isOperatorNode(node) && node.isUnary()) {
_args = [foldFraction(node.args[0], options)];
if (!isNode(_args[0])) {
res = _eval(fn, _args, options);
} else {
res = makeNode(_args);
}
} else if (isAssociative(node, options.context)) {
_args = allChildren(node, options.context);
_args = _args.map(arg => foldFraction(arg, options));
if (isCommutative(fn, options.context)) {
// commutative binary operator
var consts = [];
var vars = [];
for (var i = 0; i < _args.length; i++) {
if (!isNode(_args[i])) {
consts.push(_args[i]);
} else {
vars.push(_args[i]);
}
}
if (consts.length > 1) {
res = foldOp(fn, consts, makeNode, options);
vars.unshift(res);
res = foldOp(fn, vars, makeNode, options);
} else {
// we won't change the children order since it's not neccessary
res = foldOp(fn, _args, makeNode, options);
}
} else {
// non-commutative binary operator
res = foldOp(fn, _args, makeNode, options);
}
} else {
// non-associative binary operator
_args = node.args.map(arg => foldFraction(arg, options));
res = foldOp(fn, _args, makeNode, options);
}
return res;
}
case 'ParenthesisNode':
// remove the uneccessary parenthesis
return foldFraction(node.content, options);
case 'AccessorNode':
return _foldAccessor(foldFraction(node.object, options), foldFraction(node.index, options), options);
case 'ArrayNode':
{
var foldItems = node.items.map(item => foldFraction(item, options));
if (foldItems.some(isNode)) {
return new ArrayNode(foldItems.map(_ensureNode));
}
/* All literals -- return a Matrix so we can operate on it */
return matrix(foldItems);
}
case 'IndexNode':
{
return new IndexNode(node.dimensions.map(n => simplifyConstant(n, options)));
}
case 'ObjectNode':
{
var foldProps = {};
for (var prop in node.properties) {
foldProps[prop] = simplifyConstant(node.properties[prop], options);
}
return new ObjectNode(foldProps);
}
case 'AssignmentNode':
/* falls through */
case 'BlockNode':
/* falls through */
case 'FunctionAssignmentNode':
/* falls through */
case 'RangeNode':
/* falls through */
case 'ConditionalNode':
/* falls through */
default:
throw new Error("Unimplemented node type in simplifyConstant: ".concat(node.type));
}
}
return simplifyConstant;
});

View File

@@ -0,0 +1,291 @@
import { isAccessorNode, isArrayNode, isConstantNode, isFunctionNode, isIndexNode, isObjectNode, isOperatorNode } from '../../utils/is.js';
import { getOperator } from '../../expression/operators.js';
import { createUtil } from './simplify/util.js';
import { factory } from '../../utils/factory.js';
var name = 'simplifyCore';
var dependencies = ['typed', 'parse', 'equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'AccessorNode', 'ArrayNode', 'ConstantNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
export var createSimplifyCore = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
parse,
equal,
isZero,
add,
subtract,
multiply,
divide,
pow,
AccessorNode,
ArrayNode,
ConstantNode,
FunctionNode,
IndexNode,
ObjectNode,
OperatorNode,
ParenthesisNode,
SymbolNode
} = _ref;
var node0 = new ConstantNode(0);
var node1 = new ConstantNode(1);
var nodeT = new ConstantNode(true);
var nodeF = new ConstantNode(false);
// test if a node will always have a boolean value (true/false)
// not sure if this list is complete
function isAlwaysBoolean(node) {
return isOperatorNode(node) && ['and', 'not', 'or'].includes(node.op);
}
var {
hasProperty,
isCommutative
} = createUtil({
FunctionNode,
OperatorNode,
SymbolNode
});
/**
* simplifyCore() performs single pass simplification suitable for
* applications requiring ultimate performance. To roughly summarize,
* it handles cases along the lines of simplifyConstant() but where
* knowledge of a single argument is sufficient to determine the value.
* In contrast, simplify() extends simplifyCore() with additional passes
* to provide deeper simplification (such as gathering like terms).
*
* Specifically, simplifyCore:
*
* * Converts all function calls with operator equivalents to their
* operator forms.
* * Removes operators or function calls that are guaranteed to have no
* effect (such as unary '+').
* * Removes double unary '-', '~', and 'not'
* * Eliminates addition/subtraction of 0 and multiplication/division/powers
* by 1 or 0.
* * Converts addition of a negation into subtraction.
* * Eliminates logical operations with constant true or false leading
* arguments.
* * Puts constants on the left of a product, if multiplication is
* considered commutative by the options (which is the default)
*
* Syntax:
*
* math.simplifyCore(expr)
* math.simplifyCore(expr, options)
*
* Examples:
*
* const f = math.parse('2 * 1 * x ^ (1 - 0)')
* math.simplifyCore(f) // Node "2 * x"
* math.simplify('2 * 1 * x ^ (1 - 0)', [math.simplifyCore]) // Node "2 * x"
*
* See also:
*
* simplify, simplifyConstant, resolve, derivative
*
* @param {Node | string} node
* The expression to be simplified
* @param {Object} options
* Simplification options, as per simplify()
* @return {Node} Returns expression with basic simplifications applied
*/
function _simplifyCore(nodeToSimplify) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var context = options ? options.context : undefined;
if (hasProperty(nodeToSimplify, 'trivial', context)) {
// This node does nothing if it has only one argument, so if so,
// return that argument simplified
if (isFunctionNode(nodeToSimplify) && nodeToSimplify.args.length === 1) {
return _simplifyCore(nodeToSimplify.args[0], options);
}
// For other node types, we try the generic methods
var simpChild = false;
var childCount = 0;
nodeToSimplify.forEach(c => {
++childCount;
if (childCount === 1) {
simpChild = _simplifyCore(c, options);
}
});
if (childCount === 1) {
return simpChild;
}
}
var node = nodeToSimplify;
if (isFunctionNode(node)) {
var op = getOperator(node.name);
if (op) {
// Replace FunctionNode with a new OperatorNode
if (node.args.length > 2 && hasProperty(node, 'associative', context)) {
// unflatten into binary operations since that's what simplifyCore handles
while (node.args.length > 2) {
var last = node.args.pop();
var seclast = node.args.pop();
node.args.push(new OperatorNode(op, node.name, [last, seclast]));
}
}
node = new OperatorNode(op, node.name, node.args);
} else {
return new FunctionNode(_simplifyCore(node.fn), node.args.map(n => _simplifyCore(n, options)));
}
}
if (isOperatorNode(node) && node.isUnary()) {
var a0 = _simplifyCore(node.args[0], options);
if (node.op === '~') {
// bitwise not
if (isOperatorNode(a0) && a0.isUnary() && a0.op === '~') {
return a0.args[0];
}
}
if (node.op === 'not') {
// logical not
if (isOperatorNode(a0) && a0.isUnary() && a0.op === 'not') {
// Has the effect of turning the argument into a boolean
// So can only eliminate the double negation if
// the inside is already boolean
if (isAlwaysBoolean(a0.args[0])) {
return a0.args[0];
}
}
}
var finish = true;
if (node.op === '-') {
// unary minus
if (isOperatorNode(a0)) {
if (a0.isBinary() && a0.fn === 'subtract') {
node = new OperatorNode('-', 'subtract', [a0.args[1], a0.args[0]]);
finish = false; // continue to process the new binary node
}
if (a0.isUnary() && a0.op === '-') {
return a0.args[0];
}
}
}
if (finish) return new OperatorNode(node.op, node.fn, [a0]);
}
if (isOperatorNode(node) && node.isBinary()) {
var _a = _simplifyCore(node.args[0], options);
var a1 = _simplifyCore(node.args[1], options);
if (node.op === '+') {
if (isConstantNode(_a) && isZero(_a.value)) {
return a1;
}
if (isConstantNode(a1) && isZero(a1.value)) {
return _a;
}
if (isOperatorNode(a1) && a1.isUnary() && a1.op === '-') {
a1 = a1.args[0];
node = new OperatorNode('-', 'subtract', [_a, a1]);
}
}
if (node.op === '-') {
if (isOperatorNode(a1) && a1.isUnary() && a1.op === '-') {
return _simplifyCore(new OperatorNode('+', 'add', [_a, a1.args[0]]), options);
}
if (isConstantNode(_a) && isZero(_a.value)) {
return _simplifyCore(new OperatorNode('-', 'unaryMinus', [a1]));
}
if (isConstantNode(a1) && isZero(a1.value)) {
return _a;
}
return new OperatorNode(node.op, node.fn, [_a, a1]);
}
if (node.op === '*') {
if (isConstantNode(_a)) {
if (isZero(_a.value)) {
return node0;
} else if (equal(_a.value, 1)) {
return a1;
}
}
if (isConstantNode(a1)) {
if (isZero(a1.value)) {
return node0;
} else if (equal(a1.value, 1)) {
return _a;
}
if (isCommutative(node, context)) {
return new OperatorNode(node.op, node.fn, [a1, _a], node.implicit); // constants on left
}
}
return new OperatorNode(node.op, node.fn, [_a, a1], node.implicit);
}
if (node.op === '/') {
if (isConstantNode(_a) && isZero(_a.value)) {
return node0;
}
if (isConstantNode(a1) && equal(a1.value, 1)) {
return _a;
}
return new OperatorNode(node.op, node.fn, [_a, a1]);
}
if (node.op === '^') {
if (isConstantNode(a1)) {
if (isZero(a1.value)) {
return node1;
} else if (equal(a1.value, 1)) {
return _a;
}
}
}
if (node.op === 'and') {
if (isConstantNode(_a)) {
if (_a.value) {
if (isAlwaysBoolean(a1)) return a1;
if (isConstantNode(a1)) {
return a1.value ? nodeT : nodeF;
}
} else {
return nodeF;
}
}
if (isConstantNode(a1)) {
if (a1.value) {
if (isAlwaysBoolean(_a)) return _a;
} else {
return nodeF;
}
}
}
if (node.op === 'or') {
if (isConstantNode(_a)) {
if (_a.value) {
return nodeT;
} else {
if (isAlwaysBoolean(a1)) return a1;
}
}
if (isConstantNode(a1)) {
if (a1.value) {
return nodeT;
} else {
if (isAlwaysBoolean(_a)) return _a;
}
}
}
return new OperatorNode(node.op, node.fn, [_a, a1]);
}
if (isOperatorNode(node)) {
return new OperatorNode(node.op, node.fn, node.args.map(a => _simplifyCore(a, options)));
}
if (isArrayNode(node)) {
return new ArrayNode(node.items.map(n => _simplifyCore(n, options)));
}
if (isAccessorNode(node)) {
return new AccessorNode(_simplifyCore(node.object, options), _simplifyCore(node.index, options));
}
if (isIndexNode(node)) {
return new IndexNode(node.dimensions.map(n => _simplifyCore(n, options)));
}
if (isObjectNode(node)) {
var newProps = {};
for (var prop in node.properties) {
newProps[prop] = _simplifyCore(node.properties[prop], options);
}
return new ObjectNode(newProps);
}
// cannot simplify
return node;
}
return typed(name, {
Node: _simplifyCore,
'Node,Object': _simplifyCore
});
});

View File

@@ -0,0 +1,157 @@
import { factory } from '../../../utils/factory.js';
import { createSolveValidation } from './utils/solveValidation.js';
var name = 'lsolve';
var dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
export var createLsolve = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
divideScalar,
multiplyScalar,
subtractScalar,
equalScalar,
DenseMatrix
} = _ref;
var solveValidation = createSolveValidation({
DenseMatrix
});
/**
* Finds one solution of a linear equation system by forwards substitution. Matrix must be a lower triangular matrix. Throws an error if there's no solution.
*
* `L * x = b`
*
* Syntax:
*
* math.lsolve(L, b)
*
* Examples:
*
* const a = [[-2, 3], [2, 1]]
* const b = [11, 9]
* const x = lsolve(a, b) // [[-5.5], [20]]
*
* See also:
*
* lsolveAll, lup, slu, usolve, lusolve
*
* @param {Matrix, Array} L A N x N matrix or array (L)
* @param {Matrix, Array} b A column vector with the b values
*
* @return {DenseMatrix | Array} A column vector with the linear system solution (x)
*/
return typed(name, {
'SparseMatrix, Array | Matrix': function SparseMatrix_Array__Matrix(m, b) {
return _sparseForwardSubstitution(m, b);
},
'DenseMatrix, Array | Matrix': function DenseMatrix_Array__Matrix(m, b) {
return _denseForwardSubstitution(m, b);
},
'Array, Array | Matrix': function Array_Array__Matrix(a, b) {
var m = matrix(a);
var r = _denseForwardSubstitution(m, b);
return r.valueOf();
}
});
function _denseForwardSubstitution(m, b) {
// validate matrix and vector, return copy of column vector b
b = solveValidation(m, b, true);
var bdata = b._data;
var rows = m._size[0];
var columns = m._size[1];
// result
var x = [];
var mdata = m._data;
// loop columns
for (var j = 0; j < columns; j++) {
var bj = bdata[j][0] || 0;
var xj = void 0;
if (!equalScalar(bj, 0)) {
// non-degenerate row, find solution
var vjj = mdata[j][j];
if (equalScalar(vjj, 0)) {
throw new Error('Linear system cannot be solved since matrix is singular');
}
xj = divideScalar(bj, vjj);
// loop rows
for (var i = j + 1; i < rows; i++) {
bdata[i] = [subtractScalar(bdata[i][0] || 0, multiplyScalar(xj, mdata[i][j]))];
}
} else {
// degenerate row, we can choose any value
xj = 0;
}
x[j] = [xj];
}
return new DenseMatrix({
data: x,
size: [rows, 1]
});
}
function _sparseForwardSubstitution(m, b) {
// validate matrix and vector, return copy of column vector b
b = solveValidation(m, b, true);
var bdata = b._data;
var rows = m._size[0];
var columns = m._size[1];
var values = m._values;
var index = m._index;
var ptr = m._ptr;
// result
var x = [];
// loop columns
for (var j = 0; j < columns; j++) {
var bj = bdata[j][0] || 0;
if (!equalScalar(bj, 0)) {
// non-degenerate row, find solution
var vjj = 0;
// matrix values & indices (column j)
var jValues = [];
var jIndices = [];
// first and last index in the column
var firstIndex = ptr[j];
var lastIndex = ptr[j + 1];
// values in column, find value at [j, j]
for (var k = firstIndex; k < lastIndex; k++) {
var i = index[k];
// check row (rows are not sorted!)
if (i === j) {
vjj = values[k];
} else if (i > j) {
// store lower triangular
jValues.push(values[k]);
jIndices.push(i);
}
}
// at this point we must have a value in vjj
if (equalScalar(vjj, 0)) {
throw new Error('Linear system cannot be solved since matrix is singular');
}
var xj = divideScalar(bj, vjj);
for (var _k = 0, l = jIndices.length; _k < l; _k++) {
var _i = jIndices[_k];
bdata[_i] = [subtractScalar(bdata[_i][0] || 0, multiplyScalar(xj, jValues[_k]))];
}
x[j] = [xj];
} else {
// degenerate row, we can choose any value
x[j] = [0];
}
}
return new DenseMatrix({
data: x,
size: [rows, 1]
});
}
});

View File

@@ -0,0 +1,186 @@
import { factory } from '../../../utils/factory.js';
import { createSolveValidation } from './utils/solveValidation.js';
var name = 'lsolveAll';
var dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
export var createLsolveAll = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
divideScalar,
multiplyScalar,
subtractScalar,
equalScalar,
DenseMatrix
} = _ref;
var solveValidation = createSolveValidation({
DenseMatrix
});
/**
* Finds all solutions of a linear equation system by forwards substitution. Matrix must be a lower triangular matrix.
*
* `L * x = b`
*
* Syntax:
*
* math.lsolveAll(L, b)
*
* Examples:
*
* const a = [[-2, 3], [2, 1]]
* const b = [11, 9]
* const x = lsolveAll(a, b) // [ [[-5.5], [20]] ]
*
* See also:
*
* lsolve, lup, slu, usolve, lusolve
*
* @param {Matrix, Array} L A N x N matrix or array (L)
* @param {Matrix, Array} b A column vector with the b values
*
* @return {DenseMatrix[] | Array[]} An array of affine-independent column vectors (x) that solve the linear system
*/
return typed(name, {
'SparseMatrix, Array | Matrix': function SparseMatrix_Array__Matrix(m, b) {
return _sparseForwardSubstitution(m, b);
},
'DenseMatrix, Array | Matrix': function DenseMatrix_Array__Matrix(m, b) {
return _denseForwardSubstitution(m, b);
},
'Array, Array | Matrix': function Array_Array__Matrix(a, b) {
var m = matrix(a);
var R = _denseForwardSubstitution(m, b);
return R.map(r => r.valueOf());
}
});
function _denseForwardSubstitution(m, b_) {
// the algorithm is derived from
// https://www.overleaf.com/read/csvgqdxggyjv
// array of right-hand sides
var B = [solveValidation(m, b_, true)._data.map(e => e[0])];
var M = m._data;
var rows = m._size[0];
var columns = m._size[1];
// loop columns
for (var i = 0; i < columns; i++) {
var L = B.length;
// loop right-hand sides
for (var k = 0; k < L; k++) {
var b = B[k];
if (!equalScalar(M[i][i], 0)) {
// non-singular row
b[i] = divideScalar(b[i], M[i][i]);
for (var j = i + 1; j < columns; j++) {
// b[j] -= b[i] * M[j,i]
b[j] = subtractScalar(b[j], multiplyScalar(b[i], M[j][i]));
}
} else if (!equalScalar(b[i], 0)) {
// singular row, nonzero RHS
if (k === 0) {
// There is no valid solution
return [];
} else {
// This RHS is invalid but other solutions may still exist
B.splice(k, 1);
k -= 1;
L -= 1;
}
} else if (k === 0) {
// singular row, RHS is zero
var bNew = [...b];
bNew[i] = 1;
for (var _j = i + 1; _j < columns; _j++) {
bNew[_j] = subtractScalar(bNew[_j], M[_j][i]);
}
B.push(bNew);
}
}
}
return B.map(x => new DenseMatrix({
data: x.map(e => [e]),
size: [rows, 1]
}));
}
function _sparseForwardSubstitution(m, b_) {
// array of right-hand sides
var B = [solveValidation(m, b_, true)._data.map(e => e[0])];
var rows = m._size[0];
var columns = m._size[1];
var values = m._values;
var index = m._index;
var ptr = m._ptr;
// loop columns
for (var i = 0; i < columns; i++) {
var L = B.length;
// loop right-hand sides
for (var k = 0; k < L; k++) {
var b = B[k];
// values & indices (column i)
var iValues = [];
var iIndices = [];
// first & last indeces in column
var firstIndex = ptr[i];
var lastIndex = ptr[i + 1];
// find the value at [i, i]
var Mii = 0;
for (var j = firstIndex; j < lastIndex; j++) {
var J = index[j];
// check row
if (J === i) {
Mii = values[j];
} else if (J > i) {
// store lower triangular
iValues.push(values[j]);
iIndices.push(J);
}
}
if (!equalScalar(Mii, 0)) {
// non-singular row
b[i] = divideScalar(b[i], Mii);
for (var _j2 = 0, _lastIndex = iIndices.length; _j2 < _lastIndex; _j2++) {
var _J = iIndices[_j2];
b[_J] = subtractScalar(b[_J], multiplyScalar(b[i], iValues[_j2]));
}
} else if (!equalScalar(b[i], 0)) {
// singular row, nonzero RHS
if (k === 0) {
// There is no valid solution
return [];
} else {
// This RHS is invalid but other solutions may still exist
B.splice(k, 1);
k -= 1;
L -= 1;
}
} else if (k === 0) {
// singular row, RHS is zero
var bNew = [...b];
bNew[i] = 1;
for (var _j3 = 0, _lastIndex2 = iIndices.length; _j3 < _lastIndex2; _j3++) {
var _J2 = iIndices[_j3];
bNew[_J2] = subtractScalar(bNew[_J2], iValues[_j3]);
}
B.push(bNew);
}
}
}
return B.map(x => new DenseMatrix({
data: x.map(e => [e]),
size: [rows, 1]
}));
}
});

View File

@@ -0,0 +1,108 @@
import { isArray, isMatrix } from '../../../utils/is.js';
import { factory } from '../../../utils/factory.js';
import { createSolveValidation } from './utils/solveValidation.js';
import { csIpvec } from '../sparse/csIpvec.js';
var name = 'lusolve';
var dependencies = ['typed', 'matrix', 'lup', 'slu', 'usolve', 'lsolve', 'DenseMatrix'];
export var createLusolve = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
lup,
slu,
usolve,
lsolve,
DenseMatrix
} = _ref;
var solveValidation = createSolveValidation({
DenseMatrix
});
/**
* Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector.
*
* Syntax:
*
* math.lusolve(A, b) // returns column vector with the solution to the linear system A * x = b
* math.lusolve(lup, b) // returns column vector with the solution to the linear system A * x = b, lup = math.lup(A)
*
* Examples:
*
* const m = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]
*
* const x = math.lusolve(m, [-1, -1, -1, -1]) // x = [[-1], [-0.5], [-1/3], [-0.25]]
*
* const f = math.lup(m)
* const x1 = math.lusolve(f, [-1, -1, -1, -1]) // x1 = [[-1], [-0.5], [-1/3], [-0.25]]
* const x2 = math.lusolve(f, [1, 2, 1, -1]) // x2 = [[1], [1], [1/3], [-0.25]]
*
* const a = [[-2, 3], [2, 1]]
* const b = [11, 9]
* const x = math.lusolve(a, b) // [[2], [5]]
*
* See also:
*
* lup, slu, lsolve, usolve
*
* @param {Matrix | Array | Object} A Invertible Matrix or the Matrix LU decomposition
* @param {Matrix | Array} b Column Vector
* @param {number} [order] The Symbolic Ordering and Analysis order, see slu for details. Matrix must be a SparseMatrix
* @param {Number} [threshold] Partial pivoting threshold (1 for partial pivoting), see slu for details. Matrix must be a SparseMatrix.
*
* @return {DenseMatrix | Array} Column vector with the solution to the linear system A * x = b
*/
return typed(name, {
'Array, Array | Matrix': function Array_Array__Matrix(a, b) {
a = matrix(a);
var d = lup(a);
var x = _lusolve(d.L, d.U, d.p, null, b);
return x.valueOf();
},
'DenseMatrix, Array | Matrix': function DenseMatrix_Array__Matrix(a, b) {
var d = lup(a);
return _lusolve(d.L, d.U, d.p, null, b);
},
'SparseMatrix, Array | Matrix': function SparseMatrix_Array__Matrix(a, b) {
var d = lup(a);
return _lusolve(d.L, d.U, d.p, null, b);
},
'SparseMatrix, Array | Matrix, number, number': function SparseMatrix_Array__Matrix_number_number(a, b, order, threshold) {
var d = slu(a, order, threshold);
return _lusolve(d.L, d.U, d.p, d.q, b);
},
'Object, Array | Matrix': function Object_Array__Matrix(d, b) {
return _lusolve(d.L, d.U, d.p, d.q, b);
}
});
function _toMatrix(a) {
if (isMatrix(a)) {
return a;
}
if (isArray(a)) {
return matrix(a);
}
throw new TypeError('Invalid Matrix LU decomposition');
}
function _lusolve(l, u, p, q, b) {
// verify decomposition
l = _toMatrix(l);
u = _toMatrix(u);
// apply row permutations if needed (b is a DenseMatrix)
if (p) {
b = solveValidation(l, b, true);
b._data = csIpvec(p, b._data);
}
// use forward substitution to resolve L * y = b
var y = lsolve(l, b);
// use backward substitution to resolve U * x = y
var x = usolve(u, y);
// apply column permutations if needed (x is a DenseMatrix)
if (q) {
x._data = csIpvec(q, x._data);
}
return x;
}
});

View File

@@ -0,0 +1,161 @@
import { factory } from '../../../utils/factory.js';
import { createSolveValidation } from './utils/solveValidation.js';
var name = 'usolve';
var dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
export var createUsolve = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
divideScalar,
multiplyScalar,
subtractScalar,
equalScalar,
DenseMatrix
} = _ref;
var solveValidation = createSolveValidation({
DenseMatrix
});
/**
* Finds one solution of a linear equation system by backward substitution. Matrix must be an upper triangular matrix. Throws an error if there's no solution.
*
* `U * x = b`
*
* Syntax:
*
* math.usolve(U, b)
*
* Examples:
*
* const a = [[-2, 3], [2, 1]]
* const b = [11, 9]
* const x = usolve(a, b) // [[8], [9]]
*
* See also:
*
* usolveAll, lup, slu, usolve, lusolve
*
* @param {Matrix, Array} U A N x N matrix or array (U)
* @param {Matrix, Array} b A column vector with the b values
*
* @return {DenseMatrix | Array} A column vector with the linear system solution (x)
*/
return typed(name, {
'SparseMatrix, Array | Matrix': function SparseMatrix_Array__Matrix(m, b) {
return _sparseBackwardSubstitution(m, b);
},
'DenseMatrix, Array | Matrix': function DenseMatrix_Array__Matrix(m, b) {
return _denseBackwardSubstitution(m, b);
},
'Array, Array | Matrix': function Array_Array__Matrix(a, b) {
var m = matrix(a);
var r = _denseBackwardSubstitution(m, b);
return r.valueOf();
}
});
function _denseBackwardSubstitution(m, b) {
// make b into a column vector
b = solveValidation(m, b, true);
var bdata = b._data;
var rows = m._size[0];
var columns = m._size[1];
// result
var x = [];
var mdata = m._data;
// loop columns backwards
for (var j = columns - 1; j >= 0; j--) {
// b[j]
var bj = bdata[j][0] || 0;
// x[j]
var xj = void 0;
if (!equalScalar(bj, 0)) {
// value at [j, j]
var vjj = mdata[j][j];
if (equalScalar(vjj, 0)) {
// system cannot be solved
throw new Error('Linear system cannot be solved since matrix is singular');
}
xj = divideScalar(bj, vjj);
// loop rows
for (var i = j - 1; i >= 0; i--) {
// update copy of b
bdata[i] = [subtractScalar(bdata[i][0] || 0, multiplyScalar(xj, mdata[i][j]))];
}
} else {
// zero value at j
xj = 0;
}
// update x
x[j] = [xj];
}
return new DenseMatrix({
data: x,
size: [rows, 1]
});
}
function _sparseBackwardSubstitution(m, b) {
// make b into a column vector
b = solveValidation(m, b, true);
var bdata = b._data;
var rows = m._size[0];
var columns = m._size[1];
var values = m._values;
var index = m._index;
var ptr = m._ptr;
// result
var x = [];
// loop columns backwards
for (var j = columns - 1; j >= 0; j--) {
var bj = bdata[j][0] || 0;
if (!equalScalar(bj, 0)) {
// non-degenerate row, find solution
var vjj = 0;
// upper triangular matrix values & index (column j)
var jValues = [];
var jIndices = [];
// first & last indeces in column
var firstIndex = ptr[j];
var lastIndex = ptr[j + 1];
// values in column, find value at [j, j], loop backwards
for (var k = lastIndex - 1; k >= firstIndex; k--) {
var i = index[k];
// check row (rows are not sorted!)
if (i === j) {
vjj = values[k];
} else if (i < j) {
// store upper triangular
jValues.push(values[k]);
jIndices.push(i);
}
}
// at this point we must have a value in vjj
if (equalScalar(vjj, 0)) {
throw new Error('Linear system cannot be solved since matrix is singular');
}
var xj = divideScalar(bj, vjj);
for (var _k = 0, _lastIndex = jIndices.length; _k < _lastIndex; _k++) {
var _i = jIndices[_k];
bdata[_i] = [subtractScalar(bdata[_i][0], multiplyScalar(xj, jValues[_k]))];
}
x[j] = [xj];
} else {
// degenerate row, we can choose any value
x[j] = [0];
}
}
return new DenseMatrix({
data: x,
size: [rows, 1]
});
}
});

View File

@@ -0,0 +1,190 @@
import { factory } from '../../../utils/factory.js';
import { createSolveValidation } from './utils/solveValidation.js';
var name = 'usolveAll';
var dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
export var createUsolveAll = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
divideScalar,
multiplyScalar,
subtractScalar,
equalScalar,
DenseMatrix
} = _ref;
var solveValidation = createSolveValidation({
DenseMatrix
});
/**
* Finds all solutions of a linear equation system by backward substitution. Matrix must be an upper triangular matrix.
*
* `U * x = b`
*
* Syntax:
*
* math.usolveAll(U, b)
*
* Examples:
*
* const a = [[-2, 3], [2, 1]]
* const b = [11, 9]
* const x = usolveAll(a, b) // [ [[8], [9]] ]
*
* See also:
*
* usolve, lup, slu, usolve, lusolve
*
* @param {Matrix, Array} U A N x N matrix or array (U)
* @param {Matrix, Array} b A column vector with the b values
*
* @return {DenseMatrix[] | Array[]} An array of affine-independent column vectors (x) that solve the linear system
*/
return typed(name, {
'SparseMatrix, Array | Matrix': function SparseMatrix_Array__Matrix(m, b) {
return _sparseBackwardSubstitution(m, b);
},
'DenseMatrix, Array | Matrix': function DenseMatrix_Array__Matrix(m, b) {
return _denseBackwardSubstitution(m, b);
},
'Array, Array | Matrix': function Array_Array__Matrix(a, b) {
var m = matrix(a);
var R = _denseBackwardSubstitution(m, b);
return R.map(r => r.valueOf());
}
});
function _denseBackwardSubstitution(m, b_) {
// the algorithm is derived from
// https://www.overleaf.com/read/csvgqdxggyjv
// array of right-hand sides
var B = [solveValidation(m, b_, true)._data.map(e => e[0])];
var M = m._data;
var rows = m._size[0];
var columns = m._size[1];
// loop columns backwards
for (var i = columns - 1; i >= 0; i--) {
var L = B.length;
// loop right-hand sides
for (var k = 0; k < L; k++) {
var b = B[k];
if (!equalScalar(M[i][i], 0)) {
// non-singular row
b[i] = divideScalar(b[i], M[i][i]);
for (var j = i - 1; j >= 0; j--) {
// b[j] -= b[i] * M[j,i]
b[j] = subtractScalar(b[j], multiplyScalar(b[i], M[j][i]));
}
} else if (!equalScalar(b[i], 0)) {
// singular row, nonzero RHS
if (k === 0) {
// There is no valid solution
return [];
} else {
// This RHS is invalid but other solutions may still exist
B.splice(k, 1);
k -= 1;
L -= 1;
}
} else if (k === 0) {
// singular row, RHS is zero
var bNew = [...b];
bNew[i] = 1;
for (var _j = i - 1; _j >= 0; _j--) {
bNew[_j] = subtractScalar(bNew[_j], M[_j][i]);
}
B.push(bNew);
}
}
}
return B.map(x => new DenseMatrix({
data: x.map(e => [e]),
size: [rows, 1]
}));
}
function _sparseBackwardSubstitution(m, b_) {
// array of right-hand sides
var B = [solveValidation(m, b_, true)._data.map(e => e[0])];
var rows = m._size[0];
var columns = m._size[1];
var values = m._values;
var index = m._index;
var ptr = m._ptr;
// loop columns backwards
for (var i = columns - 1; i >= 0; i--) {
var L = B.length;
// loop right-hand sides
for (var k = 0; k < L; k++) {
var b = B[k];
// values & indices (column i)
var iValues = [];
var iIndices = [];
// first & last indeces in column
var firstIndex = ptr[i];
var lastIndex = ptr[i + 1];
// find the value at [i, i]
var Mii = 0;
for (var j = lastIndex - 1; j >= firstIndex; j--) {
var J = index[j];
// check row
if (J === i) {
Mii = values[j];
} else if (J < i) {
// store upper triangular
iValues.push(values[j]);
iIndices.push(J);
}
}
if (!equalScalar(Mii, 0)) {
// non-singular row
b[i] = divideScalar(b[i], Mii);
// loop upper triangular
for (var _j2 = 0, _lastIndex = iIndices.length; _j2 < _lastIndex; _j2++) {
var _J = iIndices[_j2];
b[_J] = subtractScalar(b[_J], multiplyScalar(b[i], iValues[_j2]));
}
} else if (!equalScalar(b[i], 0)) {
// singular row, nonzero RHS
if (k === 0) {
// There is no valid solution
return [];
} else {
// This RHS is invalid but other solutions may still exist
B.splice(k, 1);
k -= 1;
L -= 1;
}
} else if (k === 0) {
// singular row, RHS is zero
var bNew = [...b];
bNew[i] = 1;
// loop upper triangular
for (var _j3 = 0, _lastIndex2 = iIndices.length; _j3 < _lastIndex2; _j3++) {
var _J2 = iIndices[_j3];
bNew[_J2] = subtractScalar(bNew[_J2], iValues[_j3]);
}
B.push(bNew);
}
}
}
return B.map(x => new DenseMatrix({
data: x.map(e => [e]),
size: [rows, 1]
}));
}
});

View File

@@ -0,0 +1,115 @@
import { isArray, isMatrix, isDenseMatrix, isSparseMatrix } from '../../../../utils/is.js';
import { arraySize } from '../../../../utils/array.js';
import { format } from '../../../../utils/string.js';
export function createSolveValidation(_ref) {
var {
DenseMatrix
} = _ref;
/**
* Validates matrix and column vector b for backward/forward substitution algorithms.
*
* @param {Matrix} m An N x N matrix
* @param {Array | Matrix} b A column vector
* @param {Boolean} copy Return a copy of vector b
*
* @return {DenseMatrix} Dense column vector b
*/
return function solveValidation(m, b, copy) {
var mSize = m.size();
if (mSize.length !== 2) {
throw new RangeError('Matrix must be two dimensional (size: ' + format(mSize) + ')');
}
var rows = mSize[0];
var columns = mSize[1];
if (rows !== columns) {
throw new RangeError('Matrix must be square (size: ' + format(mSize) + ')');
}
var data = [];
if (isMatrix(b)) {
var bSize = b.size();
var bdata = b._data;
// 1-dim vector
if (bSize.length === 1) {
if (bSize[0] !== rows) {
throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
}
for (var i = 0; i < rows; i++) {
data[i] = [bdata[i]];
}
return new DenseMatrix({
data,
size: [rows, 1],
datatype: b._datatype
});
}
// 2-dim column
if (bSize.length === 2) {
if (bSize[0] !== rows || bSize[1] !== 1) {
throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
}
if (isDenseMatrix(b)) {
if (copy) {
data = [];
for (var _i = 0; _i < rows; _i++) {
data[_i] = [bdata[_i][0]];
}
return new DenseMatrix({
data,
size: [rows, 1],
datatype: b._datatype
});
}
return b;
}
if (isSparseMatrix(b)) {
for (var _i2 = 0; _i2 < rows; _i2++) {
data[_i2] = [0];
}
var values = b._values;
var index = b._index;
var ptr = b._ptr;
for (var k1 = ptr[1], k = ptr[0]; k < k1; k++) {
var _i3 = index[k];
data[_i3][0] = values[k];
}
return new DenseMatrix({
data,
size: [rows, 1],
datatype: b._datatype
});
}
}
throw new RangeError('Dimension mismatch. The right side has to be either 1- or 2-dimensional vector.');
}
if (isArray(b)) {
var bsize = arraySize(b);
if (bsize.length === 1) {
if (bsize[0] !== rows) {
throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
}
for (var _i4 = 0; _i4 < rows; _i4++) {
data[_i4] = [b[_i4]];
}
return new DenseMatrix({
data,
size: [rows, 1]
});
}
if (bsize.length === 2) {
if (bsize[0] !== rows || bsize[1] !== 1) {
throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
}
for (var _i5 = 0; _i5 < rows; _i5++) {
data[_i5] = [b[_i5][0]];
}
return new DenseMatrix({
data,
size: [rows, 1]
});
}
throw new RangeError('Dimension mismatch. The right side has to be either 1- or 2-dimensional vector.');
}
};
}

View File

@@ -0,0 +1,580 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { factory } from '../../../utils/factory.js';
import { csFkeep } from './csFkeep.js';
import { csFlip } from './csFlip.js';
import { csTdfs } from './csTdfs.js';
var name = 'csAmd';
var dependencies = ['add', 'multiply', 'transpose'];
export var createCsAmd = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
add,
multiply,
transpose
} = _ref;
/**
* Approximate minimum degree ordering. The minimum degree algorithm is a widely used
* heuristic for finding a permutation P so that P*A*P' has fewer nonzeros in its factorization
* than A. It is a gready method that selects the sparsest pivot row and column during the course
* of a right looking sparse Cholesky factorization.
*
* @param {Number} order 0: Natural, 1: Cholesky, 2: LU, 3: QR
* @param {Matrix} m Sparse Matrix
*/
return function csAmd(order, a) {
// check input parameters
if (!a || order <= 0 || order > 3) {
return null;
}
// a matrix arrays
var asize = a._size;
// rows and columns
var m = asize[0];
var n = asize[1];
// initialize vars
var lemax = 0;
// dense threshold
var dense = Math.max(16, 10 * Math.sqrt(n));
dense = Math.min(n - 2, dense);
// create target matrix C
var cm = _createTargetMatrix(order, a, m, n, dense);
// drop diagonal entries
csFkeep(cm, _diag, null);
// C matrix arrays
var cindex = cm._index;
var cptr = cm._ptr;
// number of nonzero elements in C
var cnz = cptr[n];
// allocate result (n+1)
var P = [];
// create workspace (8 * (n + 1))
var W = [];
var len = 0; // first n + 1 entries
var nv = n + 1; // next n + 1 entries
var next = 2 * (n + 1); // next n + 1 entries
var head = 3 * (n + 1); // next n + 1 entries
var elen = 4 * (n + 1); // next n + 1 entries
var degree = 5 * (n + 1); // next n + 1 entries
var w = 6 * (n + 1); // next n + 1 entries
var hhead = 7 * (n + 1); // last n + 1 entries
// use P as workspace for last
var last = P;
// initialize quotient graph
var mark = _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree);
// initialize degree lists
var nel = _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next);
// minimum degree node
var mindeg = 0;
// vars
var i, j, k, k1, k2, e, pj, ln, nvi, pk, eln, p1, p2, pn, h, d;
// while (selecting pivots) do
while (nel < n) {
// select node of minimum approximate degree. amd() is now ready to start eliminating the graph. It first
// finds a node k of minimum degree and removes it from its degree list. The variable nel keeps track of thow
// many nodes have been eliminated.
for (k = -1; mindeg < n && (k = W[head + mindeg]) === -1; mindeg++);
if (W[next + k] !== -1) {
last[W[next + k]] = -1;
}
// remove k from degree list
W[head + mindeg] = W[next + k];
// elenk = |Ek|
var elenk = W[elen + k];
// # of nodes k represents
var nvk = W[nv + k];
// W[nv + k] nodes of A eliminated
nel += nvk;
// Construct a new element. The new element Lk is constructed in place if |Ek| = 0. nv[i] is
// negated for all nodes i in Lk to flag them as members of this set. Each node i is removed from the
// degree lists. All elements e in Ek are absorved into element k.
var dk = 0;
// flag k as in Lk
W[nv + k] = -nvk;
var p = cptr[k];
// do in place if W[elen + k] === 0
var pk1 = elenk === 0 ? p : cnz;
var pk2 = pk1;
for (k1 = 1; k1 <= elenk + 1; k1++) {
if (k1 > elenk) {
// search the nodes in k
e = k;
// list of nodes starts at cindex[pj]
pj = p;
// length of list of nodes in k
ln = W[len + k] - elenk;
} else {
// search the nodes in e
e = cindex[p++];
pj = cptr[e];
// length of list of nodes in e
ln = W[len + e];
}
for (k2 = 1; k2 <= ln; k2++) {
i = cindex[pj++];
// check node i dead, or seen
if ((nvi = W[nv + i]) <= 0) {
continue;
}
// W[degree + Lk] += size of node i
dk += nvi;
// negate W[nv + i] to denote i in Lk
W[nv + i] = -nvi;
// place i in Lk
cindex[pk2++] = i;
if (W[next + i] !== -1) {
last[W[next + i]] = last[i];
}
// check we need to remove i from degree list
if (last[i] !== -1) {
W[next + last[i]] = W[next + i];
} else {
W[head + W[degree + i]] = W[next + i];
}
}
if (e !== k) {
// absorb e into k
cptr[e] = csFlip(k);
// e is now a dead element
W[w + e] = 0;
}
}
// cindex[cnz...nzmax] is free
if (elenk !== 0) {
cnz = pk2;
}
// external degree of k - |Lk\i|
W[degree + k] = dk;
// element k is in cindex[pk1..pk2-1]
cptr[k] = pk1;
W[len + k] = pk2 - pk1;
// k is now an element
W[elen + k] = -2;
// Find set differences. The scan1 function now computes the set differences |Le \ Lk| for all elements e. At the start of the
// scan, no entry in the w array is greater than or equal to mark.
// clear w if necessary
mark = _wclear(mark, lemax, W, w, n);
// scan 1: find |Le\Lk|
for (pk = pk1; pk < pk2; pk++) {
i = cindex[pk];
// check if W[elen + i] empty, skip it
if ((eln = W[elen + i]) <= 0) {
continue;
}
// W[nv + i] was negated
nvi = -W[nv + i];
var wnvi = mark - nvi;
// scan Ei
for (p = cptr[i], p1 = cptr[i] + eln - 1; p <= p1; p++) {
e = cindex[p];
if (W[w + e] >= mark) {
// decrement |Le\Lk|
W[w + e] -= nvi;
} else if (W[w + e] !== 0) {
// ensure e is a live element, 1st time e seen in scan 1
W[w + e] = W[degree + e] + wnvi;
}
}
}
// degree update
// The second pass computes the approximate degree di, prunes the sets Ei and Ai, and computes a hash
// function h(i) for all nodes in Lk.
// scan2: degree update
for (pk = pk1; pk < pk2; pk++) {
// consider node i in Lk
i = cindex[pk];
p1 = cptr[i];
p2 = p1 + W[elen + i] - 1;
pn = p1;
// scan Ei
for (h = 0, d = 0, p = p1; p <= p2; p++) {
e = cindex[p];
// check e is an unabsorbed element
if (W[w + e] !== 0) {
// dext = |Le\Lk|
var dext = W[w + e] - mark;
if (dext > 0) {
// sum up the set differences
d += dext;
// keep e in Ei
cindex[pn++] = e;
// compute the hash of node i
h += e;
} else {
// aggressive absorb. e->k
cptr[e] = csFlip(k);
// e is a dead element
W[w + e] = 0;
}
}
}
// W[elen + i] = |Ei|
W[elen + i] = pn - p1 + 1;
var p3 = pn;
var p4 = p1 + W[len + i];
// prune edges in Ai
for (p = p2 + 1; p < p4; p++) {
j = cindex[p];
// check node j dead or in Lk
var nvj = W[nv + j];
if (nvj <= 0) {
continue;
}
// degree(i) += |j|
d += nvj;
// place j in node list of i
cindex[pn++] = j;
// compute hash for node i
h += j;
}
// check for mass elimination
if (d === 0) {
// absorb i into k
cptr[i] = csFlip(k);
nvi = -W[nv + i];
// |Lk| -= |i|
dk -= nvi;
// |k| += W[nv + i]
nvk += nvi;
nel += nvi;
W[nv + i] = 0;
// node i is dead
W[elen + i] = -1;
} else {
// update degree(i)
W[degree + i] = Math.min(W[degree + i], d);
// move first node to end
cindex[pn] = cindex[p3];
// move 1st el. to end of Ei
cindex[p3] = cindex[p1];
// add k as 1st element in of Ei
cindex[p1] = k;
// new len of adj. list of node i
W[len + i] = pn - p1 + 1;
// finalize hash of i
h = (h < 0 ? -h : h) % n;
// place i in hash bucket
W[next + i] = W[hhead + h];
W[hhead + h] = i;
// save hash of i in last[i]
last[i] = h;
}
}
// finalize |Lk|
W[degree + k] = dk;
lemax = Math.max(lemax, dk);
// clear w
mark = _wclear(mark + lemax, lemax, W, w, n);
// Supernode detection. Supernode detection relies on the hash function h(i) computed for each node i.
// If two nodes have identical adjacency lists, their hash functions wil be identical.
for (pk = pk1; pk < pk2; pk++) {
i = cindex[pk];
// check i is dead, skip it
if (W[nv + i] >= 0) {
continue;
}
// scan hash bucket of node i
h = last[i];
i = W[hhead + h];
// hash bucket will be empty
W[hhead + h] = -1;
for (; i !== -1 && W[next + i] !== -1; i = W[next + i], mark++) {
ln = W[len + i];
eln = W[elen + i];
for (p = cptr[i] + 1; p <= cptr[i] + ln - 1; p++) {
W[w + cindex[p]] = mark;
}
var jlast = i;
// compare i with all j
for (j = W[next + i]; j !== -1;) {
var ok = W[len + j] === ln && W[elen + j] === eln;
for (p = cptr[j] + 1; ok && p <= cptr[j] + ln - 1; p++) {
// compare i and j
if (W[w + cindex[p]] !== mark) {
ok = 0;
}
}
// check i and j are identical
if (ok) {
// absorb j into i
cptr[j] = csFlip(i);
W[nv + i] += W[nv + j];
W[nv + j] = 0;
// node j is dead
W[elen + j] = -1;
// delete j from hash bucket
j = W[next + j];
W[next + jlast] = j;
} else {
// j and i are different
jlast = j;
j = W[next + j];
}
}
}
}
// Finalize new element. The elimination of node k is nearly complete. All nodes i in Lk are scanned one last time.
// Node i is removed from Lk if it is dead. The flagged status of nv[i] is cleared.
for (p = pk1, pk = pk1; pk < pk2; pk++) {
i = cindex[pk];
// check i is dead, skip it
if ((nvi = -W[nv + i]) <= 0) {
continue;
}
// restore W[nv + i]
W[nv + i] = nvi;
// compute external degree(i)
d = W[degree + i] + dk - nvi;
d = Math.min(d, n - nel - nvi);
if (W[head + d] !== -1) {
last[W[head + d]] = i;
}
// put i back in degree list
W[next + i] = W[head + d];
last[i] = -1;
W[head + d] = i;
// find new minimum degree
mindeg = Math.min(mindeg, d);
W[degree + i] = d;
// place i in Lk
cindex[p++] = i;
}
// # nodes absorbed into k
W[nv + k] = nvk;
// length of adj list of element k
if ((W[len + k] = p - pk1) === 0) {
// k is a root of the tree
cptr[k] = -1;
// k is now a dead element
W[w + k] = 0;
}
if (elenk !== 0) {
// free unused space in Lk
cnz = p;
}
}
// Postordering. The elimination is complete, but no permutation has been computed. All that is left
// of the graph is the assembly tree (ptr) and a set of dead nodes and elements (i is a dead node if
// nv[i] is zero and a dead element if nv[i] > 0). It is from this information only that the final permutation
// is computed. The tree is restored by unflipping all of ptr.
// fix assembly tree
for (i = 0; i < n; i++) {
cptr[i] = csFlip(cptr[i]);
}
for (j = 0; j <= n; j++) {
W[head + j] = -1;
}
// place unordered nodes in lists
for (j = n; j >= 0; j--) {
// skip if j is an element
if (W[nv + j] > 0) {
continue;
}
// place j in list of its parent
W[next + j] = W[head + cptr[j]];
W[head + cptr[j]] = j;
}
// place elements in lists
for (e = n; e >= 0; e--) {
// skip unless e is an element
if (W[nv + e] <= 0) {
continue;
}
if (cptr[e] !== -1) {
// place e in list of its parent
W[next + e] = W[head + cptr[e]];
W[head + cptr[e]] = e;
}
}
// postorder the assembly tree
for (k = 0, i = 0; i <= n; i++) {
if (cptr[i] === -1) {
k = csTdfs(i, k, W, head, next, P, w);
}
}
// remove last item in array
P.splice(P.length - 1, 1);
// return P
return P;
};
/**
* Creates the matrix that will be used by the approximate minimum degree ordering algorithm. The function accepts the matrix M as input and returns a permutation
* vector P. The amd algorithm operates on a symmetrix matrix, so one of three symmetric matrices is formed.
*
* Order: 0
* A natural ordering P=null matrix is returned.
*
* Order: 1
* Matrix must be square. This is appropriate for a Cholesky or LU factorization.
* P = M + M'
*
* Order: 2
* Dense columns from M' are dropped, M recreated from M'. This is appropriatefor LU factorization of unsymmetric matrices.
* P = M' * M
*
* Order: 3
* This is best used for QR factorization or LU factorization is matrix M has no dense rows. A dense row is a row with more than 10*sqr(columns) entries.
* P = M' * M
*/
function _createTargetMatrix(order, a, m, n, dense) {
// compute A'
var at = transpose(a);
// check order = 1, matrix must be square
if (order === 1 && n === m) {
// C = A + A'
return add(a, at);
}
// check order = 2, drop dense columns from M'
if (order === 2) {
// transpose arrays
var tindex = at._index;
var tptr = at._ptr;
// new column index
var p2 = 0;
// loop A' columns (rows)
for (var j = 0; j < m; j++) {
// column j of AT starts here
var p = tptr[j];
// new column j starts here
tptr[j] = p2;
// skip dense col j
if (tptr[j + 1] - p > dense) {
continue;
}
// map rows in column j of A
for (var p1 = tptr[j + 1]; p < p1; p++) {
tindex[p2++] = tindex[p];
}
}
// finalize AT
tptr[m] = p2;
// recreate A from new transpose matrix
a = transpose(at);
// use A' * A
return multiply(at, a);
}
// use A' * A, square or rectangular matrix
return multiply(at, a);
}
/**
* Initialize quotient graph. There are four kind of nodes and elements that must be represented:
*
* - A live node is a node i (or a supernode) that has not been selected as a pivot nad has not been merged into another supernode.
* - A dead node i is one that has been removed from the graph, having been absorved into r = flip(ptr[i]).
* - A live element e is one that is in the graph, having been formed when node e was selected as the pivot.
* - A dead element e is one that has benn absorved into a subsequent element s = flip(ptr[e]).
*/
function _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree) {
// Initialize quotient graph
for (var k = 0; k < n; k++) {
W[len + k] = cptr[k + 1] - cptr[k];
}
W[len + n] = 0;
// initialize workspace
for (var i = 0; i <= n; i++) {
// degree list i is empty
W[head + i] = -1;
last[i] = -1;
W[next + i] = -1;
// hash list i is empty
W[hhead + i] = -1;
// node i is just one node
W[nv + i] = 1;
// node i is alive
W[w + i] = 1;
// Ek of node i is empty
W[elen + i] = 0;
// degree of node i
W[degree + i] = W[len + i];
}
// clear w
var mark = _wclear(0, 0, W, w, n);
// n is a dead element
W[elen + n] = -2;
// n is a root of assembly tree
cptr[n] = -1;
// n is a dead element
W[w + n] = 0;
// return mark
return mark;
}
/**
* Initialize degree lists. Each node is placed in its degree lists. Nodes of zero degree are eliminated immediately. Nodes with
* degree >= dense are alsol eliminated and merged into a placeholder node n, a dead element. Thes nodes will appera last in the
* output permutation p.
*/
function _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next) {
// result
var nel = 0;
// loop columns
for (var i = 0; i < n; i++) {
// degree @ i
var d = W[degree + i];
// check node i is empty
if (d === 0) {
// element i is dead
W[elen + i] = -2;
nel++;
// i is a root of assembly tree
cptr[i] = -1;
W[w + i] = 0;
} else if (d > dense) {
// absorb i into element n
W[nv + i] = 0;
// node i is dead
W[elen + i] = -1;
nel++;
cptr[i] = csFlip(n);
W[nv + n]++;
} else {
var h = W[head + d];
if (h !== -1) {
last[h] = i;
}
// put node i in degree list d
W[next + i] = W[head + d];
W[head + d] = i;
}
}
return nel;
}
function _wclear(mark, lemax, W, w, n) {
if (mark < 2 || mark + lemax < 0) {
for (var k = 0; k < n; k++) {
if (W[w + k] !== 0) {
W[w + k] = 1;
}
}
mark = 2;
}
// at this point, W [0..n-1] < mark holds
return mark;
}
function _diag(i, j) {
return i !== j;
}
});

View File

@@ -0,0 +1,157 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { factory } from '../../../utils/factory.js';
import { csEreach } from './csEreach.js';
import { createCsSymperm } from './csSymperm.js';
var name = 'csChol';
var dependencies = ['divideScalar', 'sqrt', 'subtract', 'multiply', 'im', 're', 'conj', 'equal', 'smallerEq', 'SparseMatrix'];
export var createCsChol = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
divideScalar,
sqrt,
subtract,
multiply,
im,
re,
conj,
equal,
smallerEq,
SparseMatrix
} = _ref;
var csSymperm = createCsSymperm({
conj,
SparseMatrix
});
/**
* Computes the Cholesky factorization of matrix A. It computes L and P so
* L * L' = P * A * P'
*
* @param {Matrix} m The A Matrix to factorize, only upper triangular part used
* @param {Object} s The symbolic analysis from cs_schol()
*
* @return {Number} The numeric Cholesky factorization of A or null
*/
return function csChol(m, s) {
// validate input
if (!m) {
return null;
}
// m arrays
var size = m._size;
// columns
var n = size[1];
// symbolic analysis result
var parent = s.parent;
var cp = s.cp;
var pinv = s.pinv;
// L arrays
var lvalues = [];
var lindex = [];
var lptr = [];
// L
var L = new SparseMatrix({
values: lvalues,
index: lindex,
ptr: lptr,
size: [n, n]
});
// vars
var c = []; // (2 * n)
var x = []; // (n)
// compute C = P * A * P'
var cm = pinv ? csSymperm(m, pinv, 1) : m;
// C matrix arrays
var cvalues = cm._values;
var cindex = cm._index;
var cptr = cm._ptr;
// vars
var k, p;
// initialize variables
for (k = 0; k < n; k++) {
lptr[k] = c[k] = cp[k];
}
// compute L(k,:) for L*L' = C
for (k = 0; k < n; k++) {
// nonzero pattern of L(k,:)
var top = csEreach(cm, k, parent, c);
// x (0:k) is now zero
x[k] = 0;
// x = full(triu(C(:,k)))
for (p = cptr[k]; p < cptr[k + 1]; p++) {
if (cindex[p] <= k) {
x[cindex[p]] = cvalues[p];
}
}
// d = C(k,k)
var d = x[k];
// clear x for k+1st iteration
x[k] = 0;
// solve L(0:k-1,0:k-1) * x = C(:,k)
for (; top < n; top++) {
// s[top..n-1] is pattern of L(k,:)
var i = s[top];
// L(k,i) = x (i) / L(i,i)
var lki = divideScalar(x[i], lvalues[lptr[i]]);
// clear x for k+1st iteration
x[i] = 0;
for (p = lptr[i] + 1; p < c[i]; p++) {
// row
var r = lindex[p];
// update x[r]
x[r] = subtract(x[r], multiply(lvalues[p], lki));
}
// d = d - L(k,i)*L(k,i)
d = subtract(d, multiply(lki, conj(lki)));
p = c[i]++;
// store L(k,i) in column i
lindex[p] = k;
lvalues[p] = conj(lki);
}
// compute L(k,k)
if (smallerEq(re(d), 0) || !equal(im(d), 0)) {
// not pos def
return null;
}
p = c[k]++;
// store L(k,k) = sqrt(d) in column k
lindex[p] = k;
lvalues[p] = sqrt(d);
}
// finalize L
lptr[n] = cp[n];
// P matrix
var P;
// check we need to calculate P
if (pinv) {
// P arrays
var pvalues = [];
var pindex = [];
var pptr = [];
// create P matrix
for (p = 0; p < n; p++) {
// initialize ptr (one value per column)
pptr[p] = p;
// index (apply permutation vector)
pindex.push(pinv[p]);
// value 1
pvalues.push(1);
}
// update ptr
pptr[n] = n;
// P
P = new SparseMatrix({
values: pvalues,
index: pindex,
ptr: pptr,
size: [n, n]
});
}
// return L & P
return {
L,
P
};
};
});

View File

@@ -0,0 +1,126 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { factory } from '../../../utils/factory.js';
import { csLeaf } from './csLeaf.js';
var name = 'csCounts';
var dependencies = ['transpose'];
export var createCsCounts = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
transpose
} = _ref;
/**
* Computes the column counts using the upper triangular part of A.
* It transposes A internally, none of the input parameters are modified.
*
* @param {Matrix} a The sparse matrix A
*
* @param {Matrix} ata Count the columns of A'A instead
*
* @return An array of size n of the column counts or null on error
*/
return function (a, parent, post, ata) {
// check inputs
if (!a || !parent || !post) {
return null;
}
// a matrix arrays
var asize = a._size;
// rows and columns
var m = asize[0];
var n = asize[1];
// variables
var i, j, k, J, p, p0, p1;
// workspace size
var s = 4 * n + (ata ? n + m + 1 : 0);
// allocate workspace
var w = []; // (s)
var ancestor = 0; // first n entries
var maxfirst = n; // next n entries
var prevleaf = 2 * n; // next n entries
var first = 3 * n; // next n entries
var head = 4 * n; // next n + 1 entries (used when ata is true)
var next = 5 * n + 1; // last entries in workspace
// clear workspace w[0..s-1]
for (k = 0; k < s; k++) {
w[k] = -1;
}
// allocate result
var colcount = []; // (n)
// AT = A'
var at = transpose(a);
// at arrays
var tindex = at._index;
var tptr = at._ptr;
// find w[first + j]
for (k = 0; k < n; k++) {
j = post[k];
// colcount[j]=1 if j is a leaf
colcount[j] = w[first + j] === -1 ? 1 : 0;
for (; j !== -1 && w[first + j] === -1; j = parent[j]) {
w[first + j] = k;
}
}
// initialize ata if needed
if (ata) {
// invert post
for (k = 0; k < n; k++) {
w[post[k]] = k;
}
// loop rows (columns in AT)
for (i = 0; i < m; i++) {
// values in column i of AT
for (k = n, p0 = tptr[i], p1 = tptr[i + 1], p = p0; p < p1; p++) {
k = Math.min(k, w[tindex[p]]);
}
// place row i in linked list k
w[next + i] = w[head + k];
w[head + k] = i;
}
}
// each node in its own set
for (i = 0; i < n; i++) {
w[ancestor + i] = i;
}
for (k = 0; k < n; k++) {
// j is the kth node in postordered etree
j = post[k];
// check j is not a root
if (parent[j] !== -1) {
colcount[parent[j]]--;
}
// J=j for LL'=A case
for (J = ata ? w[head + k] : j; J !== -1; J = ata ? w[next + J] : -1) {
for (p = tptr[J]; p < tptr[J + 1]; p++) {
i = tindex[p];
var r = csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor);
// check A(i,j) is in skeleton
if (r.jleaf >= 1) {
colcount[j]++;
}
// check account for overlap in q
if (r.jleaf === 2) {
colcount[r.q]--;
}
}
}
if (parent[j] !== -1) {
w[ancestor + j] = parent[j];
}
}
// sum up colcount's of each child
for (j = 0; j < n; j++) {
if (parent[j] !== -1) {
colcount[parent[j]] += colcount[j];
}
}
return colcount;
};
});

View File

@@ -0,0 +1,28 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
/**
* It sets the p[i] equal to the sum of c[0] through c[i-1].
*
* @param {Array} ptr The Sparse Matrix ptr array
* @param {Array} c The Sparse Matrix ptr array
* @param {Number} n The number of columns
*/
export function csCumsum(ptr, c, n) {
// variables
var i;
var nz = 0;
for (i = 0; i < n; i++) {
// initialize ptr @ i
ptr[i] = nz;
// increment number of nonzeros
nz += c[i];
// also copy p[0..n-1] back into c[0..n-1]
c[i] = ptr[i];
}
// finalize ptr
ptr[n] = nz;
// return sum (c [0..n-1])
return nz;
}

View File

@@ -0,0 +1,76 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { csMarked } from './csMarked.js';
import { csMark } from './csMark.js';
import { csUnflip } from './csUnflip.js';
/**
* Depth-first search computes the nonzero pattern xi of the directed graph G (Matrix) starting
* at nodes in B (see csReach()).
*
* @param {Number} j The starting node for the DFS algorithm
* @param {Matrix} g The G matrix to search, ptr array modified, then restored
* @param {Number} top Start index in stack xi[top..n-1]
* @param {Number} k The kth column in B
* @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
* The first n entries is the nonzero pattern, the last n entries is the stack
* @param {Array} pinv The inverse row permutation vector, must be null for L * x = b
*
* @return {Number} New value of top
*/
export function csDfs(j, g, top, xi, pinv) {
// g arrays
var index = g._index;
var ptr = g._ptr;
var size = g._size;
// columns
var n = size[1];
// vars
var i, p, p2;
// initialize head
var head = 0;
// initialize the recursion stack
xi[0] = j;
// loop
while (head >= 0) {
// get j from the top of the recursion stack
j = xi[head];
// apply permutation vector
var jnew = pinv ? pinv[j] : j;
// check node j is marked
if (!csMarked(ptr, j)) {
// mark node j as visited
csMark(ptr, j);
// update stack (last n entries in xi)
xi[n + head] = jnew < 0 ? 0 : csUnflip(ptr[jnew]);
}
// node j done if no unvisited neighbors
var done = 1;
// examine all neighbors of j, stack (last n entries in xi)
for (p = xi[n + head], p2 = jnew < 0 ? 0 : csUnflip(ptr[jnew + 1]); p < p2; p++) {
// consider neighbor node i
i = index[p];
// check we have visited node i, skip it
if (csMarked(ptr, i)) {
continue;
}
// pause depth-first search of node j, update stack (last n entries in xi)
xi[n + head] = p;
// start dfs at node i
xi[++head] = i;
// node j is not done
done = 0;
// break, to start dfs(i)
break;
}
// check depth-first search at node j is done
if (done) {
// remove j from the recursion stack
head--;
// and place in the output stack
xi[--top] = j;
}
}
return top;
}

View File

@@ -0,0 +1,63 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { csMark } from './csMark.js';
import { csMarked } from './csMarked.js';
/**
* Find nonzero pattern of Cholesky L(k,1:k-1) using etree and triu(A(:,k))
*
* @param {Matrix} a The A matrix
* @param {Number} k The kth column in A
* @param {Array} parent The parent vector from the symbolic analysis result
* @param {Array} w The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
* The first n entries is the nonzero pattern, the last n entries is the stack
*
* @return {Number} The index for the nonzero pattern
*/
export function csEreach(a, k, parent, w) {
// a arrays
var aindex = a._index;
var aptr = a._ptr;
var asize = a._size;
// columns
var n = asize[1];
// initialize top
var top = n;
// vars
var p, p0, p1, len;
// mark node k as visited
csMark(w, k);
// loop values & index for column k
for (p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
// A(i,k) is nonzero
var i = aindex[p];
// only use upper triangular part of A
if (i > k) {
continue;
}
// traverse up etree
for (len = 0; !csMarked(w, i); i = parent[i]) {
// L(k,i) is nonzero, last n entries in w
w[n + len++] = i;
// mark i as visited
csMark(w, i);
}
while (len > 0) {
// decrement top & len
--top;
--len;
// push path onto stack, last n entries in w
w[n + top] = w[n + len];
}
}
// unmark all nodes
for (p = top; p < n; p++) {
// use stack value, last n entries in w
csMark(w, w[n + p]);
}
// unmark node k
csMark(w, k);
// s[top..n-1] contains pattern of L(k,:)
return top;
}

View File

@@ -0,0 +1,71 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
/**
* Computes the elimination tree of Matrix A (using triu(A)) or the
* elimination tree of A'A without forming A'A.
*
* @param {Matrix} a The A Matrix
* @param {boolean} ata A value of true the function computes the etree of A'A
*/
export function csEtree(a, ata) {
// check inputs
if (!a) {
return null;
}
// a arrays
var aindex = a._index;
var aptr = a._ptr;
var asize = a._size;
// rows & columns
var m = asize[0];
var n = asize[1];
// allocate result
var parent = []; // (n)
// allocate workspace
var w = []; // (n + (ata ? m : 0))
var ancestor = 0; // first n entries in w
var prev = n; // last m entries (ata = true)
var i, inext;
// check we are calculating A'A
if (ata) {
// initialize workspace
for (i = 0; i < m; i++) {
w[prev + i] = -1;
}
}
// loop columns
for (var k = 0; k < n; k++) {
// node k has no parent yet
parent[k] = -1;
// nor does k have an ancestor
w[ancestor + k] = -1;
// values in column k
for (var p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
// row
var r = aindex[p];
// node
i = ata ? w[prev + r] : r;
// traverse from i to k
for (; i !== -1 && i < k; i = inext) {
// inext = ancestor of i
inext = w[ancestor + i];
// path compression
w[ancestor + i] = k;
// check no anc., parent is k
if (inext === -1) {
parent[i] = k;
}
}
if (ata) {
w[prev + r] = k;
}
}
}
return parent;
}

View File

@@ -0,0 +1,58 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
/**
* Keeps entries in the matrix when the callback function returns true, removes the entry otherwise
*
* @param {Matrix} a The sparse matrix
* @param {function} callback The callback function, function will be invoked with the following args:
* - The entry row
* - The entry column
* - The entry value
* - The state parameter
* @param {any} other The state
*
* @return The number of nonzero elements in the matrix
*/
export function csFkeep(a, callback, other) {
// a arrays
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var asize = a._size;
// columns
var n = asize[1];
// nonzero items
var nz = 0;
// loop columns
for (var j = 0; j < n; j++) {
// get current location of col j
var p = aptr[j];
// record new location of col j
aptr[j] = nz;
for (; p < aptr[j + 1]; p++) {
// check we need to keep this item
if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) {
// keep A(i,j)
aindex[nz] = aindex[p];
// check we need to process values (pattern only)
if (avalues) {
avalues[nz] = avalues[p];
}
// increment nonzero items
nz++;
}
}
}
// finalize A
aptr[n] = nz;
// trim arrays
aindex.splice(nz, aindex.length - nz);
// check we need to process values (pattern only)
if (avalues) {
avalues.splice(nz, avalues.length - nz);
}
// return number of nonzero items
return nz;
}

View File

@@ -0,0 +1,13 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
/**
* This function "flips" its input about the integer -1.
*
* @param {Number} i The value to flip
*/
export function csFlip(i) {
// flip the value
return -i - 2;
}

View File

@@ -0,0 +1,33 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
/**
* Permutes a vector; x = P'b. In MATLAB notation, x(p)=b.
*
* @param {Array} p The permutation vector of length n. null value denotes identity
* @param {Array} b The input vector
*
* @return {Array} The output vector x = P'b
*/
export function csIpvec(p, b) {
// vars
var k;
var n = b.length;
var x = [];
// check permutation vector was provided, p = null denotes identity
if (p) {
// loop vector
for (k = 0; k < n; k++) {
// apply permutation
x[p[k]] = b[k];
}
} else {
// loop vector
for (k = 0; k < n; k++) {
// x[i] = b[i]
x[k] = b[k];
}
}
return x;
}

View File

@@ -0,0 +1,56 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
/**
* This function determines if j is a leaf of the ith row subtree.
* Consider A(i,j), node j in ith row subtree and return lca(jprev,j)
*
* @param {Number} i The ith row subtree
* @param {Number} j The node to test
* @param {Array} w The workspace array
* @param {Number} first The index offset within the workspace for the first array
* @param {Number} maxfirst The index offset within the workspace for the maxfirst array
* @param {Number} prevleaf The index offset within the workspace for the prevleaf array
* @param {Number} ancestor The index offset within the workspace for the ancestor array
*
* @return {Object}
*/
export function csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor) {
var s, sparent;
// our result
var jleaf = 0;
var q;
// check j is a leaf
if (i <= j || w[first + j] <= w[maxfirst + i]) {
return -1;
}
// update max first[j] seen so far
w[maxfirst + i] = w[first + j];
// jprev = previous leaf of ith subtree
var jprev = w[prevleaf + i];
w[prevleaf + i] = j;
// check j is first or subsequent leaf
if (jprev === -1) {
// 1st leaf, q = root of ith subtree
jleaf = 1;
q = i;
} else {
// update jleaf
jleaf = 2;
// q = least common ancester (jprev,j)
for (q = jprev; q !== w[ancestor + q]; q = w[ancestor + q]);
for (s = jprev; s !== q; s = sparent) {
// path compression
sparent = w[ancestor + s];
w[ancestor + s] = q;
}
}
return {
jleaf,
q
};
}

View File

@@ -0,0 +1,182 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { factory } from '../../../utils/factory.js';
import { createCsSpsolve } from './csSpsolve.js';
var name = 'csLu';
var dependencies = ['abs', 'divideScalar', 'multiply', 'subtract', 'larger', 'largerEq', 'SparseMatrix'];
export var createCsLu = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
abs,
divideScalar,
multiply,
subtract,
larger,
largerEq,
SparseMatrix
} = _ref;
var csSpsolve = createCsSpsolve({
divideScalar,
multiply,
subtract
});
/**
* Computes the numeric LU factorization of the sparse matrix A. Implements a Left-looking LU factorization
* algorithm that computes L and U one column at a tume. At the kth step, it access columns 1 to k-1 of L
* and column k of A. Given the fill-reducing column ordering q (see parameter s) computes L, U and pinv so
* L * U = A(p, q), where p is the inverse of pinv.
*
* @param {Matrix} m The A Matrix to factorize
* @param {Object} s The symbolic analysis from csSqr(). Provides the fill-reducing
* column ordering q
* @param {Number} tol Partial pivoting threshold (1 for partial pivoting)
*
* @return {Number} The numeric LU factorization of A or null
*/
return function csLu(m, s, tol) {
// validate input
if (!m) {
return null;
}
// m arrays
var size = m._size;
// columns
var n = size[1];
// symbolic analysis result
var q;
var lnz = 100;
var unz = 100;
// update symbolic analysis parameters
if (s) {
q = s.q;
lnz = s.lnz || lnz;
unz = s.unz || unz;
}
// L arrays
var lvalues = []; // (lnz)
var lindex = []; // (lnz)
var lptr = []; // (n + 1)
// L
var L = new SparseMatrix({
values: lvalues,
index: lindex,
ptr: lptr,
size: [n, n]
});
// U arrays
var uvalues = []; // (unz)
var uindex = []; // (unz)
var uptr = []; // (n + 1)
// U
var U = new SparseMatrix({
values: uvalues,
index: uindex,
ptr: uptr,
size: [n, n]
});
// inverse of permutation vector
var pinv = []; // (n)
// vars
var i, p;
// allocate arrays
var x = []; // (n)
var xi = []; // (2 * n)
// initialize variables
for (i = 0; i < n; i++) {
// clear workspace
x[i] = 0;
// no rows pivotal yet
pinv[i] = -1;
// no cols of L yet
lptr[i + 1] = 0;
}
// reset number of nonzero elements in L and U
lnz = 0;
unz = 0;
// compute L(:,k) and U(:,k)
for (var k = 0; k < n; k++) {
// update ptr
lptr[k] = lnz;
uptr[k] = unz;
// apply column permutations if needed
var col = q ? q[k] : k;
// solve triangular system, x = L\A(:,col)
var top = csSpsolve(L, m, col, xi, x, pinv, 1);
// find pivot
var ipiv = -1;
var a = -1;
// loop xi[] from top -> n
for (p = top; p < n; p++) {
// x[i] is nonzero
i = xi[p];
// check row i is not yet pivotal
if (pinv[i] < 0) {
// absolute value of x[i]
var xabs = abs(x[i]);
// check absoulte value is greater than pivot value
if (larger(xabs, a)) {
// largest pivot candidate so far
a = xabs;
ipiv = i;
}
} else {
// x(i) is the entry U(pinv[i],k)
uindex[unz] = pinv[i];
uvalues[unz++] = x[i];
}
}
// validate we found a valid pivot
if (ipiv === -1 || a <= 0) {
return null;
}
// update actual pivot column, give preference to diagonal value
if (pinv[col] < 0 && largerEq(abs(x[col]), multiply(a, tol))) {
ipiv = col;
}
// the chosen pivot
var pivot = x[ipiv];
// last entry in U(:,k) is U(k,k)
uindex[unz] = k;
uvalues[unz++] = pivot;
// ipiv is the kth pivot row
pinv[ipiv] = k;
// first entry in L(:,k) is L(k,k) = 1
lindex[lnz] = ipiv;
lvalues[lnz++] = 1;
// L(k+1:n,k) = x / pivot
for (p = top; p < n; p++) {
// row
i = xi[p];
// check x(i) is an entry in L(:,k)
if (pinv[i] < 0) {
// save unpermuted row in L
lindex[lnz] = i;
// scale pivot column
lvalues[lnz++] = divideScalar(x[i], pivot);
}
// x[0..n-1] = 0 for next k
x[i] = 0;
}
}
// update ptr
lptr[n] = lnz;
uptr[n] = unz;
// fix row indices of L for final pinv
for (p = 0; p < lnz; p++) {
lindex[p] = pinv[lindex[p]];
}
// trim arrays
lvalues.splice(lnz, lvalues.length - lnz);
lindex.splice(lnz, lindex.length - lnz);
uvalues.splice(unz, uvalues.length - unz);
uindex.splice(unz, uindex.length - unz);
// return LU factor
return {
L,
U,
pinv
};
};
});

View File

@@ -0,0 +1,16 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { csFlip } from './csFlip.js';
/**
* Marks the node at w[j]
*
* @param {Array} w The array
* @param {Number} j The array index
*/
export function csMark(w, j) {
// mark w[j]
w[j] = csFlip(w[j]);
}

View File

@@ -0,0 +1,14 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
/**
* Checks if the node at w[j] is marked
*
* @param {Array} w The array
* @param {Number} j The array index
*/
export function csMarked(w, j) {
// check node is marked
return w[j] < 0;
}

View File

@@ -0,0 +1,61 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
/**
* Permutes a sparse matrix C = P * A * Q
*
* @param {SparseMatrix} a The Matrix A
* @param {Array} pinv The row permutation vector
* @param {Array} q The column permutation vector
* @param {boolean} values Create a pattern matrix (false), values and pattern otherwise
*
* @return {Matrix} C = P * A * Q, null on error
*/
export function csPermute(a, pinv, q, values) {
// a arrays
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var asize = a._size;
var adt = a._datatype;
// rows & columns
var m = asize[0];
var n = asize[1];
// c arrays
var cvalues = values && a._values ? [] : null;
var cindex = []; // (aptr[n])
var cptr = []; // (n + 1)
// initialize vars
var nz = 0;
// loop columns
for (var k = 0; k < n; k++) {
// column k of C is column q[k] of A
cptr[k] = nz;
// apply column permutation
var j = q ? q[k] : k;
// loop values in column j of A
for (var t0 = aptr[j], t1 = aptr[j + 1], t = t0; t < t1; t++) {
// row i of A is row pinv[i] of C
var r = pinv ? pinv[aindex[t]] : aindex[t];
// index
cindex[nz] = r;
// check we need to populate values
if (cvalues) {
cvalues[nz] = avalues[t];
}
// increment number of nonzero elements
nz++;
}
}
// finalize the last column of C
cptr[n] = nz;
// return C matrix
return a.createSparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [m, n],
datatype: adt
});
}

View File

@@ -0,0 +1,52 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { csTdfs } from './csTdfs.js';
/**
* Post order a tree of forest
*
* @param {Array} parent The tree or forest
* @param {Number} n Number of columns
*/
export function csPost(parent, n) {
// check inputs
if (!parent) {
return null;
}
// vars
var k = 0;
var j;
// allocate result
var post = []; // (n)
// workspace, head: first n entries, next: next n entries, stack: last n entries
var w = []; // (3 * n)
var head = 0;
var next = n;
var stack = 2 * n;
// initialize workspace
for (j = 0; j < n; j++) {
// empty linked lists
w[head + j] = -1;
}
// traverse nodes in reverse order
for (j = n - 1; j >= 0; j--) {
// check j is a root
if (parent[j] === -1) {
continue;
}
// add j to list of its parent
w[next + j] = w[head + parent[j]];
w[head + parent[j]] = j;
}
// loop nodes
for (j = 0; j < n; j++) {
// skip j if it is not a root
if (parent[j] !== -1) {
continue;
}
// depth-first search
k = csTdfs(j, k, w, head, next, post, stack);
}
return post;
}

View File

@@ -0,0 +1,52 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { csMarked } from './csMarked.js';
import { csMark } from './csMark.js';
import { csDfs } from './csDfs.js';
/**
* The csReach function computes X = Reach(B), where B is the nonzero pattern of the n-by-1
* sparse column of vector b. The function returns the set of nodes reachable from any node in B. The
* nonzero pattern xi of the solution x to the sparse linear system Lx=b is given by X=Reach(B).
*
* @param {Matrix} g The G matrix
* @param {Matrix} b The B matrix
* @param {Number} k The kth column in B
* @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
* The first n entries is the nonzero pattern, the last n entries is the stack
* @param {Array} pinv The inverse row permutation vector
*
* @return {Number} The index for the nonzero pattern
*/
export function csReach(g, b, k, xi, pinv) {
// g arrays
var gptr = g._ptr;
var gsize = g._size;
// b arrays
var bindex = b._index;
var bptr = b._ptr;
// columns
var n = gsize[1];
// vars
var p, p0, p1;
// initialize top
var top = n;
// loop column indeces in B
for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) {
// node i
var i = bindex[p];
// check node i is marked
if (!csMarked(gptr, i)) {
// start a dfs at unmarked node i
top = csDfs(i, g, top, xi, pinv);
}
}
// loop columns from top -> n - 1
for (p = top; p < n; p++) {
// restore G
csMark(gptr, xi[p]);
}
return top;
}

View File

@@ -0,0 +1,84 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { csReach } from './csReach.js';
import { factory } from '../../../utils/factory.js';
var name = 'csSpsolve';
var dependencies = ['divideScalar', 'multiply', 'subtract'];
export var createCsSpsolve = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
divideScalar,
multiply,
subtract
} = _ref;
/**
* The function csSpsolve() computes the solution to G * x = bk, where bk is the
* kth column of B. When lo is true, the function assumes G = L is lower triangular with the
* diagonal entry as the first entry in each column. When lo is true, the function assumes G = U
* is upper triangular with the diagonal entry as the last entry in each column.
*
* @param {Matrix} g The G matrix
* @param {Matrix} b The B matrix
* @param {Number} k The kth column in B
* @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
* The first n entries is the nonzero pattern, the last n entries is the stack
* @param {Array} x The soluton to the linear system G * x = b
* @param {Array} pinv The inverse row permutation vector, must be null for L * x = b
* @param {boolean} lo The lower (true) upper triangular (false) flag
*
* @return {Number} The index for the nonzero pattern
*/
return function csSpsolve(g, b, k, xi, x, pinv, lo) {
// g arrays
var gvalues = g._values;
var gindex = g._index;
var gptr = g._ptr;
var gsize = g._size;
// columns
var n = gsize[1];
// b arrays
var bvalues = b._values;
var bindex = b._index;
var bptr = b._ptr;
// vars
var p, p0, p1, q;
// xi[top..n-1] = csReach(B(:,k))
var top = csReach(g, b, k, xi, pinv);
// clear x
for (p = top; p < n; p++) {
x[xi[p]] = 0;
}
// scatter b
for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) {
x[bindex[p]] = bvalues[p];
}
// loop columns
for (var px = top; px < n; px++) {
// x array index for px
var j = xi[px];
// apply permutation vector (U x = b), j maps to column J of G
var J = pinv ? pinv[j] : j;
// check column J is empty
if (J < 0) {
continue;
}
// column value indeces in G, p0 <= p < p1
p0 = gptr[J];
p1 = gptr[J + 1];
// x(j) /= G(j,j)
x[j] = divideScalar(x[j], gvalues[lo ? p0 : p1 - 1]);
// first entry L(j,j)
p = lo ? p0 + 1 : p0;
q = lo ? p1 : p1 - 1;
// loop
for (; p < q; p++) {
// row
var i = gindex[p];
// x(i) -= G(i,j) * x(j)
x[i] = subtract(x[i], multiply(gvalues[p], x[j]));
}
}
// return top of stack
return top;
};
});

View File

@@ -0,0 +1,179 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { csPermute } from './csPermute.js';
import { csPost } from './csPost.js';
import { csEtree } from './csEtree.js';
import { createCsAmd } from './csAmd.js';
import { createCsCounts } from './csCounts.js';
import { factory } from '../../../utils/factory.js';
var name = 'csSqr';
var dependencies = ['add', 'multiply', 'transpose'];
export var createCsSqr = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
add,
multiply,
transpose
} = _ref;
var csAmd = createCsAmd({
add,
multiply,
transpose
});
var csCounts = createCsCounts({
transpose
});
/**
* Symbolic ordering and analysis for QR and LU decompositions.
*
* @param {Number} order The ordering strategy (see csAmd for more details)
* @param {Matrix} a The A matrix
* @param {boolean} qr Symbolic ordering and analysis for QR decomposition (true) or
* symbolic ordering and analysis for LU decomposition (false)
*
* @return {Object} The Symbolic ordering and analysis for matrix A
*/
return function csSqr(order, a, qr) {
// a arrays
var aptr = a._ptr;
var asize = a._size;
// columns
var n = asize[1];
// vars
var k;
// symbolic analysis result
var s = {};
// fill-reducing ordering
s.q = csAmd(order, a);
// validate results
if (order && !s.q) {
return null;
}
// QR symbolic analysis
if (qr) {
// apply permutations if needed
var c = order ? csPermute(a, null, s.q, 0) : a;
// etree of C'*C, where C=A(:,q)
s.parent = csEtree(c, 1);
// post order elimination tree
var post = csPost(s.parent, n);
// col counts chol(C'*C)
s.cp = csCounts(c, s.parent, post, 1);
// check we have everything needed to calculate number of nonzero elements
if (c && s.parent && s.cp && _vcount(c, s)) {
// calculate number of nonzero elements
for (s.unz = 0, k = 0; k < n; k++) {
s.unz += s.cp[k];
}
}
} else {
// for LU factorization only, guess nnz(L) and nnz(U)
s.unz = 4 * aptr[n] + n;
s.lnz = s.unz;
}
// return result S
return s;
};
/**
* Compute nnz(V) = s.lnz, s.pinv, s.leftmost, s.m2 from A and s.parent
*/
function _vcount(a, s) {
// a arrays
var aptr = a._ptr;
var aindex = a._index;
var asize = a._size;
// rows & columns
var m = asize[0];
var n = asize[1];
// initialize s arrays
s.pinv = []; // (m + n)
s.leftmost = []; // (m)
// vars
var parent = s.parent;
var pinv = s.pinv;
var leftmost = s.leftmost;
// workspace, next: first m entries, head: next n entries, tail: next n entries, nque: next n entries
var w = []; // (m + 3 * n)
var next = 0;
var head = m;
var tail = m + n;
var nque = m + 2 * n;
// vars
var i, k, p, p0, p1;
// initialize w
for (k = 0; k < n; k++) {
// queue k is empty
w[head + k] = -1;
w[tail + k] = -1;
w[nque + k] = 0;
}
// initialize row arrays
for (i = 0; i < m; i++) {
leftmost[i] = -1;
}
// loop columns backwards
for (k = n - 1; k >= 0; k--) {
// values & index for column k
for (p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
// leftmost[i] = min(find(A(i,:)))
leftmost[aindex[p]] = k;
}
}
// scan rows in reverse order
for (i = m - 1; i >= 0; i--) {
// row i is not yet ordered
pinv[i] = -1;
k = leftmost[i];
// check row i is empty
if (k === -1) {
continue;
}
// first row in queue k
if (w[nque + k]++ === 0) {
w[tail + k] = i;
}
// put i at head of queue k
w[next + i] = w[head + k];
w[head + k] = i;
}
s.lnz = 0;
s.m2 = m;
// find row permutation and nnz(V)
for (k = 0; k < n; k++) {
// remove row i from queue k
i = w[head + k];
// count V(k,k) as nonzero
s.lnz++;
// add a fictitious row
if (i < 0) {
i = s.m2++;
}
// associate row i with V(:,k)
pinv[i] = k;
// skip if V(k+1:m,k) is empty
if (--nque[k] <= 0) {
continue;
}
// nque[k] is nnz (V(k+1:m,k))
s.lnz += w[nque + k];
// move all rows to parent of k
var pa = parent[k];
if (pa !== -1) {
if (w[nque + pa] === 0) {
w[tail + pa] = w[tail + k];
}
w[next + w[tail + k]] = w[head + pa];
w[head + pa] = w[next + i];
w[nque + pa] += w[nque + k];
}
}
for (i = 0; i < m; i++) {
if (pinv[i] < 0) {
pinv[i] = k++;
}
}
return true;
}
});

View File

@@ -0,0 +1,93 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { csCumsum } from './csCumsum.js';
import { factory } from '../../../utils/factory.js';
var name = 'csSymperm';
var dependencies = ['conj', 'SparseMatrix'];
export var createCsSymperm = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
conj,
SparseMatrix
} = _ref;
/**
* Computes the symmetric permutation of matrix A accessing only
* the upper triangular part of A.
*
* C = P * A * P'
*
* @param {Matrix} a The A matrix
* @param {Array} pinv The inverse of permutation vector
* @param {boolean} values Process matrix values (true)
*
* @return {Matrix} The C matrix, C = P * A * P'
*/
return function csSymperm(a, pinv, values) {
// A matrix arrays
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var asize = a._size;
// columns
var n = asize[1];
// C matrix arrays
var cvalues = values && avalues ? [] : null;
var cindex = []; // (nz)
var cptr = []; // (n + 1)
// variables
var i, i2, j, j2, p, p0, p1;
// create workspace vector
var w = []; // (n)
// count entries in each column of C
for (j = 0; j < n; j++) {
// column j of A is column j2 of C
j2 = pinv ? pinv[j] : j;
// loop values in column j
for (p0 = aptr[j], p1 = aptr[j + 1], p = p0; p < p1; p++) {
// row
i = aindex[p];
// skip lower triangular part of A
if (i > j) {
continue;
}
// row i of A is row i2 of C
i2 = pinv ? pinv[i] : i;
// column count of C
w[Math.max(i2, j2)]++;
}
}
// compute column pointers of C
csCumsum(cptr, w, n);
// loop columns
for (j = 0; j < n; j++) {
// column j of A is column j2 of C
j2 = pinv ? pinv[j] : j;
// loop values in column j
for (p0 = aptr[j], p1 = aptr[j + 1], p = p0; p < p1; p++) {
// row
i = aindex[p];
// skip lower triangular part of A
if (i > j) {
continue;
}
// row i of A is row i2 of C
i2 = pinv ? pinv[i] : i;
// C index for column j2
var q = w[Math.max(i2, j2)]++;
// update C index for entry q
cindex[q] = Math.min(i2, j2);
// check we need to process values
if (cvalues) {
cvalues[q] = i2 <= j2 ? avalues[p] : conj(avalues[p]);
}
}
}
// return C matrix
return new SparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [n, n]
});
};
});

View File

@@ -0,0 +1,42 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
/**
* Depth-first search and postorder of a tree rooted at node j
*
* @param {Number} j The tree node
* @param {Number} k
* @param {Array} w The workspace array
* @param {Number} head The index offset within the workspace for the head array
* @param {Number} next The index offset within the workspace for the next array
* @param {Array} post The post ordering array
* @param {Number} stack The index offset within the workspace for the stack array
*/
export function csTdfs(j, k, w, head, next, post, stack) {
// variables
var top = 0;
// place j on the stack
w[stack] = j;
// while (stack is not empty)
while (top >= 0) {
// p = top of stack
var p = w[stack + top];
// i = youngest child of p
var i = w[head + p];
if (i === -1) {
// p has no unordered children left
top--;
// node p is the kth postordered node
post[k++] = p;
} else {
// remove i from children of p
w[head + p] = w[next + i];
// increment top
++top;
// start dfs on child node i
w[stack + top] = i;
}
}
return k;
}

View File

@@ -0,0 +1,14 @@
// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source
import { csFlip } from './csFlip.js';
/**
* Flips the value if it is negative of returns the same value otherwise.
*
* @param {Number} i The value to flip
*/
export function csUnflip(i) {
// flip the value if it is negative
return i < 0 ? csFlip(i) : i;
}

View File

@@ -0,0 +1,118 @@
import { factory } from '../../utils/factory.js';
var name = 'sylvester';
var dependencies = ['typed', 'schur', 'matrixFromColumns', 'matrix', 'multiply', 'range', 'concat', 'transpose', 'index', 'subset', 'add', 'subtract', 'identity', 'lusolve', 'abs'];
export var createSylvester = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
schur,
matrixFromColumns,
matrix,
multiply,
range,
concat,
transpose,
index,
subset,
add,
subtract,
identity,
lusolve,
abs
} = _ref;
/**
*
* Solves the real-valued Sylvester equation AX+XB=C for X, where A, B and C are
* matrices of appropriate dimensions, being A and B squared. Notice that other
* equivalent definitions for the Sylvester equation exist and this function
* assumes the one presented in the original publication of the the Bartels-
* Stewart algorithm, which is implemented by this function.
* https://en.wikipedia.org/wiki/Sylvester_equation
*
* Syntax:
*
* math.sylvester(A, B, C)
*
* Examples:
*
* const A = [[-1, -2], [1, 1]]
* const B = [[2, -1], [1, -2]]
* const C = [[-3, 2], [3, 0]]
* math.sylvester(A, B, C) // returns DenseMatrix [[-0.25, 0.25], [1.5, -1.25]]
*
* See also:
*
* schur, lyap
*
* @param {Matrix | Array} A Matrix A
* @param {Matrix | Array} B Matrix B
* @param {Matrix | Array} C Matrix C
* @return {Matrix | Array} Matrix X, solving the Sylvester equation
*/
return typed(name, {
'Matrix, Matrix, Matrix': _sylvester,
'Array, Matrix, Matrix': function Array_Matrix_Matrix(A, B, C) {
return _sylvester(matrix(A), B, C);
},
'Array, Array, Matrix': function Array_Array_Matrix(A, B, C) {
return _sylvester(matrix(A), matrix(B), C);
},
'Array, Matrix, Array': function Array_Matrix_Array(A, B, C) {
return _sylvester(matrix(A), B, matrix(C));
},
'Matrix, Array, Matrix': function Matrix_Array_Matrix(A, B, C) {
return _sylvester(A, matrix(B), C);
},
'Matrix, Array, Array': function Matrix_Array_Array(A, B, C) {
return _sylvester(A, matrix(B), matrix(C));
},
'Matrix, Matrix, Array': function Matrix_Matrix_Array(A, B, C) {
return _sylvester(A, B, matrix(C));
},
'Array, Array, Array': function Array_Array_Array(A, B, C) {
return _sylvester(matrix(A), matrix(B), matrix(C)).toArray();
}
});
function _sylvester(A, B, C) {
var n = B.size()[0];
var m = A.size()[0];
var sA = schur(A);
var F = sA.T;
var U = sA.U;
var sB = schur(multiply(-1, B));
var G = sB.T;
var V = sB.U;
var D = multiply(multiply(transpose(U), C), V);
var all = range(0, m);
var y = [];
var hc = (a, b) => concat(a, b, 1);
var vc = (a, b) => concat(a, b, 0);
for (var k = 0; k < n; k++) {
if (k < n - 1 && abs(subset(G, index(k + 1, k))) > 1e-5) {
var RHS = vc(subset(D, index(all, k)), subset(D, index(all, k + 1)));
for (var j = 0; j < k; j++) {
RHS = add(RHS, vc(multiply(y[j], subset(G, index(j, k))), multiply(y[j], subset(G, index(j, k + 1)))));
}
var gkk = multiply(identity(m), multiply(-1, subset(G, index(k, k))));
var gmk = multiply(identity(m), multiply(-1, subset(G, index(k + 1, k))));
var gkm = multiply(identity(m), multiply(-1, subset(G, index(k, k + 1))));
var gmm = multiply(identity(m), multiply(-1, subset(G, index(k + 1, k + 1))));
var LHS = vc(hc(add(F, gkk), gmk), hc(gkm, add(F, gmm)));
var yAux = lusolve(LHS, RHS);
y[k] = yAux.subset(index(range(0, m), 0));
y[k + 1] = yAux.subset(index(range(m, 2 * m), 0));
k++;
} else {
var _RHS = subset(D, index(all, k));
for (var _j = 0; _j < k; _j++) {
_RHS = add(_RHS, multiply(y[_j], subset(G, index(_j, k))));
}
var _gkk = subset(G, index(k, k));
var _LHS = subtract(F, multiply(_gkk, identity(m)));
y[k] = lusolve(_LHS, _RHS);
}
}
var Y = matrix(matrixFromColumns(...y));
var X = multiply(U, multiply(Y, transpose(V)));
return X;
}
});

View File

@@ -0,0 +1,60 @@
import { isConstantNode } from '../../utils/is.js';
import { factory } from '../../utils/factory.js';
var name = 'symbolicEqual';
var dependencies = ['parse', 'simplify', 'typed', 'OperatorNode'];
export var createSymbolicEqual = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
parse,
simplify,
typed,
OperatorNode
} = _ref;
/**
* Attempts to determine if two expressions are symbolically equal, i.e.
* one is the result of valid algebraic manipulations on the other.
* Currently, this simply checks if the difference of the two expressions
* simplifies down to 0. So there are two important caveats:
* 1. whether two expressions are symbolically equal depends on the
* manipulations allowed. Therefore, this function takes an optional
* third argument, which are the options that control the behavior
* as documented for the `simplify()` function.
* 2. it is in general intractable to find the minimal simplification of
* an arbitrarily complicated expression. So while a `true` value
* of `symbolicEqual` ensures that the two expressions can be manipulated
* to match each other, a `false` value does not absolutely rule this out.
*
* Syntax:
*
* math.symbolicEqual(expr1, expr2)
* math.symbolicEqual(expr1, expr2, options)
*
* Examples:
*
* math.symbolicEqual('x*y', 'y*x') // Returns true
* math.symbolicEqual('x*y', 'y*x', {context: {multiply: {commutative: false}}}) // Returns false
* math.symbolicEqual('x/y', '(y*x^(-1))^(-1)') // Returns true
* math.symbolicEqual('abs(x)','x') // Returns false
* math.symbolicEqual('abs(x)','x', simplify.positiveContext) // Returns true
*
* See also:
*
* simplify, evaluate
*
* @param {Node|string} expr1 The first expression to compare
* @param {Node|string} expr2 The second expression to compare
* @param {Object} [options] Optional option object, passed to simplify
* @returns {boolean}
* Returns true if a valid manipulation making the expressions equal
* is found.
*/
function _symbolicEqual(e1, e2) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var diff = new OperatorNode('-', 'subtract', [e1, e2]);
var simplified = simplify(diff, {}, options);
return isConstantNode(simplified) && !simplified.value;
}
return typed(name, {
'Node, Node': _symbolicEqual,
'Node, Node, Object': _symbolicEqual
});
});

41
node_modules/mathjs/lib/esm/function/arithmetic/abs.js generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { absNumber } from '../../plain/number/index.js';
var name = 'abs';
var dependencies = ['typed'];
export var createAbs = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5) // returns number 3.5
* math.abs(-4.2) // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]) // returns Array [3, 5, 1, 0, 2]
*
* See also:
*
* sign
*
* @param {number | BigNumber | bigint | Fraction | Complex | Array | Matrix | Unit} x
* A number or matrix for which to get the absolute value
* @return {number | BigNumber | bigint | Fraction | Complex | Array | Matrix | Unit}
* Absolute value of `x`
*/
return typed(name, {
number: absNumber,
'Complex | BigNumber | Fraction | Unit': x => x.abs(),
bigint: x => x < 0n ? -x : x,
// deep map collection, skip zeros since abs(0) = 0
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self, true))
});
});

83
node_modules/mathjs/lib/esm/function/arithmetic/add.js generated vendored Normal file
View File

@@ -0,0 +1,83 @@
import { factory } from '../../utils/factory.js';
import { createMatAlgo01xDSid } from '../../type/matrix/utils/matAlgo01xDSid.js';
import { createMatAlgo04xSidSid } from '../../type/matrix/utils/matAlgo04xSidSid.js';
import { createMatAlgo10xSids } from '../../type/matrix/utils/matAlgo10xSids.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
var name = 'add';
var dependencies = ['typed', 'matrix', 'addScalar', 'equalScalar', 'DenseMatrix', 'SparseMatrix', 'concat'];
export var createAdd = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
addScalar,
equalScalar,
DenseMatrix,
SparseMatrix,
concat
} = _ref;
var matAlgo01xDSid = createMatAlgo01xDSid({
typed
});
var matAlgo04xSidSid = createMatAlgo04xSidSid({
typed,
equalScalar
});
var matAlgo10xSids = createMatAlgo10xSids({
typed,
DenseMatrix
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Add two or more values, `x + y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.add(x, y)
* math.add(x, y, z, ...)
*
* Examples:
*
* math.add(2, 3) // returns number 5
* math.add(2, 3, 4) // returns number 9
*
* const a = math.complex(2, 3)
* const b = math.complex(-4, 1)
* math.add(a, b) // returns Complex -2 + 4i
*
* math.add([1, 2, 3], 4) // returns Array [5, 6, 7]
*
* const c = math.unit('5 cm')
* const d = math.unit('2.1 mm')
* math.add(c, d) // returns Unit 52.1 mm
*
* math.add("2.3", "4") // returns number 6.3
*
* See also:
*
* subtract, sum
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x First value to add
* @param {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} y Second value to add
* @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} Sum of `x` and `y`
*/
return typed(name, {
'any, any': addScalar,
'any, any, ...any': typed.referToSelf(self => (x, y, rest) => {
var result = self(x, y);
for (var i = 0; i < rest.length; i++) {
result = self(result, rest[i]);
}
return result;
})
}, matrixAlgorithmSuite({
elop: addScalar,
DS: matAlgo01xDSid,
SS: matAlgo04xSidSid,
Ss: matAlgo10xSids
}));
});

View File

@@ -0,0 +1,49 @@
import { factory } from '../../utils/factory.js';
import { addNumber } from '../../plain/number/index.js';
var name = 'addScalar';
var dependencies = ['typed'];
export var createAddScalar = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Add two scalar values, `x + y`.
* This function is meant for internal use: it is used by the public function
* `add`
*
* This function does not support collections (Array or Matrix).
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit} x First value to add
* @param {number | BigNumber | bigint | Fraction | Complex} y Second value to add
* @return {number | BigNumber | bigint | Fraction | Complex | Unit} Sum of `x` and `y`
* @private
*/
return typed(name, {
'number, number': addNumber,
'Complex, Complex': function Complex_Complex(x, y) {
return x.add(y);
},
'BigNumber, BigNumber': function BigNumber_BigNumber(x, y) {
return x.plus(y);
},
'bigint, bigint': function bigint_bigint(x, y) {
return x + y;
},
'Fraction, Fraction': function Fraction_Fraction(x, y) {
return x.add(y);
},
'Unit, Unit': typed.referToSelf(self => (x, y) => {
if (x.value === null || x.value === undefined) {
throw new Error('Parameter x contains a unit with undefined value');
}
if (y.value === null || y.value === undefined) {
throw new Error('Parameter y contains a unit with undefined value');
}
if (!x.equalBase(y)) throw new Error('Units do not match');
var res = x.clone();
res.value = typed.find(self, [res.valueType(), y.valueType()])(res.value, y.value);
res.fixPrefix = false;
return res;
})
});
});

131
node_modules/mathjs/lib/esm/function/arithmetic/cbrt.js generated vendored Normal file
View File

@@ -0,0 +1,131 @@
import { factory } from '../../utils/factory.js';
import { isBigNumber, isComplex, isFraction } from '../../utils/is.js';
import { cbrtNumber } from '../../plain/number/index.js';
var name = 'cbrt';
var dependencies = ['config', 'typed', 'isNegative', 'unaryMinus', 'matrix', 'Complex', 'BigNumber', 'Fraction'];
export var createCbrt = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
config,
typed,
isNegative,
unaryMinus,
matrix,
Complex,
BigNumber,
Fraction
} = _ref;
/**
* Calculate the cubic root of a value.
*
* To avoid confusion with the matrix cube root, this function does not
* apply to matrices. For a matrix, to take the cube root elementwise,
* see the examples.
*
* Syntax:
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27) // returns 3
* math.cube(3) // returns 27
* math.cbrt(-64) // returns -4
* math.cbrt(math.unit('27 m^3')) // returns Unit 3 m
* math.map([27, 64, 125], x => math.cbrt(x)) // returns [3, 4, 5]
*
* const x = math.complex('8i')
* math.cbrt(x) // returns Complex 1.7320508075689 + i
* math.cbrt(x, true) // returns Matrix [
* // 1.7320508075689 + i
* // -1.7320508075689 + i
* // -2i
* // ]
*
* See also:
*
* square, sqrt, cube
*
* @param {number | BigNumber | Complex | Unit} x
* Value for which to calculate the cubic root.
* @param {boolean} [allRoots] Optional, false by default. Only applicable
* when `x` is a number or complex number. If true, all complex
* roots are returned, if false (default) the principal root is
* returned.
* @return {number | BigNumber | Complex | Unit}
* Returns the cubic root of `x`
*/
return typed(name, {
number: cbrtNumber,
// note: signature 'number, boolean' is also supported,
// created by typed as it knows how to convert number to Complex
Complex: _cbrtComplex,
'Complex, boolean': _cbrtComplex,
BigNumber: function BigNumber(x) {
return x.cbrt();
},
Unit: _cbrtUnit
});
/**
* Calculate the cubic root for a complex number
* @param {Complex} x
* @param {boolean} [allRoots] If true, the function will return an array
* with all three roots. If false or undefined,
* the principal root is returned.
* @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
* @private
*/
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3).exp());
if (allRoots) {
var all = [principal, new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 + Math.PI * 2 / 3).exp()), new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 - Math.PI * 2 / 3).exp())];
return config.matrix === 'Array' ? all : matrix(all);
} else {
return principal;
}
}
/**
* Calculate the cubic root for a Unit
* @param {Unit} x
* @return {Unit} Returns the cubic root of x
* @private
*/
function _cbrtUnit(x) {
if (x.value && isComplex(x.value)) {
var result = x.clone();
result.value = 1.0;
result = result.pow(1.0 / 3); // Compute the units
result.value = _cbrtComplex(x.value); // Compute the value
return result;
} else {
var negate = isNegative(x.value);
if (negate) {
x.value = unaryMinus(x.value);
}
// TODO: create a helper function for this
var third;
if (isBigNumber(x.value)) {
third = new BigNumber(1).div(3);
} else if (isFraction(x.value)) {
third = new Fraction(1, 3);
} else {
third = 1 / 3;
}
var _result = x.pow(third);
if (negate) {
_result.value = unaryMinus(_result.value);
}
return _result;
}
}
});

161
node_modules/mathjs/lib/esm/function/arithmetic/ceil.js generated vendored Normal file
View File

@@ -0,0 +1,161 @@
import Decimal from 'decimal.js';
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { nearlyEqual } from '../../utils/number.js';
import { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo12xSfs } from '../../type/matrix/utils/matAlgo12xSfs.js';
import { createMatAlgo14xDs } from '../../type/matrix/utils/matAlgo14xDs.js';
var name = 'ceil';
var dependencies = ['typed', 'config', 'round', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix'];
export var createCeilNumber = /* #__PURE__ */factory(name, ['typed', 'config', 'round'], _ref => {
var {
typed,
config,
round
} = _ref;
return typed(name, {
number: function number(x) {
if (nearlyEqual(x, round(x), config.relTol, config.absTol)) {
return round(x);
} else {
return Math.ceil(x);
}
},
'number, number': function number_number(x, n) {
if (nearlyEqual(x, round(x, n), config.relTol, config.absTol)) {
return round(x, n);
} else {
var [number, exponent] = "".concat(x, "e").split('e');
var result = Math.ceil(Number("".concat(number, "e").concat(Number(exponent) + n)));
[number, exponent] = "".concat(result, "e").split('e');
return Number("".concat(number, "e").concat(Number(exponent) - n));
}
}
});
});
export var createCeil = /* #__PURE__ */factory(name, dependencies, _ref2 => {
var {
typed,
config,
round,
matrix,
equalScalar,
zeros,
DenseMatrix
} = _ref2;
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo12xSfs = createMatAlgo12xSfs({
typed,
DenseMatrix
});
var matAlgo14xDs = createMatAlgo14xDs({
typed
});
var ceilNumber = createCeilNumber({
typed,
config,
round
});
/**
* Round a value towards plus infinity
* If `x` is complex, both real and imaginary part are rounded towards plus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.ceil(x)
* math.ceil(x, n)
*
* Examples:
*
* math.ceil(3.2) // returns number 4
* math.ceil(3.8) // returns number 4
* math.ceil(-4.2) // returns number -4
* math.ceil(-4.7) // returns number -4
*
* math.ceil(3.212, 2) // returns number 3.22
* math.ceil(3.288, 2) // returns number 3.29
* math.ceil(-4.212, 2) // returns number -4.21
* math.ceil(-4.782, 2) // returns number -4.78
*
* const c = math.complex(3.24, -2.71)
* math.ceil(c) // returns Complex 4 - 2i
* math.ceil(c, 1) // returns Complex 3.3 - 2.7i
*
* math.ceil([3.2, 3.8, -4.7]) // returns Array [4, 4, -4]
* math.ceil([3.21, 3.82, -4.71], 1) // returns Array [3.3, 3.9, -4.7]
*
* See also:
*
* floor, fix, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @param {number | BigNumber | Array} [n=0] Number of decimals
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
return typed('ceil', {
number: ceilNumber.signatures.number,
'number,number': ceilNumber.signatures['number,number'],
Complex: function Complex(x) {
return x.ceil();
},
'Complex, number': function Complex_number(x, n) {
return x.ceil(n);
},
'Complex, BigNumber': function Complex_BigNumber(x, n) {
return x.ceil(n.toNumber());
},
BigNumber: function BigNumber(x) {
if (bigNearlyEqual(x, round(x), config.relTol, config.absTol)) {
return round(x);
} else {
return x.ceil();
}
},
'BigNumber, BigNumber': function BigNumber_BigNumber(x, n) {
if (bigNearlyEqual(x, round(x, n), config.relTol, config.absTol)) {
return round(x, n);
} else {
return x.toDecimalPlaces(n.toNumber(), Decimal.ROUND_CEIL);
}
},
Fraction: function Fraction(x) {
return x.ceil();
},
'Fraction, number': function Fraction_number(x, n) {
return x.ceil(n);
},
'Fraction, BigNumber': function Fraction_BigNumber(x, n) {
return x.ceil(n.toNumber());
},
'Array | Matrix': typed.referToSelf(self => x => {
// deep map collection, skip zeros since ceil(0) = 0
return deepMap(x, self, true);
}),
'Array, number | BigNumber': typed.referToSelf(self => (x, n) => {
// deep map collection, skip zeros since ceil(0) = 0
return deepMap(x, i => self(i, n), true);
}),
'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
return matAlgo11xS0s(x, y, self, false);
}),
'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
return matAlgo14xDs(x, y, self, false);
}),
'number | Complex | Fraction | BigNumber, Array': typed.referToSelf(self => (x, y) => {
// use matrix implementation
return matAlgo14xDs(matrix(y), x, self, true).valueOf();
}),
'number | Complex | Fraction | BigNumber, Matrix': typed.referToSelf(self => (x, y) => {
if (equalScalar(x, 0)) return zeros(y.size(), y.storage());
if (y.storage() === 'dense') {
return matAlgo14xDs(y, x, self, true);
}
return matAlgo12xSfs(y, x, self, true);
})
});
});

View File

@@ -0,0 +1,52 @@
import { factory } from '../../utils/factory.js';
import { cubeNumber } from '../../plain/number/index.js';
var name = 'cube';
var dependencies = ['typed'];
export var createCube = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Compute the cube of a value, `x * x * x`.
* To avoid confusion with `pow(M,3)`, this function does not apply to matrices.
* If you wish to cube every entry of a matrix, see the examples.
*
* Syntax:
*
* math.cube(x)
*
* Examples:
*
* math.cube(2) // returns number 8
* math.pow(2, 3) // returns number 8
* math.cube(4) // returns number 64
* 4 * 4 * 4 // returns number 64
*
* math.map([1, 2, 3, 4], math.cube) // returns Array [1, 8, 27, 64]
*
* See also:
*
* multiply, square, pow, cbrt
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit} x Number for which to calculate the cube
* @return {number | BigNumber | bigint | Fraction | Complex | Unit} Cube of x
*/
return typed(name, {
number: cubeNumber,
Complex: function Complex(x) {
return x.mul(x).mul(x); // Is faster than pow(x, 3)
},
BigNumber: function BigNumber(x) {
return x.times(x).times(x);
},
bigint: function bigint(x) {
return x * x * x;
},
Fraction: function Fraction(x) {
return x.pow(3); // Is faster than mul()mul()mul()
},
Unit: function Unit(x) {
return x.pow(3);
}
});
});

View File

@@ -0,0 +1,79 @@
import { factory } from '../../utils/factory.js';
import { extend } from '../../utils/object.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo14xDs } from '../../type/matrix/utils/matAlgo14xDs.js';
var name = 'divide';
var dependencies = ['typed', 'matrix', 'multiply', 'equalScalar', 'divideScalar', 'inv'];
export var createDivide = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
multiply,
equalScalar,
divideScalar,
inv
} = _ref;
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo14xDs = createMatAlgo14xDs({
typed
});
/**
* Divide two values, `x / y`.
* To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
*
* Syntax:
*
* math.divide(x, y)
*
* Examples:
*
* math.divide(2, 3) // returns number 0.6666666666666666
*
* const a = math.complex(5, 14)
* const b = math.complex(4, 1)
* math.divide(a, b) // returns Complex 2 + 3i
*
* const c = [[7, -6], [13, -4]]
* const d = [[1, 2], [4, 3]]
* math.divide(c, d) // returns Array [[-9, 4], [-11, 6]]
*
* const e = math.unit('18 km')
* math.divide(e, 4.5) // returns Unit 4 km
*
* See also:
*
* multiply
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x Numerator
* @param {number | BigNumber | bigint | Fraction | Complex | Array | Matrix} y Denominator
* @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} Quotient, `x / y`
*/
return typed('divide', extend({
// we extend the signatures of divideScalar with signatures dealing with matrices
'Array | Matrix, Array | Matrix': function Array__Matrix_Array__Matrix(x, y) {
// TODO: implement matrix right division using pseudo inverse
// https://www.mathworks.nl/help/matlab/ref/mrdivide.html
// https://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html
// https://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour
return multiply(x, inv(y));
},
'DenseMatrix, any': function DenseMatrix_any(x, y) {
return matAlgo14xDs(x, y, divideScalar, false);
},
'SparseMatrix, any': function SparseMatrix_any(x, y) {
return matAlgo11xS0s(x, y, divideScalar, false);
},
'Array, any': function Array_any(x, y) {
// use matrix implementation
return matAlgo14xDs(matrix(x), y, divideScalar, false).valueOf();
},
'any, Array | Matrix': function any_Array__Matrix(x, y) {
return multiply(x, inv(y));
}
}, divideScalar.signatures));
});

View File

@@ -0,0 +1,40 @@
import { factory } from '../../utils/factory.js';
var name = 'divideScalar';
var dependencies = ['typed', 'numeric'];
export var createDivideScalar = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
numeric
} = _ref;
/**
* Divide two scalar values, `x / y`.
* This function is meant for internal use: it is used by the public functions
* `divide` and `inv`.
*
* This function does not support collections (Array or Matrix).
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit} x Numerator
* @param {number | BigNumber | bigint | Fraction | Complex} y Denominator
* @return {number | BigNumber | bigint | Fraction | Complex | Unit} Quotient, `x / y`
* @private
*/
return typed(name, {
'number, number': function number_number(x, y) {
return x / y;
},
'Complex, Complex': function Complex_Complex(x, y) {
return x.div(y);
},
'BigNumber, BigNumber': function BigNumber_BigNumber(x, y) {
return x.div(y);
},
'bigint, bigint': function bigint_bigint(x, y) {
return x / y;
},
'Fraction, Fraction': function Fraction_Fraction(x, y) {
return x.div(y);
},
'Unit, number | Complex | Fraction | BigNumber | Unit': (x, y) => x.divide(y),
'number | Fraction | Complex | BigNumber, Unit': (x, y) => y.divideInto(x)
});
});

View File

@@ -0,0 +1,78 @@
import { factory } from '../../utils/factory.js';
import { createMatAlgo02xDS0 } from '../../type/matrix/utils/matAlgo02xDS0.js';
import { createMatAlgo03xDSf } from '../../type/matrix/utils/matAlgo03xDSf.js';
import { createMatAlgo07xSSf } from '../../type/matrix/utils/matAlgo07xSSf.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo12xSfs } from '../../type/matrix/utils/matAlgo12xSfs.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
var name = 'dotDivide';
var dependencies = ['typed', 'matrix', 'equalScalar', 'divideScalar', 'DenseMatrix', 'concat'];
export var createDotDivide = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
divideScalar,
DenseMatrix,
concat
} = _ref;
var matAlgo02xDS0 = createMatAlgo02xDS0({
typed,
equalScalar
});
var matAlgo03xDSf = createMatAlgo03xDSf({
typed
});
var matAlgo07xSSf = createMatAlgo07xSSf({
typed,
DenseMatrix
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo12xSfs = createMatAlgo12xSfs({
typed,
DenseMatrix
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Divide two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotDivide(x, y)
*
* Examples:
*
* math.dotDivide(2, 4) // returns 0.5
*
* a = [[9, 5], [6, 1]]
* b = [[3, 2], [5, 2]]
*
* math.dotDivide(a, b) // returns [[3, 2.5], [1.2, 0.5]]
* math.divide(a, b) // returns [[1.75, 0.75], [-1.75, 2.25]]
*
* See also:
*
* divide, multiply, dotMultiply
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Denominator
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x ./ y`
*/
return typed(name, matrixAlgorithmSuite({
elop: divideScalar,
SS: matAlgo07xSSf,
DS: matAlgo03xDSf,
SD: matAlgo02xDS0,
Ss: matAlgo11xS0s,
sS: matAlgo12xSfs
}));
});

View File

@@ -0,0 +1,66 @@
import { factory } from '../../utils/factory.js';
import { createMatAlgo02xDS0 } from '../../type/matrix/utils/matAlgo02xDS0.js';
import { createMatAlgo09xS0Sf } from '../../type/matrix/utils/matAlgo09xS0Sf.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
var name = 'dotMultiply';
var dependencies = ['typed', 'matrix', 'equalScalar', 'multiplyScalar', 'concat'];
export var createDotMultiply = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
multiplyScalar,
concat
} = _ref;
var matAlgo02xDS0 = createMatAlgo02xDS0({
typed,
equalScalar
});
var matAlgo09xS0Sf = createMatAlgo09xS0Sf({
typed,
equalScalar
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Multiply two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotMultiply(x, y)
*
* Examples:
*
* math.dotMultiply(2, 4) // returns 8
*
* a = [[9, 5], [6, 1]]
* b = [[3, 2], [5, 2]]
*
* math.dotMultiply(a, b) // returns [[27, 10], [30, 2]]
* math.multiply(a, b) // returns [[52, 28], [23, 14]]
*
* See also:
*
* multiply, divide, dotDivide
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Left hand value
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Right hand value
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
*/
return typed(name, matrixAlgorithmSuite({
elop: multiplyScalar,
SS: matAlgo09xS0Sf,
DS: matAlgo02xDS0,
Ss: matAlgo11xS0s
}));
});

View File

@@ -0,0 +1,78 @@
import { factory } from '../../utils/factory.js';
import { createMatAlgo03xDSf } from '../../type/matrix/utils/matAlgo03xDSf.js';
import { createMatAlgo07xSSf } from '../../type/matrix/utils/matAlgo07xSSf.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo12xSfs } from '../../type/matrix/utils/matAlgo12xSfs.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
var name = 'dotPow';
var dependencies = ['typed', 'equalScalar', 'matrix', 'pow', 'DenseMatrix', 'concat'];
export var createDotPow = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
equalScalar,
matrix,
pow,
DenseMatrix,
concat
} = _ref;
var matAlgo03xDSf = createMatAlgo03xDSf({
typed
});
var matAlgo07xSSf = createMatAlgo07xSSf({
typed,
DenseMatrix
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo12xSfs = createMatAlgo12xSfs({
typed,
DenseMatrix
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
var powScalarSignatures = {};
for (var signature in pow.signatures) {
if (Object.prototype.hasOwnProperty.call(pow.signatures, signature)) {
if (!signature.includes('Matrix') && !signature.includes('Array')) {
powScalarSignatures[signature] = pow.signatures[signature];
}
}
}
var powScalar = typed(powScalarSignatures);
/**
* Calculates the power of x to y element wise.
*
* Syntax:
*
* math.dotPow(x, y)
*
* Examples:
*
* math.dotPow(2, 3) // returns number 8
*
* const a = [[1, 2], [4, 3]]
* math.dotPow(a, 2) // returns Array [[1, 4], [16, 9]]
* math.pow(a, 2) // returns Array [[9, 8], [16, 17]]
*
* See also:
*
* pow, sqrt, multiply
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base
* @param {number | BigNumber | Complex | Unit | Array | Matrix} y The exponent
* @return {number | BigNumber | Complex | Unit | Array | Matrix} The value of `x` to the power `y`
*/
return typed(name, matrixAlgorithmSuite({
elop: powScalar,
SS: matAlgo07xSSf,
DS: matAlgo03xDSf,
Ss: matAlgo11xS0s,
sS: matAlgo12xSfs
}));
});

48
node_modules/mathjs/lib/esm/function/arithmetic/exp.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
import { factory } from '../../utils/factory.js';
import { expNumber } from '../../plain/number/index.js';
var name = 'exp';
var dependencies = ['typed'];
export var createExp = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Calculate the exponential of a value.
* For matrices, if you want the matrix exponential of square matrix, use
* the `expm` function; if you want to take the exponential of each element,
* see the examples.
*
* Syntax:
*
* math.exp(x)
*
* Examples:
*
* math.exp(2) // returns number 7.3890560989306495
* math.pow(math.e, 2) // returns number 7.3890560989306495
* math.log(math.exp(2)) // returns number 2
*
* math.map([1, 2, 3], math.exp)
* // returns Array [
* // 2.718281828459045,
* // 7.3890560989306495,
* // 20.085536923187668
* // ]
*
* See also:
*
* expm1, expm, log, pow
*
* @param {number | BigNumber | Complex} x A number to exponentiate
* @return {number | BigNumber | Complex} Exponential of `x`
*/
return typed(name, {
number: expNumber,
Complex: function Complex(x) {
return x.exp();
},
BigNumber: function BigNumber(x) {
return x.exp();
}
});
});

View File

@@ -0,0 +1,53 @@
import { factory } from '../../utils/factory.js';
import { expm1Number } from '../../plain/number/index.js';
var name = 'expm1';
var dependencies = ['typed', 'Complex'];
export var createExpm1 = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
Complex: _Complex
} = _ref;
/**
* Calculate the value of subtracting 1 from the exponential value.
* This function is more accurate than `math.exp(x)-1` when `x` is near 0
* To avoid ambiguity with the matrix exponential `expm`, this function
* does not operate on matrices; if you wish to apply it elementwise, see
* the examples.
*
* Syntax:
*
* math.expm1(x)
*
* Examples:
*
* math.expm1(2) // returns number 6.38905609893065
* math.pow(math.e, 2) - 1 // returns number 6.3890560989306495
* math.expm1(1e-8) // returns number 1.0000000050000001e-8
* math.exp(1e-8) - 1 // returns number 9.9999999392253e-9
* math.log(math.expm1(2) + 1) // returns number 2
*
* math.map([1, 2, 3], math.expm1)
* // returns Array [
* // 1.718281828459045,
* // 6.3890560989306495,
* // 19.085536923187668
* // ]
*
* See also:
*
* exp, expm, log, pow
*
* @param {number | BigNumber | Complex} x The number to exponentiate
* @return {number | BigNumber | Complex} Exponential of `x`, minus one
*/
return typed(name, {
number: expm1Number,
Complex: function Complex(x) {
var r = Math.exp(x.re);
return new _Complex(r * Math.cos(x.im) - 1, r * Math.sin(x.im));
},
BigNumber: function BigNumber(x) {
return x.exp().minus(1);
}
});
});

126
node_modules/mathjs/lib/esm/function/arithmetic/fix.js generated vendored Normal file
View File

@@ -0,0 +1,126 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { createMatAlgo12xSfs } from '../../type/matrix/utils/matAlgo12xSfs.js';
import { createMatAlgo14xDs } from '../../type/matrix/utils/matAlgo14xDs.js';
var name = 'fix';
var dependencies = ['typed', 'Complex', 'matrix', 'ceil', 'floor', 'equalScalar', 'zeros', 'DenseMatrix'];
export var createFixNumber = /* #__PURE__ */factory(name, ['typed', 'ceil', 'floor'], _ref => {
var {
typed,
ceil,
floor
} = _ref;
return typed(name, {
number: function number(x) {
return x > 0 ? floor(x) : ceil(x);
},
'number, number': function number_number(x, n) {
return x > 0 ? floor(x, n) : ceil(x, n);
}
});
});
export var createFix = /* #__PURE__ */factory(name, dependencies, _ref2 => {
var {
typed,
Complex: _Complex,
matrix,
ceil,
floor,
equalScalar,
zeros,
DenseMatrix
} = _ref2;
var matAlgo12xSfs = createMatAlgo12xSfs({
typed,
DenseMatrix
});
var matAlgo14xDs = createMatAlgo14xDs({
typed
});
var fixNumber = createFixNumber({
typed,
ceil,
floor
});
/**
* Round a value towards zero.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.fix(x)
* math.fix(x,n)
*
* Examples:
*
* math.fix(3.2) // returns number 3
* math.fix(3.8) // returns number 3
* math.fix(-4.2) // returns number -4
* math.fix(-4.7) // returns number -4
*
* math.fix(3.12, 1) // returns number 3.1
* math.fix(3.18, 1) // returns number 3.1
* math.fix(-4.12, 1) // returns number -4.1
* math.fix(-4.17, 1) // returns number -4.1
*
* const c = math.complex(3.22, -2.78)
* math.fix(c) // returns Complex 3 - 2i
* math.fix(c, 1) // returns Complex 3.2 -2.7i
*
* math.fix([3.2, 3.8, -4.7]) // returns Array [3, 3, -4]
* math.fix([3.2, 3.8, -4.7], 1) // returns Array [3.2, 3.8, -4.7]
*
* See also:
*
* ceil, floor, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @param {number | BigNumber | Array} [n=0] Number of decimals
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
return typed('fix', {
number: fixNumber.signatures.number,
'number, number | BigNumber': fixNumber.signatures['number,number'],
Complex: function Complex(x) {
return new _Complex(x.re > 0 ? Math.floor(x.re) : Math.ceil(x.re), x.im > 0 ? Math.floor(x.im) : Math.ceil(x.im));
},
'Complex, number': function Complex_number(x, n) {
return new _Complex(x.re > 0 ? floor(x.re, n) : ceil(x.re, n), x.im > 0 ? floor(x.im, n) : ceil(x.im, n));
},
'Complex, BigNumber': function Complex_BigNumber(x, bn) {
var n = bn.toNumber();
return new _Complex(x.re > 0 ? floor(x.re, n) : ceil(x.re, n), x.im > 0 ? floor(x.im, n) : ceil(x.im, n));
},
BigNumber: function BigNumber(x) {
return x.isNegative() ? ceil(x) : floor(x);
},
'BigNumber, number | BigNumber': function BigNumber_number__BigNumber(x, n) {
return x.isNegative() ? ceil(x, n) : floor(x, n);
},
Fraction: function Fraction(x) {
return x.s < 0 ? x.ceil() : x.floor();
},
'Fraction, number | BigNumber': function Fraction_number__BigNumber(x, n) {
return x.s < 0 ? ceil(x, n) : floor(x, n);
},
'Array | Matrix': typed.referToSelf(self => x => {
// deep map collection, skip zeros since fix(0) = 0
return deepMap(x, self, true);
}),
'Array | Matrix, number | BigNumber': typed.referToSelf(self => (x, n) => {
// deep map collection, skip zeros since fix(0) = 0
return deepMap(x, i => self(i, n), true);
}),
'number | Complex | Fraction | BigNumber, Array': typed.referToSelf(self => (x, y) => {
// use matrix implementation
return matAlgo14xDs(matrix(y), x, self, true).valueOf();
}),
'number | Complex | Fraction | BigNumber, Matrix': typed.referToSelf(self => (x, y) => {
if (equalScalar(x, 0)) return zeros(y.size(), y.storage());
if (y.storage() === 'dense') {
return matAlgo14xDs(y, x, self, true);
}
return matAlgo12xSfs(y, x, self, true);
})
});
});

View File

@@ -0,0 +1,164 @@
import Decimal from 'decimal.js';
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { nearlyEqual } from '../../utils/number.js';
import { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo12xSfs } from '../../type/matrix/utils/matAlgo12xSfs.js';
import { createMatAlgo14xDs } from '../../type/matrix/utils/matAlgo14xDs.js';
var name = 'floor';
var dependencies = ['typed', 'config', 'round', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix'];
export var createFloorNumber = /* #__PURE__ */factory(name, ['typed', 'config', 'round'], _ref => {
var {
typed,
config,
round
} = _ref;
return typed(name, {
number: function number(x) {
if (nearlyEqual(x, round(x), config.relTol, config.absTol)) {
return round(x);
} else {
return Math.floor(x);
}
},
'number, number': function number_number(x, n) {
if (nearlyEqual(x, round(x, n), config.relTol, config.absTol)) {
return round(x, n);
} else {
var [number, exponent] = "".concat(x, "e").split('e');
var result = Math.floor(Number("".concat(number, "e").concat(Number(exponent) + n)));
[number, exponent] = "".concat(result, "e").split('e');
return Number("".concat(number, "e").concat(Number(exponent) - n));
}
}
});
});
export var createFloor = /* #__PURE__ */factory(name, dependencies, _ref2 => {
var {
typed,
config,
round,
matrix,
equalScalar,
zeros,
DenseMatrix
} = _ref2;
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo12xSfs = createMatAlgo12xSfs({
typed,
DenseMatrix
});
var matAlgo14xDs = createMatAlgo14xDs({
typed
});
var floorNumber = createFloorNumber({
typed,
config,
round
});
/**
* Round a value towards minus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.floor(x)
* math.floor(x, n)
*
* Examples:
*
* math.floor(3.2) // returns number 3
* math.floor(3.8) // returns number 3
* math.floor(-4.2) // returns number -5
* math.floor(-4.7) // returns number -5
*
* math.floor(3.212, 2) // returns number 3.21
* math.floor(3.288, 2) // returns number 3.28
* math.floor(-4.212, 2) // returns number -4.22
* math.floor(-4.782, 2) // returns number -4.79
*
* const c = math.complex(3.24, -2.71)
* math.floor(c) // returns Complex 3 - 3i
* math.floor(c, 1) // returns Complex 3.2 -2.8i
*
* math.floor([3.2, 3.8, -4.7]) // returns Array [3, 3, -5]
* math.floor([3.21, 3.82, -4.71], 1) // returns Array [3.2, 3.8, -4.8]
*
* math.floor(math.tau, [2, 3]) // returns Array [6.28, 6.283]
*
* // Note that floor(array, array) currently not implemented.
*
* See also:
*
* ceil, fix, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @param {number | BigNumber | Array} [n=0] Number of decimals
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
return typed('floor', {
number: floorNumber.signatures.number,
'number,number': floorNumber.signatures['number,number'],
Complex: function Complex(x) {
return x.floor();
},
'Complex, number': function Complex_number(x, n) {
return x.floor(n);
},
'Complex, BigNumber': function Complex_BigNumber(x, n) {
return x.floor(n.toNumber());
},
BigNumber: function BigNumber(x) {
if (bigNearlyEqual(x, round(x), config.relTol, config.absTol)) {
return round(x);
} else {
return x.floor();
}
},
'BigNumber, BigNumber': function BigNumber_BigNumber(x, n) {
if (bigNearlyEqual(x, round(x, n), config.relTol, config.absTol)) {
return round(x, n);
} else {
return x.toDecimalPlaces(n.toNumber(), Decimal.ROUND_FLOOR);
}
},
Fraction: function Fraction(x) {
return x.floor();
},
'Fraction, number': function Fraction_number(x, n) {
return x.floor(n);
},
'Fraction, BigNumber': function Fraction_BigNumber(x, n) {
return x.floor(n.toNumber());
},
'Array | Matrix': typed.referToSelf(self => x => {
// deep map collection, skip zeros since floor(0) = 0
return deepMap(x, self, true);
}),
'Array, number | BigNumber': typed.referToSelf(self => (x, n) => {
// deep map collection, skip zeros since ceil(0) = 0
return deepMap(x, i => self(i, n), true);
}),
'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
return matAlgo11xS0s(x, y, self, false);
}),
'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
return matAlgo14xDs(x, y, self, false);
}),
'number | Complex | Fraction | BigNumber, Array': typed.referToSelf(self => (x, y) => {
// use matrix implementation
return matAlgo14xDs(matrix(y), x, self, true).valueOf();
}),
'number | Complex | Fraction | BigNumber, Matrix': typed.referToSelf(self => (x, y) => {
if (equalScalar(x, 0)) return zeros(y.size(), y.storage());
if (y.storage() === 'dense') {
return matAlgo14xDs(y, x, self, true);
}
return matAlgo12xSfs(y, x, self, true);
})
});
});

153
node_modules/mathjs/lib/esm/function/arithmetic/gcd.js generated vendored Normal file
View File

@@ -0,0 +1,153 @@
import { isInteger } from '../../utils/number.js';
import { factory } from '../../utils/factory.js';
import { createMod } from './mod.js';
import { createMatAlgo01xDSid } from '../../type/matrix/utils/matAlgo01xDSid.js';
import { createMatAlgo04xSidSid } from '../../type/matrix/utils/matAlgo04xSidSid.js';
import { createMatAlgo10xSids } from '../../type/matrix/utils/matAlgo10xSids.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
import { ArgumentsError } from '../../error/ArgumentsError.js';
var name = 'gcd';
var dependencies = ['typed', 'config', 'round', 'matrix', 'equalScalar', 'zeros', 'BigNumber', 'DenseMatrix', 'concat'];
var gcdTypes = 'number | BigNumber | Fraction | Matrix | Array';
var gcdManyTypesSignature = "".concat(gcdTypes, ", ").concat(gcdTypes, ", ...").concat(gcdTypes);
function is1d(array) {
return !array.some(element => Array.isArray(element));
}
export var createGcd = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
config,
round,
equalScalar,
zeros,
BigNumber,
DenseMatrix,
concat
} = _ref;
var mod = createMod({
typed,
config,
round,
matrix,
equalScalar,
zeros,
DenseMatrix,
concat
});
var matAlgo01xDSid = createMatAlgo01xDSid({
typed
});
var matAlgo04xSidSid = createMatAlgo04xSidSid({
typed,
equalScalar
});
var matAlgo10xSids = createMatAlgo10xSids({
typed,
DenseMatrix
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Calculate the greatest common divisor for two or more values or arrays.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gcd(a, b)
* math.gcd(a, b, c, ...)
*
* Examples:
*
* math.gcd(8, 12) // returns 4
* math.gcd(-4, 6) // returns 2
* math.gcd(25, 15, -10) // returns 5
*
* math.gcd([8, -4], [12, 6]) // returns [4, 2]
*
* See also:
*
* lcm, xgcd
*
* @param {... number | BigNumber | Fraction | Array | Matrix} args Two or more integer numbers
* @return {number | BigNumber | Fraction | Array | Matrix} The greatest common divisor
*/
return typed(name, {
'number, number': _gcdNumber,
'BigNumber, BigNumber': _gcdBigNumber,
'Fraction, Fraction': (x, y) => x.gcd(y)
}, matrixAlgorithmSuite({
SS: matAlgo04xSidSid,
DS: matAlgo01xDSid,
Ss: matAlgo10xSids
}), {
[gcdManyTypesSignature]: typed.referToSelf(self => (a, b, args) => {
var res = self(a, b);
for (var i = 0; i < args.length; i++) {
res = self(res, args[i]);
}
return res;
}),
Array: typed.referToSelf(self => array => {
if (array.length === 1 && Array.isArray(array[0]) && is1d(array[0])) {
return self(...array[0]);
}
if (is1d(array)) {
return self(...array);
}
throw new ArgumentsError('gcd() supports only 1d matrices!');
}),
Matrix: typed.referToSelf(self => matrix => {
return self(matrix.toArray());
})
});
/**
* Calculate gcd for numbers
* @param {number} a
* @param {number} b
* @returns {number} Returns the greatest common denominator of a and b
* @private
*/
function _gcdNumber(a, b) {
if (!isInteger(a) || !isInteger(b)) {
throw new Error('Parameters in function gcd must be integer numbers');
}
// https://en.wikipedia.org/wiki/Euclidean_algorithm
var r;
while (b !== 0) {
r = mod(a, b);
a = b;
b = r;
}
return a < 0 ? -a : a;
}
/**
* Calculate gcd for BigNumbers
* @param {BigNumber} a
* @param {BigNumber} b
* @returns {BigNumber} Returns greatest common denominator of a and b
* @private
*/
function _gcdBigNumber(a, b) {
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function gcd must be integer numbers');
}
// https://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new BigNumber(0);
while (!b.isZero()) {
var r = mod(a, b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
});

View File

@@ -0,0 +1,77 @@
import { factory } from '../../utils/factory.js';
import { flatten } from '../../utils/array.js';
import { isComplex } from '../../utils/is.js';
var name = 'hypot';
var dependencies = ['typed', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'sqrt', 'smaller', 'isPositive'];
export var createHypot = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
abs,
addScalar,
divideScalar,
multiplyScalar,
sqrt,
smaller,
isPositive
} = _ref;
/**
* Calculate the hypotenuse of a list with values. The hypotenuse is defined as:
*
* hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
*
* For matrix input, the hypotenuse is calculated for all values in the matrix.
*
* Syntax:
*
* math.hypot(a, b, ...)
* math.hypot([a, b, c, ...])
*
* Examples:
*
* math.hypot(3, 4) // 5
* math.hypot(3, 4, 5) // 7.0710678118654755
* math.hypot([3, 4, 5]) // 7.0710678118654755
* math.hypot(-2) // 2
*
* See also:
*
* abs, norm
*
* @param {... number | BigNumber | Array | Matrix} args A list with numeric values or an Array or Matrix.
* Matrix and Array input is flattened and returns a
* single number for the whole matrix.
* @return {number | BigNumber} Returns the hypothenusa of the input values.
*/
return typed(name, {
'... number | BigNumber': _hypot,
Array: _hypot,
Matrix: M => _hypot(flatten(M.toArray()))
});
/**
* Calculate the hypotenuse for an Array with values
* @param {Array.<number | BigNumber>} args
* @return {number | BigNumber} Returns the result
* @private
*/
function _hypot(args) {
// code based on `hypot` from es6-shim:
// https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633
var result = 0;
var largest = 0;
for (var i = 0; i < args.length; i++) {
if (isComplex(args[i])) {
throw new TypeError('Unexpected type of argument to hypot');
}
var value = abs(args[i]);
if (smaller(largest, value)) {
result = multiplyScalar(result, multiplyScalar(divideScalar(largest, value), divideScalar(largest, value)));
result = addScalar(result, 1);
largest = value;
} else {
result = addScalar(result, isPositive(value) ? multiplyScalar(divideScalar(value, largest), divideScalar(value, largest)) : value);
}
}
return multiplyScalar(largest, sqrt(result));
}
});

View File

@@ -0,0 +1,55 @@
import { factory } from '../../utils/factory.js';
var name = 'invmod';
var dependencies = ['typed', 'config', 'BigNumber', 'xgcd', 'equal', 'smaller', 'mod', 'add', 'isInteger'];
export var createInvmod = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
BigNumber,
xgcd,
equal,
smaller,
mod,
add,
isInteger
} = _ref;
/**
* Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation `ax ≣ 1 (mod b)`
* See https://en.wikipedia.org/wiki/Modular_multiplicative_inverse.
*
* Syntax:
*
* math.invmod(a, b)
*
* Examples:
*
* math.invmod(8, 12) // returns NaN
* math.invmod(7, 13) // returns 2
* math.invmod(15151, 15122) // returns 10429
*
* See also:
*
* gcd, xgcd
*
* @param {number | BigNumber} a An integer number
* @param {number | BigNumber} b An integer number
* @return {number | BigNumber } Returns an integer number
* where `invmod(a,b)*a ≣ 1 (mod b)`
*/
return typed(name, {
'number, number': invmod,
'BigNumber, BigNumber': invmod
});
function invmod(a, b) {
if (!isInteger(a) || !isInteger(b)) throw new Error('Parameters in function invmod must be integer numbers');
a = mod(a, b);
if (equal(b, 0)) throw new Error('Divisor must be non zero');
var res = xgcd(a, b);
res = res.valueOf();
var [gcd, inv] = res;
if (!equal(gcd, BigNumber(1))) return NaN;
inv = mod(inv, b);
if (smaller(inv, BigNumber(0))) inv = add(inv, b);
return inv;
}
});

110
node_modules/mathjs/lib/esm/function/arithmetic/lcm.js generated vendored Normal file
View File

@@ -0,0 +1,110 @@
import { factory } from '../../utils/factory.js';
import { createMatAlgo02xDS0 } from '../../type/matrix/utils/matAlgo02xDS0.js';
import { createMatAlgo06xS0S0 } from '../../type/matrix/utils/matAlgo06xS0S0.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
import { lcmNumber } from '../../plain/number/index.js';
var name = 'lcm';
var dependencies = ['typed', 'matrix', 'equalScalar', 'concat'];
export var createLcm = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
concat
} = _ref;
var matAlgo02xDS0 = createMatAlgo02xDS0({
typed,
equalScalar
});
var matAlgo06xS0S0 = createMatAlgo06xS0S0({
typed,
equalScalar
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
var lcmTypes = 'number | BigNumber | Fraction | Matrix | Array';
var lcmManySignature = {};
lcmManySignature["".concat(lcmTypes, ", ").concat(lcmTypes, ", ...").concat(lcmTypes)] = typed.referToSelf(self => (a, b, args) => {
var res = self(a, b);
for (var i = 0; i < args.length; i++) {
res = self(res, args[i]);
}
return res;
});
/**
* Calculate the least common multiple for two or more values or arrays.
*
* lcm is defined as:
*
* lcm(a, b) = abs(a * b) / gcd(a, b)
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.lcm(a, b)
* math.lcm(a, b, c, ...)
*
* Examples:
*
* math.lcm(4, 6) // returns 12
* math.lcm(6, 21) // returns 42
* math.lcm(6, 21, 5) // returns 210
*
* math.lcm([4, 6], [6, 21]) // returns [12, 42]
*
* See also:
*
* gcd, xgcd
*
* @param {... number | BigNumber | Array | Matrix} args Two or more integer numbers
* @return {number | BigNumber | Array | Matrix} The least common multiple
*/
return typed(name, {
'number, number': lcmNumber,
'BigNumber, BigNumber': _lcmBigNumber,
'Fraction, Fraction': (x, y) => x.lcm(y)
}, matrixAlgorithmSuite({
SS: matAlgo06xS0S0,
DS: matAlgo02xDS0,
Ss: matAlgo11xS0s
}), lcmManySignature);
/**
* Calculate lcm for two BigNumbers
* @param {BigNumber} a
* @param {BigNumber} b
* @returns {BigNumber} Returns the least common multiple of a and b
* @private
*/
function _lcmBigNumber(a, b) {
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function lcm must be integer numbers');
}
if (a.isZero()) {
return a;
}
if (b.isZero()) {
return b;
}
// https://en.wikipedia.org/wiki/Euclidean_algorithm
// evaluate lcm here inline to reduce overhead
var prod = a.times(b);
while (!b.isZero()) {
var t = b;
b = a.mod(t);
a = t;
}
return prod.div(a).abs();
}
});

72
node_modules/mathjs/lib/esm/function/arithmetic/log.js generated vendored Normal file
View File

@@ -0,0 +1,72 @@
import { factory } from '../../utils/factory.js';
import { logNumber } from '../../plain/number/index.js';
var name = 'log';
var dependencies = ['config', 'typed', 'divideScalar', 'Complex'];
export var createLog = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
divideScalar,
Complex
} = _ref;
/**
* Calculate the logarithm of a value.
*
* To avoid confusion with the matrix logarithm, this function does not
* apply to matrices.
*
* Syntax:
*
* math.log(x)
* math.log(x, base)
*
* Examples:
*
* math.log(3.5) // returns 1.252762968495368
* math.exp(math.log(2.4)) // returns 2.4
*
* math.pow(10, 4) // returns 10000
* math.log(10000, 10) // returns 4
* math.log(10000) / math.log(10) // returns 4
*
* math.log(1024, 2) // returns 10
* math.pow(2, 10) // returns 1024
*
* See also:
*
* exp, log2, log10, log1p
*
* @param {number | BigNumber | Complex} x
* Value for which to calculate the logarithm.
* @param {number | BigNumber | Complex} [base=e]
* Optional base for the logarithm. If not provided, the natural
* logarithm of `x` is calculated.
* @return {number | BigNumber | Complex}
* Returns the logarithm of `x`
*/
return typed(name, {
number: function number(x) {
if (x >= 0 || config.predictable) {
return logNumber(x);
} else {
// negative value -> complex value computation
return new Complex(x, 0).log();
}
},
Complex: function Complex(x) {
return x.log();
},
BigNumber: function BigNumber(x) {
if (!x.isNegative() || config.predictable) {
return x.ln();
} else {
// downgrade to number, return Complex valued result
return new Complex(x.toNumber(), 0).log();
}
},
'any, any': typed.referToSelf(self => (x, base) => {
// calculate logarithm for a specified base, log(x, base)
return divideScalar(self(x), self(base));
})
});
});

View File

@@ -0,0 +1,59 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { log10Number } from '../../plain/number/index.js';
var name = 'log10';
var dependencies = ['typed', 'config', 'Complex'];
export var createLog10 = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
Complex: _Complex
} = _ref;
/**
* Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.log10(x)
*
* Examples:
*
* math.log10(0.00001) // returns -5
* math.log10(10000) // returns 4
* math.log(10000) / math.log(10) // returns 4
* math.pow(10, 4) // returns 10000
*
* See also:
*
* exp, log, log1p, log2
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* Value for which to calculate the logarithm.
* @return {number | BigNumber | Complex | Array | Matrix}
* Returns the 10-base logarithm of `x`
*/
return typed(name, {
number: function number(x) {
if (x >= 0 || config.predictable) {
return log10Number(x);
} else {
// negative value -> complex value computation
return new _Complex(x, 0).log().div(Math.LN10);
}
},
Complex: function Complex(x) {
return new _Complex(x).log().div(Math.LN10);
},
BigNumber: function BigNumber(x) {
if (!x.isNegative() || config.predictable) {
return x.log();
} else {
// downgrade to number, return Complex valued result
return new _Complex(x.toNumber(), 0).log().div(Math.LN10);
}
},
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
});
});

View File

@@ -0,0 +1,81 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { log1p as _log1p } from '../../utils/number.js';
var name = 'log1p';
var dependencies = ['typed', 'config', 'divideScalar', 'log', 'Complex'];
export var createLog1p = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
divideScalar,
log,
Complex
} = _ref;
/**
* Calculate the logarithm of a `value+1`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.log1p(x)
* math.log1p(x, base)
*
* Examples:
*
* math.log1p(2.5) // returns 1.252762968495368
* math.exp(math.log1p(1.4)) // returns 2.4
*
* math.pow(10, 4) // returns 10000
* math.log1p(9999, 10) // returns 4
* math.log1p(9999) / math.log(10) // returns 4
*
* See also:
*
* exp, log, log2, log10
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* Value for which to calculate the logarithm of `x+1`.
* @param {number | BigNumber | Complex} [base=e]
* Optional base for the logarithm. If not provided, the natural
* logarithm of `x+1` is calculated.
* @return {number | BigNumber | Complex | Array | Matrix}
* Returns the logarithm of `x+1`
*/
return typed(name, {
number: function number(x) {
if (x >= -1 || config.predictable) {
return _log1p(x);
} else {
// negative value -> complex value computation
return _log1pComplex(new Complex(x, 0));
}
},
Complex: _log1pComplex,
BigNumber: function BigNumber(x) {
var y = x.plus(1);
if (!y.isNegative() || config.predictable) {
return y.ln();
} else {
// downgrade to number, return Complex valued result
return _log1pComplex(new Complex(x.toNumber(), 0));
}
},
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self)),
'any, any': typed.referToSelf(self => (x, base) => {
// calculate logarithm for a specified base, log1p(x, base)
return divideScalar(self(x), log(base));
})
});
/**
* Calculate the natural logarithm of a complex number + 1
* @param {Complex} x
* @returns {Complex}
* @private
*/
function _log1pComplex(x) {
var xRe1p = x.re + 1;
return new Complex(Math.log(Math.sqrt(xRe1p * xRe1p + x.im * x.im)), Math.atan2(x.im, xRe1p));
}
});

View File

@@ -0,0 +1,68 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { log2Number } from '../../plain/number/index.js';
var name = 'log2';
var dependencies = ['typed', 'config', 'Complex'];
export var createLog2 = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
Complex
} = _ref;
/**
* Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.log2(x)
*
* Examples:
*
* math.log2(0.03125) // returns -5
* math.log2(16) // returns 4
* math.log2(16) / math.log2(2) // returns 4
* math.pow(2, 4) // returns 16
*
* See also:
*
* exp, log, log1p, log10
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* Value for which to calculate the logarithm.
* @return {number | BigNumber | Complex | Array | Matrix}
* Returns the 2-base logarithm of `x`
*/
return typed(name, {
number: function number(x) {
if (x >= 0 || config.predictable) {
return log2Number(x);
} else {
// negative value -> complex value computation
return _log2Complex(new Complex(x, 0));
}
},
Complex: _log2Complex,
BigNumber: function BigNumber(x) {
if (!x.isNegative() || config.predictable) {
return x.log(2);
} else {
// downgrade to number, return Complex valued result
return _log2Complex(new Complex(x.toNumber(), 0));
}
},
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
});
/**
* Calculate log2 for a complex value
* @param {Complex} x
* @returns {Complex}
* @private
*/
function _log2Complex(x) {
var newX = Math.sqrt(x.re * x.re + x.im * x.im);
return new Complex(Math.log2 ? Math.log2(newX) : Math.log(newX) / Math.LN2, Math.atan2(x.im, x.re) / Math.LN2);
}
});

133
node_modules/mathjs/lib/esm/function/arithmetic/mod.js generated vendored Normal file
View File

@@ -0,0 +1,133 @@
import { factory } from '../../utils/factory.js';
import { createFloor } from './floor.js';
import { createMatAlgo02xDS0 } from '../../type/matrix/utils/matAlgo02xDS0.js';
import { createMatAlgo03xDSf } from '../../type/matrix/utils/matAlgo03xDSf.js';
import { createMatAlgo05xSfSf } from '../../type/matrix/utils/matAlgo05xSfSf.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo12xSfs } from '../../type/matrix/utils/matAlgo12xSfs.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
var name = 'mod';
var dependencies = ['typed', 'config', 'round', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix', 'concat'];
export var createMod = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
round,
matrix,
equalScalar,
zeros,
DenseMatrix,
concat
} = _ref;
var floor = createFloor({
typed,
config,
round,
matrix,
equalScalar,
zeros,
DenseMatrix
});
var matAlgo02xDS0 = createMatAlgo02xDS0({
typed,
equalScalar
});
var matAlgo03xDSf = createMatAlgo03xDSf({
typed
});
var matAlgo05xSfSf = createMatAlgo05xSfSf({
typed,
equalScalar
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo12xSfs = createMatAlgo12xSfs({
typed,
DenseMatrix
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Calculates the modulus, the remainder of an integer division.
*
* For matrices, the function is evaluated element wise.
*
* The modulus is defined as:
*
* x - y * floor(x / y)
*
* See https://en.wikipedia.org/wiki/Modulo_operation.
*
* Syntax:
*
* math.mod(x, y)
*
* Examples:
*
* math.mod(8, 3) // returns 2
* math.mod(11, 2) // returns 1
*
* function isOdd(x) {
* return math.mod(x, 2) != 0
* }
*
* isOdd(2) // returns false
* isOdd(3) // returns true
*
* See also:
*
* divide
*
* @param {number | BigNumber | bigint | Fraction | Array | Matrix} x Dividend
* @param {number | BigNumber | bigint | Fraction | Array | Matrix} y Divisor
* @return {number | BigNumber | bigint | Fraction | Array | Matrix} Returns the remainder of `x` divided by `y`.
*/
return typed(name, {
'number, number': _modNumber,
'BigNumber, BigNumber': function BigNumber_BigNumber(x, y) {
return y.isZero() ? x : x.sub(y.mul(floor(x.div(y))));
},
'bigint, bigint': function bigint_bigint(x, y) {
if (y === 0n) {
return x;
}
if (x < 0) {
var m = x % y;
return m === 0n ? m : m + y;
}
return x % y;
},
'Fraction, Fraction': function Fraction_Fraction(x, y) {
return y.equals(0) ? x : x.sub(y.mul(floor(x.div(y))));
}
}, matrixAlgorithmSuite({
SS: matAlgo05xSfSf,
DS: matAlgo03xDSf,
SD: matAlgo02xDS0,
Ss: matAlgo11xS0s,
sS: matAlgo12xSfs
}));
/**
* Calculate the modulus of two numbers
* @param {number} x
* @param {number} y
* @returns {number} res
* @private
*/
function _modNumber(x, y) {
// We don't use JavaScript's % operator here as this doesn't work
// correctly for x < 0 and x === 0
// see https://en.wikipedia.org/wiki/Modulo_operation
// We use mathjs floor to handle errors associated with
// precision float approximation
return y === 0 ? x : x - y * floor(x / y);
}
});

View File

@@ -0,0 +1,880 @@
import { factory } from '../../utils/factory.js';
import { isMatrix } from '../../utils/is.js';
import { arraySize } from '../../utils/array.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo14xDs } from '../../type/matrix/utils/matAlgo14xDs.js';
var name = 'multiply';
var dependencies = ['typed', 'matrix', 'addScalar', 'multiplyScalar', 'equalScalar', 'dot'];
export var createMultiply = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
addScalar,
multiplyScalar,
equalScalar,
dot
} = _ref;
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo14xDs = createMatAlgo14xDs({
typed
});
function _validateMatrixDimensions(size1, size2) {
// check left operand dimensions
switch (size1.length) {
case 1:
// check size2
switch (size2.length) {
case 1:
// Vector x Vector
if (size1[0] !== size2[0]) {
// throw error
throw new RangeError('Dimension mismatch in multiplication. Vectors must have the same length');
}
break;
case 2:
// Vector x Matrix
if (size1[0] !== size2[0]) {
// throw error
throw new RangeError('Dimension mismatch in multiplication. Vector length (' + size1[0] + ') must match Matrix rows (' + size2[0] + ')');
}
break;
default:
throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
}
break;
case 2:
// check size2
switch (size2.length) {
case 1:
// Matrix x Vector
if (size1[1] !== size2[0]) {
// throw error
throw new RangeError('Dimension mismatch in multiplication. Matrix columns (' + size1[1] + ') must match Vector length (' + size2[0] + ')');
}
break;
case 2:
// Matrix x Matrix
if (size1[1] !== size2[0]) {
// throw error
throw new RangeError('Dimension mismatch in multiplication. Matrix A columns (' + size1[1] + ') must match Matrix B rows (' + size2[0] + ')');
}
break;
default:
throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
}
break;
default:
throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix A has ' + size1.length + ' dimensions)');
}
}
/**
* C = A * B
*
* @param {Matrix} a Dense Vector (N)
* @param {Matrix} b Dense Vector (N)
*
* @return {number} Scalar value
*/
function _multiplyVectorVector(a, b, n) {
// check empty vector
if (n === 0) {
throw new Error('Cannot multiply two empty vectors');
}
return dot(a, b);
}
/**
* C = A * B
*
* @param {Matrix} a Dense Vector (M)
* @param {Matrix} b Matrix (MxN)
*
* @return {Matrix} Dense Vector (N)
*/
function _multiplyVectorMatrix(a, b) {
// process storage
if (b.storage() !== 'dense') {
throw new Error('Support for SparseMatrix not implemented');
}
return _multiplyVectorDenseMatrix(a, b);
}
/**
* C = A * B
*
* @param {Matrix} a Dense Vector (M)
* @param {Matrix} b Dense Matrix (MxN)
*
* @return {Matrix} Dense Vector (N)
*/
function _multiplyVectorDenseMatrix(a, b) {
// a dense
var adata = a._data;
var asize = a._size;
var adt = a._datatype || a.getDataType();
// b dense
var bdata = b._data;
var bsize = b._size;
var bdt = b._datatype || b.getDataType();
// rows & columns
var alength = asize[0];
var bcolumns = bsize[1];
// datatype
var dt;
// addScalar signature to use
var af = addScalar;
// multiplyScalar signature to use
var mf = multiplyScalar;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
}
// result
var c = [];
// loop matrix columns
for (var j = 0; j < bcolumns; j++) {
// sum (do not initialize it with zero)
var sum = mf(adata[0], bdata[0][j]);
// loop vector
for (var i = 1; i < alength; i++) {
// multiply & accumulate
sum = af(sum, mf(adata[i], bdata[i][j]));
}
c[j] = sum;
}
// return matrix
return a.createDenseMatrix({
data: c,
size: [bcolumns],
datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
});
}
/**
* C = A * B
*
* @param {Matrix} a Matrix (MxN)
* @param {Matrix} b Dense Vector (N)
*
* @return {Matrix} Dense Vector (M)
*/
var _multiplyMatrixVector = typed('_multiplyMatrixVector', {
'DenseMatrix, any': _multiplyDenseMatrixVector,
'SparseMatrix, any': _multiplySparseMatrixVector
});
/**
* C = A * B
*
* @param {Matrix} a Matrix (MxN)
* @param {Matrix} b Matrix (NxC)
*
* @return {Matrix} Matrix (MxC)
*/
var _multiplyMatrixMatrix = typed('_multiplyMatrixMatrix', {
'DenseMatrix, DenseMatrix': _multiplyDenseMatrixDenseMatrix,
'DenseMatrix, SparseMatrix': _multiplyDenseMatrixSparseMatrix,
'SparseMatrix, DenseMatrix': _multiplySparseMatrixDenseMatrix,
'SparseMatrix, SparseMatrix': _multiplySparseMatrixSparseMatrix
});
/**
* C = A * B
*
* @param {Matrix} a DenseMatrix (MxN)
* @param {Matrix} b Dense Vector (N)
*
* @return {Matrix} Dense Vector (M)
*/
function _multiplyDenseMatrixVector(a, b) {
// a dense
var adata = a._data;
var asize = a._size;
var adt = a._datatype || a.getDataType();
// b dense
var bdata = b._data;
var bdt = b._datatype || b.getDataType();
// rows & columns
var arows = asize[0];
var acolumns = asize[1];
// datatype
var dt;
// addScalar signature to use
var af = addScalar;
// multiplyScalar signature to use
var mf = multiplyScalar;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
}
// result
var c = [];
// loop matrix a rows
for (var i = 0; i < arows; i++) {
// current row
var row = adata[i];
// sum (do not initialize it with zero)
var sum = mf(row[0], bdata[0]);
// loop matrix a columns
for (var j = 1; j < acolumns; j++) {
// multiply & accumulate
sum = af(sum, mf(row[j], bdata[j]));
}
c[i] = sum;
}
// return matrix
return a.createDenseMatrix({
data: c,
size: [arows],
datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
});
}
/**
* C = A * B
*
* @param {Matrix} a DenseMatrix (MxN)
* @param {Matrix} b DenseMatrix (NxC)
*
* @return {Matrix} DenseMatrix (MxC)
*/
function _multiplyDenseMatrixDenseMatrix(a, b) {
// getDataType()
// a dense
var adata = a._data;
var asize = a._size;
var adt = a._datatype || a.getDataType();
// b dense
var bdata = b._data;
var bsize = b._size;
var bdt = b._datatype || b.getDataType();
// rows & columns
var arows = asize[0];
var acolumns = asize[1];
var bcolumns = bsize[1];
// datatype
var dt;
// addScalar signature to use
var af = addScalar;
// multiplyScalar signature to use
var mf = multiplyScalar;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed' && adt !== 'mixed') {
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
}
// result
var c = [];
// loop matrix a rows
for (var i = 0; i < arows; i++) {
// current row
var row = adata[i];
// initialize row array
c[i] = [];
// loop matrix b columns
for (var j = 0; j < bcolumns; j++) {
// sum (avoid initializing sum to zero)
var sum = mf(row[0], bdata[0][j]);
// loop matrix a columns
for (var x = 1; x < acolumns; x++) {
// multiply & accumulate
sum = af(sum, mf(row[x], bdata[x][j]));
}
c[i][j] = sum;
}
}
// return matrix
return a.createDenseMatrix({
data: c,
size: [arows, bcolumns],
datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
});
}
/**
* C = A * B
*
* @param {Matrix} a DenseMatrix (MxN)
* @param {Matrix} b SparseMatrix (NxC)
*
* @return {Matrix} SparseMatrix (MxC)
*/
function _multiplyDenseMatrixSparseMatrix(a, b) {
// a dense
var adata = a._data;
var asize = a._size;
var adt = a._datatype || a.getDataType();
// b sparse
var bvalues = b._values;
var bindex = b._index;
var bptr = b._ptr;
var bsize = b._size;
var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();
// validate b matrix
if (!bvalues) {
throw new Error('Cannot multiply Dense Matrix times Pattern only Matrix');
}
// rows & columns
var arows = asize[0];
var bcolumns = bsize[1];
// datatype
var dt;
// addScalar signature to use
var af = addScalar;
// multiplyScalar signature to use
var mf = multiplyScalar;
// equalScalar signature to use
var eq = equalScalar;
// zero value
var zero = 0;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
eq = typed.find(equalScalar, [dt, dt]);
// convert 0 to the same datatype
zero = typed.convert(0, dt);
}
// result
var cvalues = [];
var cindex = [];
var cptr = [];
// c matrix
var c = b.createSparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [arows, bcolumns],
datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
});
// loop b columns
for (var jb = 0; jb < bcolumns; jb++) {
// update ptr
cptr[jb] = cindex.length;
// indeces in column jb
var kb0 = bptr[jb];
var kb1 = bptr[jb + 1];
// do not process column jb if no data exists
if (kb1 > kb0) {
// last row mark processed
var last = 0;
// loop a rows
for (var i = 0; i < arows; i++) {
// column mark
var mark = i + 1;
// C[i, jb]
var cij = void 0;
// values in b column j
for (var kb = kb0; kb < kb1; kb++) {
// row
var ib = bindex[kb];
// check value has been initialized
if (last !== mark) {
// first value in column jb
cij = mf(adata[i][ib], bvalues[kb]);
// update mark
last = mark;
} else {
// accumulate value
cij = af(cij, mf(adata[i][ib], bvalues[kb]));
}
}
// check column has been processed and value != 0
if (last === mark && !eq(cij, zero)) {
// push row & value
cindex.push(i);
cvalues.push(cij);
}
}
}
}
// update ptr
cptr[bcolumns] = cindex.length;
// return sparse matrix
return c;
}
/**
* C = A * B
*
* @param {Matrix} a SparseMatrix (MxN)
* @param {Matrix} b Dense Vector (N)
*
* @return {Matrix} SparseMatrix (M, 1)
*/
function _multiplySparseMatrixVector(a, b) {
// a sparse
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
// validate a matrix
if (!avalues) {
throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
}
// b dense
var bdata = b._data;
var bdt = b._datatype || b.getDataType();
// rows & columns
var arows = a._size[0];
var brows = b._size[0];
// result
var cvalues = [];
var cindex = [];
var cptr = [];
// datatype
var dt;
// addScalar signature to use
var af = addScalar;
// multiplyScalar signature to use
var mf = multiplyScalar;
// equalScalar signature to use
var eq = equalScalar;
// zero value
var zero = 0;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
eq = typed.find(equalScalar, [dt, dt]);
// convert 0 to the same datatype
zero = typed.convert(0, dt);
}
// workspace
var x = [];
// vector with marks indicating a value x[i] exists in a given column
var w = [];
// update ptr
cptr[0] = 0;
// rows in b
for (var ib = 0; ib < brows; ib++) {
// b[ib]
var vbi = bdata[ib];
// check b[ib] != 0, avoid loops
if (!eq(vbi, zero)) {
// A values & index in ib column
for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
// a row
var ia = aindex[ka];
// check value exists in current j
if (!w[ia]) {
// ia is new entry in j
w[ia] = true;
// add i to pattern of C
cindex.push(ia);
// x(ia) = A
x[ia] = mf(vbi, avalues[ka]);
} else {
// i exists in C already
x[ia] = af(x[ia], mf(vbi, avalues[ka]));
}
}
}
}
// copy values from x to column jb of c
for (var p1 = cindex.length, p = 0; p < p1; p++) {
// row
var ic = cindex[p];
// copy value
cvalues[p] = x[ic];
}
// update ptr
cptr[1] = cindex.length;
// matrix to return
return a.createSparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [arows, 1],
datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
});
}
/**
* C = A * B
*
* @param {Matrix} a SparseMatrix (MxN)
* @param {Matrix} b DenseMatrix (NxC)
*
* @return {Matrix} SparseMatrix (MxC)
*/
function _multiplySparseMatrixDenseMatrix(a, b) {
// a sparse
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
// validate a matrix
if (!avalues) {
throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
}
// b dense
var bdata = b._data;
var bdt = b._datatype || b.getDataType();
// rows & columns
var arows = a._size[0];
var brows = b._size[0];
var bcolumns = b._size[1];
// datatype
var dt;
// addScalar signature to use
var af = addScalar;
// multiplyScalar signature to use
var mf = multiplyScalar;
// equalScalar signature to use
var eq = equalScalar;
// zero value
var zero = 0;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
eq = typed.find(equalScalar, [dt, dt]);
// convert 0 to the same datatype
zero = typed.convert(0, dt);
}
// result
var cvalues = [];
var cindex = [];
var cptr = [];
// c matrix
var c = a.createSparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [arows, bcolumns],
datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
});
// workspace
var x = [];
// vector with marks indicating a value x[i] exists in a given column
var w = [];
// loop b columns
for (var jb = 0; jb < bcolumns; jb++) {
// update ptr
cptr[jb] = cindex.length;
// mark in workspace for current column
var mark = jb + 1;
// rows in jb
for (var ib = 0; ib < brows; ib++) {
// b[ib, jb]
var vbij = bdata[ib][jb];
// check b[ib, jb] != 0, avoid loops
if (!eq(vbij, zero)) {
// A values & index in ib column
for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
// a row
var ia = aindex[ka];
// check value exists in current j
if (w[ia] !== mark) {
// ia is new entry in j
w[ia] = mark;
// add i to pattern of C
cindex.push(ia);
// x(ia) = A
x[ia] = mf(vbij, avalues[ka]);
} else {
// i exists in C already
x[ia] = af(x[ia], mf(vbij, avalues[ka]));
}
}
}
}
// copy values from x to column jb of c
for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
// row
var ic = cindex[p];
// copy value
cvalues[p] = x[ic];
}
}
// update ptr
cptr[bcolumns] = cindex.length;
// return sparse matrix
return c;
}
/**
* C = A * B
*
* @param {Matrix} a SparseMatrix (MxN)
* @param {Matrix} b SparseMatrix (NxC)
*
* @return {Matrix} SparseMatrix (MxC)
*/
function _multiplySparseMatrixSparseMatrix(a, b) {
// a sparse
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
// b sparse
var bvalues = b._values;
var bindex = b._index;
var bptr = b._ptr;
var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();
// rows & columns
var arows = a._size[0];
var bcolumns = b._size[1];
// flag indicating both matrices (a & b) contain data
var values = avalues && bvalues;
// datatype
var dt;
// addScalar signature to use
var af = addScalar;
// multiplyScalar signature to use
var mf = multiplyScalar;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
}
// result
var cvalues = values ? [] : undefined;
var cindex = [];
var cptr = [];
// c matrix
var c = a.createSparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [arows, bcolumns],
datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
});
// workspace
var x = values ? [] : undefined;
// vector with marks indicating a value x[i] exists in a given column
var w = [];
// variables
var ka, ka0, ka1, kb, kb0, kb1, ia, ib;
// loop b columns
for (var jb = 0; jb < bcolumns; jb++) {
// update ptr
cptr[jb] = cindex.length;
// mark in workspace for current column
var mark = jb + 1;
// B values & index in j
for (kb0 = bptr[jb], kb1 = bptr[jb + 1], kb = kb0; kb < kb1; kb++) {
// b row
ib = bindex[kb];
// check we need to process values
if (values) {
// loop values in a[:,ib]
for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
// row
ia = aindex[ka];
// check value exists in current j
if (w[ia] !== mark) {
// ia is new entry in j
w[ia] = mark;
// add i to pattern of C
cindex.push(ia);
// x(ia) = A
x[ia] = mf(bvalues[kb], avalues[ka]);
} else {
// i exists in C already
x[ia] = af(x[ia], mf(bvalues[kb], avalues[ka]));
}
}
} else {
// loop values in a[:,ib]
for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
// row
ia = aindex[ka];
// check value exists in current j
if (w[ia] !== mark) {
// ia is new entry in j
w[ia] = mark;
// add i to pattern of C
cindex.push(ia);
}
}
}
}
// check we need to process matrix values (pattern matrix)
if (values) {
// copy values from x to column jb of c
for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
// row
var ic = cindex[p];
// copy value
cvalues[p] = x[ic];
}
}
}
// update ptr
cptr[bcolumns] = cindex.length;
// return sparse matrix
return c;
}
/**
* Multiply two or more values, `x * y`.
* For matrices, the matrix product is calculated.
*
* Syntax:
*
* math.multiply(x, y)
* math.multiply(x, y, z, ...)
*
* Examples:
*
* math.multiply(4, 5.2) // returns number 20.8
* math.multiply(2, 3, 4) // returns number 24
*
* const a = math.complex(2, 3)
* const b = math.complex(4, 1)
* math.multiply(a, b) // returns Complex 5 + 14i
*
* const c = [[1, 2], [4, 3]]
* const d = [[1, 2, 3], [3, -4, 7]]
* math.multiply(c, d) // returns Array [[7, -6, 17], [13, -4, 33]]
*
* const e = math.unit('2.1 km')
* math.multiply(3, e) // returns Unit 6.3 km
*
* See also:
*
* divide, prod, cross, dot
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x First value to multiply
* @param {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} y Second value to multiply
* @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
*/
return typed(name, multiplyScalar, {
// we extend the signatures of multiplyScalar with signatures dealing with matrices
'Array, Array': typed.referTo('Matrix, Matrix', selfMM => (x, y) => {
// check dimensions
_validateMatrixDimensions(arraySize(x), arraySize(y));
// use dense matrix implementation
var m = selfMM(matrix(x), matrix(y));
// return array or scalar
return isMatrix(m) ? m.valueOf() : m;
}),
'Matrix, Matrix': function Matrix_Matrix(x, y) {
// dimensions
var xsize = x.size();
var ysize = y.size();
// check dimensions
_validateMatrixDimensions(xsize, ysize);
// process dimensions
if (xsize.length === 1) {
// process y dimensions
if (ysize.length === 1) {
// Vector * Vector
return _multiplyVectorVector(x, y, xsize[0]);
}
// Vector * Matrix
return _multiplyVectorMatrix(x, y);
}
// process y dimensions
if (ysize.length === 1) {
// Matrix * Vector
return _multiplyMatrixVector(x, y);
}
// Matrix * Matrix
return _multiplyMatrixMatrix(x, y);
},
'Matrix, Array': typed.referTo('Matrix,Matrix', selfMM => (x, y) => selfMM(x, matrix(y))),
'Array, Matrix': typed.referToSelf(self => (x, y) => {
// use Matrix * Matrix implementation
return self(matrix(x, y.storage()), y);
}),
'SparseMatrix, any': function SparseMatrix_any(x, y) {
return matAlgo11xS0s(x, y, multiplyScalar, false);
},
'DenseMatrix, any': function DenseMatrix_any(x, y) {
return matAlgo14xDs(x, y, multiplyScalar, false);
},
'any, SparseMatrix': function any_SparseMatrix(x, y) {
return matAlgo11xS0s(y, x, multiplyScalar, true);
},
'any, DenseMatrix': function any_DenseMatrix(x, y) {
return matAlgo14xDs(y, x, multiplyScalar, true);
},
'Array, any': function Array_any(x, y) {
// use matrix implementation
return matAlgo14xDs(matrix(x), y, multiplyScalar, false).valueOf();
},
'any, Array': function any_Array(x, y) {
// use matrix implementation
return matAlgo14xDs(matrix(y), x, multiplyScalar, true).valueOf();
},
'any, any': multiplyScalar,
'any, any, ...any': typed.referToSelf(self => (x, y, rest) => {
var result = self(x, y);
for (var i = 0; i < rest.length; i++) {
result = self(result, rest[i]);
}
return result;
})
});
});

View File

@@ -0,0 +1,38 @@
import { factory } from '../../utils/factory.js';
import { multiplyNumber } from '../../plain/number/index.js';
var name = 'multiplyScalar';
var dependencies = ['typed'];
export var createMultiplyScalar = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Multiply two scalar values, `x * y`.
* This function is meant for internal use: it is used by the public function
* `multiply`
*
* This function does not support collections (Array or Matrix).
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit} x First value to multiply
* @param {number | BigNumber | bigint | Fraction | Complex} y Second value to multiply
* @return {number | BigNumber | bigint | Fraction | Complex | Unit} Multiplication of `x` and `y`
* @private
*/
return typed('multiplyScalar', {
'number, number': multiplyNumber,
'Complex, Complex': function Complex_Complex(x, y) {
return x.mul(y);
},
'BigNumber, BigNumber': function BigNumber_BigNumber(x, y) {
return x.times(y);
},
'bigint, bigint': function bigint_bigint(x, y) {
return x * y;
},
'Fraction, Fraction': function Fraction_Fraction(x, y) {
return x.mul(y);
},
'number | Fraction | BigNumber | Complex, Unit': (x, y) => y.multiply(x),
'Unit, number | Fraction | BigNumber | Complex | Unit': (x, y) => x.multiply(y)
});
});

287
node_modules/mathjs/lib/esm/function/arithmetic/norm.js generated vendored Normal file
View File

@@ -0,0 +1,287 @@
import { factory } from '../../utils/factory.js';
var name = 'norm';
var dependencies = ['typed', 'abs', 'add', 'pow', 'conj', 'sqrt', 'multiply', 'equalScalar', 'larger', 'smaller', 'matrix', 'ctranspose', 'eigs'];
export var createNorm = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
abs,
add,
pow,
conj,
sqrt,
multiply,
equalScalar,
larger,
smaller,
matrix,
ctranspose,
eigs
} = _ref;
/**
* Calculate the norm of a number, vector or matrix.
*
* The second parameter p is optional. If not provided, it defaults to 2.
*
* Syntax:
*
* math.norm(x)
* math.norm(x, p)
*
* Examples:
*
* math.abs(-3.5) // returns 3.5
* math.norm(-3.5) // returns 3.5
*
* math.norm(math.complex(3, -4)) // returns 5
*
* math.norm([1, 2, -3], Infinity) // returns 3
* math.norm([1, 2, -3], -Infinity) // returns 1
*
* math.norm([3, 4], 2) // returns 5
*
* math.norm([[1, 2], [3, 4]], 1) // returns 6
* math.norm([[1, 2], [3, 4]], 'inf') // returns 7
* math.norm([[1, 2], [3, 4]], 'fro') // returns 5.477225575051661
*
* See also:
*
* abs, hypot
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* Value for which to calculate the norm
* @param {number | BigNumber | string} [p=2]
* Vector space.
* Supported numbers include Infinity and -Infinity.
* Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm)
* @return {number | BigNumber} the p-norm
*/
return typed(name, {
number: Math.abs,
Complex: function Complex(x) {
return x.abs();
},
BigNumber: function BigNumber(x) {
// norm(x) = abs(x)
return x.abs();
},
boolean: function boolean(x) {
// norm(x) = abs(x)
return Math.abs(x);
},
Array: function Array(x) {
return _norm(matrix(x), 2);
},
Matrix: function Matrix(x) {
return _norm(x, 2);
},
'Array, number | BigNumber | string': function Array_number__BigNumber__string(x, p) {
return _norm(matrix(x), p);
},
'Matrix, number | BigNumber | string': function Matrix_number__BigNumber__string(x, p) {
return _norm(x, p);
}
});
/**
* Calculate the plus infinity norm for a vector
* @param {Matrix} x
* @returns {number} Returns the norm
* @private
*/
function _vectorNormPlusInfinity(x) {
// norm(x, Infinity) = max(abs(x))
var pinf = 0;
// skip zeros since abs(0) === 0
x.forEach(function (value) {
var v = abs(value);
if (larger(v, pinf)) {
pinf = v;
}
}, true);
return pinf;
}
/**
* Calculate the minus infinity norm for a vector
* @param {Matrix} x
* @returns {number} Returns the norm
* @private
*/
function _vectorNormMinusInfinity(x) {
// norm(x, -Infinity) = min(abs(x))
var ninf;
// skip zeros since abs(0) === 0
x.forEach(function (value) {
var v = abs(value);
if (!ninf || smaller(v, ninf)) {
ninf = v;
}
}, true);
return ninf || 0;
}
/**
* Calculate the norm for a vector
* @param {Matrix} x
* @param {number | string} p
* @returns {number} Returns the norm
* @private
*/
function _vectorNorm(x, p) {
// check p
if (p === Number.POSITIVE_INFINITY || p === 'inf') {
return _vectorNormPlusInfinity(x);
}
if (p === Number.NEGATIVE_INFINITY || p === '-inf') {
return _vectorNormMinusInfinity(x);
}
if (p === 'fro') {
return _norm(x, 2);
}
if (typeof p === 'number' && !isNaN(p)) {
// check p != 0
if (!equalScalar(p, 0)) {
// norm(x, p) = sum(abs(xi) ^ p) ^ 1/p
var n = 0;
// skip zeros since abs(0) === 0
x.forEach(function (value) {
n = add(pow(abs(value), p), n);
}, true);
return pow(n, 1 / p);
}
return Number.POSITIVE_INFINITY;
}
// invalid parameter value
throw new Error('Unsupported parameter value');
}
/**
* Calculate the Frobenius norm for a matrix
* @param {Matrix} x
* @returns {number} Returns the norm
* @private
*/
function _matrixNormFrobenius(x) {
// norm(x) = sqrt(sum(diag(x'x)))
var fro = 0;
x.forEach(function (value, index) {
fro = add(fro, multiply(value, conj(value)));
});
return abs(sqrt(fro));
}
/**
* Calculate the norm L1 for a matrix
* @param {Matrix} x
* @returns {number} Returns the norm
* @private
*/
function _matrixNormOne(x) {
// norm(x) = the largest column sum
var c = [];
// result
var maxc = 0;
// skip zeros since abs(0) == 0
x.forEach(function (value, index) {
var j = index[1];
var cj = add(c[j] || 0, abs(value));
if (larger(cj, maxc)) {
maxc = cj;
}
c[j] = cj;
}, true);
return maxc;
}
/**
* Calculate the norm L2 for a matrix
* @param {Matrix} x
* @returns {number} Returns the norm
* @private
*/
function _matrixNormTwo(x) {
// norm(x) = sqrt( max eigenvalue of A*.A)
var sizeX = x.size();
if (sizeX[0] !== sizeX[1]) {
throw new RangeError('Invalid matrix dimensions');
}
var tx = ctranspose(x);
var squaredX = multiply(tx, x);
var eigenVals = eigs(squaredX).values.toArray();
var rho = eigenVals[eigenVals.length - 1];
return abs(sqrt(rho));
}
/**
* Calculate the infinity norm for a matrix
* @param {Matrix} x
* @returns {number} Returns the norm
* @private
*/
function _matrixNormInfinity(x) {
// norm(x) = the largest row sum
var r = [];
// result
var maxr = 0;
// skip zeros since abs(0) == 0
x.forEach(function (value, index) {
var i = index[0];
var ri = add(r[i] || 0, abs(value));
if (larger(ri, maxr)) {
maxr = ri;
}
r[i] = ri;
}, true);
return maxr;
}
/**
* Calculate the norm for a 2D Matrix (M*N)
* @param {Matrix} x
* @param {number | string} p
* @returns {number} Returns the norm
* @private
*/
function _matrixNorm(x, p) {
// check p
if (p === 1) {
return _matrixNormOne(x);
}
if (p === Number.POSITIVE_INFINITY || p === 'inf') {
return _matrixNormInfinity(x);
}
if (p === 'fro') {
return _matrixNormFrobenius(x);
}
if (p === 2) {
return _matrixNormTwo(x);
} // invalid parameter value
throw new Error('Unsupported parameter value ' + p);
}
/**
* Calculate the norm for an array
* @param {Matrix} x
* @param {number | string} p
* @returns {number} Returns the norm
* @private
*/
function _norm(x, p) {
// size
var sizeX = x.size();
// check if it is a vector
if (sizeX.length === 1) {
return _vectorNorm(x, p);
}
// MxN matrix
if (sizeX.length === 2) {
if (sizeX[0] && sizeX[1]) {
return _matrixNorm(x, p);
} else {
throw new RangeError('Invalid matrix dimensions');
}
}
}
});

View File

@@ -0,0 +1,166 @@
import { factory } from '../../utils/factory.js';
import { createMatAlgo01xDSid } from '../../type/matrix/utils/matAlgo01xDSid.js';
import { createMatAlgo02xDS0 } from '../../type/matrix/utils/matAlgo02xDS0.js';
import { createMatAlgo06xS0S0 } from '../../type/matrix/utils/matAlgo06xS0S0.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
import { nthRootNumber } from '../../plain/number/index.js';
var name = 'nthRoot';
var dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber', 'concat'];
export var createNthRoot = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
BigNumber: _BigNumber,
concat
} = _ref;
var matAlgo01xDSid = createMatAlgo01xDSid({
typed
});
var matAlgo02xDS0 = createMatAlgo02xDS0({
typed,
equalScalar
});
var matAlgo06xS0S0 = createMatAlgo06xS0S0({
typed,
equalScalar
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Calculate the nth root of a value.
* The principal nth root of a positive real number A, is the positive real
* solution of the equation
*
* x^root = A
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.nthRoot(a)
* math.nthRoot(a, root)
*
* Examples:
*
* math.nthRoot(9, 2) // returns 3 (since 3^2 == 9)
* math.sqrt(9) // returns 3 (since 3^2 == 9)
* math.nthRoot(64, 3) // returns 4 (since 4^3 == 64)
*
* See also:
*
* sqrt, pow
*
* @param {number | BigNumber | Array | Matrix | Complex} a
* Value for which to calculate the nth root
* @param {number | BigNumber} [root=2] The root.
* @return {number | Complex | Array | Matrix} Returns the nth root of `a`
*/
function complexErr() {
throw new Error('Complex number not supported in function nthRoot. Use nthRoots instead.');
}
return typed(name, {
number: nthRootNumber,
'number, number': nthRootNumber,
BigNumber: x => _bigNthRoot(x, new _BigNumber(2)),
'BigNumber, BigNumber': _bigNthRoot,
Complex: complexErr,
'Complex, number': complexErr,
Array: typed.referTo('DenseMatrix,number', selfDn => x => selfDn(matrix(x), 2).valueOf()),
DenseMatrix: typed.referTo('DenseMatrix,number', selfDn => x => selfDn(x, 2)),
SparseMatrix: typed.referTo('SparseMatrix,number', selfSn => x => selfSn(x, 2)),
'SparseMatrix, SparseMatrix': typed.referToSelf(self => (x, y) => {
// density must be one (no zeros in matrix)
if (y.density() === 1) {
// sparse + sparse
return matAlgo06xS0S0(x, y, self);
} else {
// throw exception
throw new Error('Root must be non-zero');
}
}),
'DenseMatrix, SparseMatrix': typed.referToSelf(self => (x, y) => {
// density must be one (no zeros in matrix)
if (y.density() === 1) {
// dense + sparse
return matAlgo01xDSid(x, y, self, false);
} else {
// throw exception
throw new Error('Root must be non-zero');
}
}),
'Array, SparseMatrix': typed.referTo('DenseMatrix,SparseMatrix', selfDS => (x, y) => selfDS(matrix(x), y)),
'number | BigNumber, SparseMatrix': typed.referToSelf(self => (x, y) => {
// density must be one (no zeros in matrix)
if (y.density() === 1) {
// sparse - scalar
return matAlgo11xS0s(y, x, self, true);
} else {
// throw exception
throw new Error('Root must be non-zero');
}
})
}, matrixAlgorithmSuite({
scalar: 'number | BigNumber',
SD: matAlgo02xDS0,
Ss: matAlgo11xS0s,
sS: false
}));
/**
* Calculate the nth root of a for BigNumbers, solve x^root == a
* https://rosettacode.org/wiki/Nth_root#JavaScript
* @param {BigNumber} a
* @param {BigNumber} root
* @private
*/
function _bigNthRoot(a, root) {
var precision = _BigNumber.precision;
var Big = _BigNumber.clone({
precision: precision + 2
});
var zero = new _BigNumber(0);
var one = new Big(1);
var inv = root.isNegative();
if (inv) {
root = root.neg();
}
if (root.isZero()) {
throw new Error('Root must be non-zero');
}
if (a.isNegative() && !root.abs().mod(2).equals(1)) {
throw new Error('Root must be odd when a is negative.');
}
// edge cases zero and infinity
if (a.isZero()) {
return inv ? new Big(Infinity) : 0;
}
if (!a.isFinite()) {
return inv ? zero : a;
}
var x = a.abs().pow(one.div(root));
// If a < 0, we require that root is an odd integer,
// so (-1) ^ (1/root) = -1
x = a.isNeg() ? x.neg() : x;
return new _BigNumber((inv ? one.div(x) : x).toPrecision(precision));
}
});
export var createNthRootNumber = /* #__PURE__ */factory(name, ['typed'], _ref2 => {
var {
typed
} = _ref2;
return typed(name, {
number: nthRootNumber,
'number, number': nthRootNumber
});
});

View File

@@ -0,0 +1,111 @@
import { factory } from '../../utils/factory.js';
var name = 'nthRoots';
var dependencies = ['config', 'typed', 'divideScalar', 'Complex'];
export var createNthRoots = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
divideScalar,
Complex
} = _ref;
/**
* Each function here returns a real multiple of i as a Complex value.
* @param {number} val
* @return {Complex} val, i*val, -val or -i*val for index 0, 1, 2, 3
*/
// This is used to fix float artifacts for zero-valued components.
var _calculateExactResult = [function realPos(val) {
return new Complex(val, 0);
}, function imagPos(val) {
return new Complex(0, val);
}, function realNeg(val) {
return new Complex(-val, 0);
}, function imagNeg(val) {
return new Complex(0, -val);
}];
/**
* Calculate the nth root of a Complex Number a using De Movire's Theorem.
* @param {Complex} a
* @param {number} root
* @return {Array} array of n Complex Roots
*/
function _nthComplexRoots(a, root) {
if (root < 0) throw new Error('Root must be greater than zero');
if (root === 0) throw new Error('Root must be non-zero');
if (root % 1 !== 0) throw new Error('Root must be an integer');
if (a === 0 || a.abs() === 0) return [new Complex(0, 0)];
var aIsNumeric = typeof a === 'number';
var offset;
// determine the offset (argument of a)/(pi/2)
if (aIsNumeric || a.re === 0 || a.im === 0) {
if (aIsNumeric) {
offset = 2 * +(a < 0); // numeric value on the real axis
} else if (a.im === 0) {
offset = 2 * +(a.re < 0); // complex value on the real axis
} else {
offset = 2 * +(a.im < 0) + 1; // complex value on the imaginary axis
}
}
var arg = a.arg();
var abs = a.abs();
var roots = [];
var r = Math.pow(abs, 1 / root);
for (var k = 0; k < root; k++) {
var halfPiFactor = (offset + 4 * k) / root;
/**
* If (offset + 4*k)/root is an integral multiple of pi/2
* then we can produce a more exact result.
*/
if (halfPiFactor === Math.round(halfPiFactor)) {
roots.push(_calculateExactResult[halfPiFactor % 4](r));
continue;
}
roots.push(new Complex({
r,
phi: (arg + 2 * Math.PI * k) / root
}));
}
return roots;
}
/**
* Calculate the nth roots of a value.
* An nth root of a positive real number A,
* is a positive real solution of the equation "x^root = A".
* This function returns an array of complex values.
*
* Syntax:
*
* math.nthRoots(x)
* math.nthRoots(x, root)
*
* Examples:
*
* math.nthRoots(1)
* // returns [
* // {re: 1, im: 0},
* // {re: -1, im: 0}
* // ]
* math.nthRoots(1, 3)
* // returns [
* // { re: 1, im: 0 },
* // { re: -0.4999999999999998, im: 0.8660254037844387 },
* // { re: -0.5000000000000004, im: -0.8660254037844385 }
* // ]
*
* See also:
*
* nthRoot, pow, sqrt
*
* @param {number | BigNumber | Fraction | Complex} x Number to be rounded
* @param {number} [root=2] Optional root, default value is 2
* @return {number | BigNumber | Fraction | Complex} Returns the nth roots
*/
return typed(name, {
Complex: function Complex(x) {
return _nthComplexRoots(x, 2);
},
'Complex, number': _nthComplexRoots
});
});

192
node_modules/mathjs/lib/esm/function/arithmetic/pow.js generated vendored Normal file
View File

@@ -0,0 +1,192 @@
import { factory } from '../../utils/factory.js';
import { isInteger } from '../../utils/number.js';
import { arraySize as size } from '../../utils/array.js';
import { powNumber } from '../../plain/number/index.js';
var name = 'pow';
var dependencies = ['typed', 'config', 'identity', 'multiply', 'matrix', 'inv', 'fraction', 'number', 'Complex'];
export var createPow = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
identity,
multiply,
matrix,
inv,
number,
fraction,
Complex
} = _ref;
/**
* Calculates the power of x to y, `x ^ y`.
*
* Matrix exponentiation is supported for square matrices `x` and integers `y`:
* when `y` is nonnegative, `x` may be any square matrix; and when `y` is
* negative, `x` must be invertible, and then this function returns
* inv(x)^(-y).
*
* For cubic roots of negative numbers, the function returns the principal
* root by default. In order to let the function return the real root,
* math.js can be configured with `math.config({predictable: true})`.
* To retrieve all cubic roots of a value, use `math.cbrt(x, true)`.
*
* Syntax:
*
* math.pow(x, y)
*
* Examples:
*
* math.pow(2, 3) // returns number 8
*
* const a = math.complex(2, 3)
* math.pow(a, 2) // returns Complex -5 + 12i
*
* const b = [[1, 2], [4, 3]]
* math.pow(b, 2) // returns Array [[9, 8], [16, 17]]
*
* const c = [[1, 2], [4, 3]]
* math.pow(c, -1) // returns Array [[-0.6, 0.4], [0.8, -0.2]]
*
* See also:
*
* multiply, sqrt, cbrt, nthRoot
*
* @param {number | BigNumber | bigint | Complex | Unit | Array | Matrix} x The base
* @param {number | BigNumber | bigint | Complex} y The exponent
* @return {number | BigNumber | bigint | Complex | Array | Matrix} The value of `x` to the power `y`
*/
return typed(name, {
'number, number': _pow,
'Complex, Complex': function Complex_Complex(x, y) {
return x.pow(y);
},
'BigNumber, BigNumber': function BigNumber_BigNumber(x, y) {
if (y.isInteger() || x >= 0 || config.predictable) {
return x.pow(y);
} else {
return new Complex(x.toNumber(), 0).pow(y.toNumber(), 0);
}
},
'bigint, bigint': (x, y) => x ** y,
'Fraction, Fraction': function Fraction_Fraction(x, y) {
var result = x.pow(y);
if (result != null) {
return result;
}
if (config.predictable) {
throw new Error('Result of pow is non-rational and cannot be expressed as a fraction');
} else {
return _pow(x.valueOf(), y.valueOf());
}
},
'Array, number': _powArray,
'Array, BigNumber': function Array_BigNumber(x, y) {
return _powArray(x, y.toNumber());
},
'Matrix, number': _powMatrix,
'Matrix, BigNumber': function Matrix_BigNumber(x, y) {
return _powMatrix(x, y.toNumber());
},
'Unit, number | BigNumber': function Unit_number__BigNumber(x, y) {
return x.pow(y);
}
});
/**
* Calculates the power of x to y, x^y, for two numbers.
* @param {number} x
* @param {number} y
* @return {number | Complex} res
* @private
*/
function _pow(x, y) {
// Alternatively could define a 'realmode' config option or something, but
// 'predictable' will work for now
if (config.predictable && !isInteger(y) && x < 0) {
// Check to see if y can be represented as a fraction
try {
var yFrac = fraction(y);
var yNum = number(yFrac);
if (y === yNum || Math.abs((y - yNum) / y) < 1e-14) {
if (yFrac.d % 2 === 1) {
return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y);
}
}
} catch (ex) {
// fraction() throws an error if y is Infinity, etc.
}
// Unable to express y as a fraction, so continue on
}
// **for predictable mode** x^Infinity === NaN if x < -1
// N.B. this behavour is different from `Math.pow` which gives
// (-2)^Infinity === Infinity
if (config.predictable && (x < -1 && y === Infinity || x > -1 && x < 0 && y === -Infinity)) {
return NaN;
}
if (isInteger(y) || x >= 0 || config.predictable) {
return powNumber(x, y);
} else {
// TODO: the following infinity checks are duplicated from powNumber. Deduplicate this somehow
// x^Infinity === 0 if -1 < x < 1
// A real number 0 is returned instead of complex(0)
if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) {
return 0;
}
return new Complex(x, 0).pow(y, 0);
}
}
/**
* Calculate the power of a 2d array
* @param {Array} x must be a 2 dimensional, square matrix
* @param {number} y a integer value (positive if `x` is not invertible)
* @returns {Array}
* @private
*/
function _powArray(x, y) {
if (!isInteger(y)) {
throw new TypeError('For A^b, b must be an integer (value is ' + y + ')');
}
// verify that A is a 2 dimensional square matrix
var s = size(x);
if (s.length !== 2) {
throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimensions)');
}
if (s[0] !== s[1]) {
throw new Error('For A^b, A must be square (size is ' + s[0] + 'x' + s[1] + ')');
}
if (y < 0) {
try {
return _powArray(inv(x), -y);
} catch (error) {
if (error.message === 'Cannot calculate inverse, determinant is zero') {
throw new TypeError('For A^b, when A is not invertible, b must be a positive integer (value is ' + y + ')');
}
throw error;
}
}
var res = identity(s[0]).valueOf();
var px = x;
while (y >= 1) {
if ((y & 1) === 1) {
res = multiply(px, res);
}
y >>= 1;
px = multiply(px, px);
}
return res;
}
/**
* Calculate the power of a 2d matrix
* @param {Matrix} x must be a 2 dimensional, square matrix
* @param {number} y a positive, integer value
* @returns {Matrix}
* @private
*/
function _powMatrix(x, y) {
return matrix(_powArray(x.valueOf(), y));
}
});

View File

@@ -0,0 +1,202 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { nearlyEqual, splitNumber } from '../../utils/number.js';
import { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo12xSfs } from '../../type/matrix/utils/matAlgo12xSfs.js';
import { createMatAlgo14xDs } from '../../type/matrix/utils/matAlgo14xDs.js';
import { roundNumber } from '../../plain/number/index.js';
var NO_INT = 'Number of decimals in function round must be an integer';
var name = 'round';
var dependencies = ['typed', 'config', 'matrix', 'equalScalar', 'zeros', 'BigNumber', 'DenseMatrix'];
export var createRound = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
matrix,
equalScalar,
zeros,
BigNumber: _BigNumber,
DenseMatrix
} = _ref;
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo12xSfs = createMatAlgo12xSfs({
typed,
DenseMatrix
});
var matAlgo14xDs = createMatAlgo14xDs({
typed
});
function toExponent(epsilon) {
return Math.abs(splitNumber(epsilon).exponent);
}
/**
* Round a value towards the nearest rounded value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.round(x)
* math.round(x, n)
* math.round(unit, valuelessUnit)
* math.round(unit, n, valuelessUnit)
*
* Examples:
*
* math.round(3.22) // returns number 3
* math.round(3.82) // returns number 4
* math.round(-4.2) // returns number -4
* math.round(-4.7) // returns number -5
* math.round(3.22, 1) // returns number 3.2
* math.round(3.88, 1) // returns number 3.9
* math.round(-4.21, 1) // returns number -4.2
* math.round(-4.71, 1) // returns number -4.7
* math.round(math.pi, 3) // returns number 3.142
* math.round(123.45678, 2) // returns number 123.46
*
* const c = math.complex(3.2, -2.7)
* math.round(c) // returns Complex 3 - 3i
*
* const unit = math.unit('3.241 cm')
* const cm = math.unit('cm')
* const mm = math.unit('mm')
* math.round(unit, 1, cm) // returns Unit 3.2 cm
* math.round(unit, 1, mm) // returns Unit 32.4 mm
*
* math.round([3.2, 3.8, -4.7]) // returns Array [3, 4, -5]
*
* See also:
*
* ceil, fix, floor
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Value to be rounded
* @param {number | BigNumber | Array} [n=0] Number of decimals
* @param {Unit} [valuelessUnit] A valueless unit
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
return typed(name, {
number: function number(x) {
// Handle round off errors by first rounding to relTol precision
var xEpsilon = roundNumber(x, toExponent(config.relTol));
var xSelected = nearlyEqual(x, xEpsilon, config.relTol, config.absTol) ? xEpsilon : x;
return roundNumber(xSelected);
},
'number, number': function number_number(x, n) {
// Same as number: unless user specifies more decimals than relTol
var epsilonExponent = toExponent(config.relTol);
if (n >= epsilonExponent) {
return roundNumber(x, n);
}
var xEpsilon = roundNumber(x, epsilonExponent);
var xSelected = nearlyEqual(x, xEpsilon, config.relTol, config.absTol) ? xEpsilon : x;
return roundNumber(xSelected, n);
},
'number, BigNumber': function number_BigNumber(x, n) {
if (!n.isInteger()) {
throw new TypeError(NO_INT);
}
return new _BigNumber(x).toDecimalPlaces(n.toNumber());
},
Complex: function Complex(x) {
return x.round();
},
'Complex, number': function Complex_number(x, n) {
if (n % 1) {
throw new TypeError(NO_INT);
}
return x.round(n);
},
'Complex, BigNumber': function Complex_BigNumber(x, n) {
if (!n.isInteger()) {
throw new TypeError(NO_INT);
}
var _n = n.toNumber();
return x.round(_n);
},
BigNumber: function BigNumber(x) {
// Handle round off errors by first rounding to relTol precision
var xEpsilon = new _BigNumber(x).toDecimalPlaces(toExponent(config.relTol));
var xSelected = bigNearlyEqual(x, xEpsilon, config.relTol, config.absTol) ? xEpsilon : x;
return xSelected.toDecimalPlaces(0);
},
'BigNumber, BigNumber': function BigNumber_BigNumber(x, n) {
if (!n.isInteger()) {
throw new TypeError(NO_INT);
}
// Same as BigNumber: unless user specifies more decimals than relTol
var epsilonExponent = toExponent(config.relTol);
if (n >= epsilonExponent) {
return x.toDecimalPlaces(n.toNumber());
}
var xEpsilon = x.toDecimalPlaces(epsilonExponent);
var xSelected = bigNearlyEqual(x, xEpsilon, config.relTol, config.absTol) ? xEpsilon : x;
return xSelected.toDecimalPlaces(n.toNumber());
},
Fraction: function Fraction(x) {
return x.round();
},
'Fraction, number': function Fraction_number(x, n) {
if (n % 1) {
throw new TypeError(NO_INT);
}
return x.round(n);
},
'Fraction, BigNumber': function Fraction_BigNumber(x, n) {
if (!n.isInteger()) {
throw new TypeError(NO_INT);
}
return x.round(n.toNumber());
},
'Unit, number, Unit': typed.referToSelf(self => function (x, n, unit) {
var valueless = x.toNumeric(unit);
return unit.multiply(self(valueless, n));
}),
'Unit, BigNumber, Unit': typed.referToSelf(self => (x, n, unit) => self(x, n.toNumber(), unit)),
'Unit, Unit': typed.referToSelf(self => (x, unit) => self(x, 0, unit)),
'Array | Matrix, number, Unit': typed.referToSelf(self => (x, n, unit) => {
// deep map collection, skip zeros since round(0) = 0
return deepMap(x, value => self(value, n, unit), true);
}),
'Array | Matrix, BigNumber, Unit': typed.referToSelf(self => (x, n, unit) => self(x, n.toNumber(), unit)),
'Array | Matrix, Unit': typed.referToSelf(self => (x, unit) => self(x, 0, unit)),
'Array | Matrix': typed.referToSelf(self => x => {
// deep map collection, skip zeros since round(0) = 0
return deepMap(x, self, true);
}),
'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, n) => {
return matAlgo11xS0s(x, n, self, false);
}),
'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, n) => {
return matAlgo14xDs(x, n, self, false);
}),
'Array, number | BigNumber': typed.referToSelf(self => (x, n) => {
// use matrix implementation
return matAlgo14xDs(matrix(x), n, self, false).valueOf();
}),
'number | Complex | BigNumber | Fraction, SparseMatrix': typed.referToSelf(self => (x, n) => {
// check scalar is zero
if (equalScalar(x, 0)) {
// do not execute algorithm, result will be a zero matrix
return zeros(n.size(), n.storage());
}
return matAlgo12xSfs(n, x, self, true);
}),
'number | Complex | BigNumber | Fraction, DenseMatrix': typed.referToSelf(self => (x, n) => {
// check scalar is zero
if (equalScalar(x, 0)) {
// do not execute algorithm, result will be a zero matrix
return zeros(n.size(), n.storage());
}
return matAlgo14xDs(n, x, self, true);
}),
'number | Complex | BigNumber | Fraction, Array': typed.referToSelf(self => (x, n) => {
// use matrix implementation
return matAlgo14xDs(matrix(n), x, self, true).valueOf();
})
});
});

View File

@@ -0,0 +1,66 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { signNumber } from '../../plain/number/index.js';
var name = 'sign';
var dependencies = ['typed', 'BigNumber', 'Fraction', 'complex'];
export var createSign = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
BigNumber: _BigNumber,
complex,
Fraction: _Fraction
} = _ref;
/**
* Compute the sign of a value. The sign of a value x is:
*
* - 1 when x > 0
* - -1 when x < 0
* - 0 when x == 0
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sign(x)
*
* Examples:
*
* math.sign(3.5) // returns 1
* math.sign(-4.2) // returns -1
* math.sign(0) // returns 0
*
* math.sign([3, 5, -2, 0, 2]) // returns [1, 1, -1, 0, 1]
*
* See also:
*
* abs
*
* @param {number | BigNumber | bigint | Fraction | Complex | Array | Matrix | Unit} x
* The number for which to determine the sign
* @return {number | BigNumber | bigint | Fraction | Complex | Array | Matrix | Unit}
* The sign of `x`
*/
return typed(name, {
number: signNumber,
Complex: function Complex(x) {
return x.im === 0 ? complex(signNumber(x.re)) : x.sign();
},
BigNumber: function BigNumber(x) {
return new _BigNumber(x.cmp(0));
},
bigint: function bigint(x) {
return x > 0n ? 1n : x < 0n ? -1n : 0n;
},
Fraction: function Fraction(x) {
return new _Fraction(x.s, 1);
},
// deep map collection, skip zeros since sign(0) = 0
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self, true)),
Unit: typed.referToSelf(self => x => {
if (!x._isDerived() && x.units[0].unit.offset !== 0) {
throw new TypeError('sign is ambiguous for units with offset');
}
return typed.find(self, x.valueType())(x.value);
})
});
});

View File

@@ -0,0 +1,70 @@
import { factory } from '../../utils/factory.js';
var name = 'sqrt';
var dependencies = ['config', 'typed', 'Complex'];
export var createSqrt = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
config,
typed,
Complex
} = _ref;
/**
* Calculate the square root of a value.
*
* For matrices, if you want the matrix square root of a square matrix,
* use the `sqrtm` function. If you wish to apply `sqrt` elementwise to
* a matrix M, use `math.map(M, math.sqrt)`.
*
* Syntax:
*
* math.sqrt(x)
*
* Examples:
*
* math.sqrt(25) // returns 5
* math.square(5) // returns 25
* math.sqrt(-4) // returns Complex 2i
*
* See also:
*
* square, multiply, cube, cbrt, sqrtm
*
* @param {number | BigNumber | Complex | Unit} x
* Value for which to calculate the square root.
* @return {number | BigNumber | Complex | Unit}
* Returns the square root of `x`
*/
return typed('sqrt', {
number: _sqrtNumber,
Complex: function Complex(x) {
return x.sqrt();
},
BigNumber: function BigNumber(x) {
if (!x.isNegative() || config.predictable) {
return x.sqrt();
} else {
// negative value -> downgrade to number to do complex value computation
return _sqrtNumber(x.toNumber());
}
},
Unit: function Unit(x) {
// Someday will work for complex units when they are implemented
return x.pow(0.5);
}
});
/**
* Calculate sqrt for a number
* @param {number} x
* @returns {number | Complex} Returns the square root of x
* @private
*/
function _sqrtNumber(x) {
if (isNaN(x)) {
return NaN;
} else if (x >= 0 || config.predictable) {
return Math.sqrt(x);
} else {
return new Complex(x, 0).sqrt();
}
}
});

View File

@@ -0,0 +1,55 @@
import { factory } from '../../utils/factory.js';
import { squareNumber } from '../../plain/number/index.js';
var name = 'square';
var dependencies = ['typed'];
export var createSquare = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Compute the square of a value, `x * x`.
* To avoid confusion with multiplying a square matrix by itself,
* this function does not apply to matrices. If you wish to square
* every element of a matrix, see the examples.
*
* Syntax:
*
* math.square(x)
*
* Examples:
*
* math.square(2) // returns number 4
* math.square(3) // returns number 9
* math.pow(3, 2) // returns number 9
* math.multiply(3, 3) // returns number 9
*
* math.map([1, 2, 3, 4], math.square) // returns Array [1, 4, 9, 16]
*
* See also:
*
* multiply, cube, sqrt, pow
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit} x
* Number for which to calculate the square
* @return {number | BigNumber | bigint | Fraction | Complex | Unit}
* Squared value
*/
return typed(name, {
number: squareNumber,
Complex: function Complex(x) {
return x.mul(x);
},
BigNumber: function BigNumber(x) {
return x.times(x);
},
bigint: function bigint(x) {
return x * x;
},
Fraction: function Fraction(x) {
return x.mul(x);
},
Unit: function Unit(x) {
return x.pow(2);
}
});
});

View File

@@ -0,0 +1,86 @@
import { factory } from '../../utils/factory.js';
import { createMatAlgo01xDSid } from '../../type/matrix/utils/matAlgo01xDSid.js';
import { createMatAlgo03xDSf } from '../../type/matrix/utils/matAlgo03xDSf.js';
import { createMatAlgo05xSfSf } from '../../type/matrix/utils/matAlgo05xSfSf.js';
import { createMatAlgo10xSids } from '../../type/matrix/utils/matAlgo10xSids.js';
import { createMatAlgo12xSfs } from '../../type/matrix/utils/matAlgo12xSfs.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
var name = 'subtract';
var dependencies = ['typed', 'matrix', 'equalScalar', 'subtractScalar', 'unaryMinus', 'DenseMatrix', 'concat'];
export var createSubtract = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
subtractScalar,
unaryMinus,
DenseMatrix,
concat
} = _ref;
// TODO: split function subtract in two: subtract and subtractScalar
var matAlgo01xDSid = createMatAlgo01xDSid({
typed
});
var matAlgo03xDSf = createMatAlgo03xDSf({
typed
});
var matAlgo05xSfSf = createMatAlgo05xSfSf({
typed,
equalScalar
});
var matAlgo10xSids = createMatAlgo10xSids({
typed,
DenseMatrix
});
var matAlgo12xSfs = createMatAlgo12xSfs({
typed,
DenseMatrix
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Subtract two values, `x - y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.subtract(x, y)
*
* Examples:
*
* math.subtract(5.3, 2) // returns number 3.3
*
* const a = math.complex(2, 3)
* const b = math.complex(4, 1)
* math.subtract(a, b) // returns Complex -2 + 2i
*
* math.subtract([5, 7, 4], 4) // returns Array [1, 3, 0]
*
* const c = math.unit('2.1 km')
* const d = math.unit('500m')
* math.subtract(c, d) // returns Unit 1.6 km
*
* See also:
*
* add
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x Initial value
* @param {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} y Value to subtract from `x`
* @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} Subtraction of `x` and `y`
*/
return typed(name, {
'any, any': subtractScalar
}, matrixAlgorithmSuite({
elop: subtractScalar,
SS: matAlgo05xSfSf,
DS: matAlgo01xDSid,
SD: matAlgo03xDSf,
Ss: matAlgo12xSfs,
sS: matAlgo10xSids
}));
});

View File

@@ -0,0 +1,49 @@
import { factory } from '../../utils/factory.js';
import { subtractNumber } from '../../plain/number/index.js';
var name = 'subtractScalar';
var dependencies = ['typed'];
export var createSubtractScalar = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Subtract two scalar values, `x - y`.
* This function is meant for internal use: it is used by the public function
* `subtract`
*
* This function does not support collections (Array or Matrix).
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit} x First value
* @param {number | BigNumber | bigint | Fraction | Complex} y Second value to be subtracted from `x`
* @return {number | BigNumber | bigint | Fraction | Complex | Unit} Difference of `x` and `y`
* @private
*/
return typed(name, {
'number, number': subtractNumber,
'Complex, Complex': function Complex_Complex(x, y) {
return x.sub(y);
},
'BigNumber, BigNumber': function BigNumber_BigNumber(x, y) {
return x.minus(y);
},
'bigint, bigint': function bigint_bigint(x, y) {
return x - y;
},
'Fraction, Fraction': function Fraction_Fraction(x, y) {
return x.sub(y);
},
'Unit, Unit': typed.referToSelf(self => (x, y) => {
if (x.value === null || x.value === undefined) {
throw new Error('Parameter x contains a unit with undefined value');
}
if (y.value === null || y.value === undefined) {
throw new Error('Parameter y contains a unit with undefined value');
}
if (!x.equalBase(y)) throw new Error('Units do not match');
var res = x.clone();
res.value = typed.find(self, [res.valueType(), y.valueType()])(res.value, y.value);
res.fixPrefix = false;
return res;
})
});
});

View File

@@ -0,0 +1,47 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { unaryMinusNumber } from '../../plain/number/index.js';
var name = 'unaryMinus';
var dependencies = ['typed'];
export var createUnaryMinus = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Inverse the sign of a value, apply a unary minus operation.
*
* For matrices, the function is evaluated element wise. Boolean values and
* strings will be converted to a number. For complex numbers, both real and
* complex value are inverted.
*
* Syntax:
*
* math.unaryMinus(x)
*
* Examples:
*
* math.unaryMinus(3.5) // returns -3.5
* math.unaryMinus(-4.2) // returns 4.2
*
* See also:
*
* add, subtract, unaryPlus
*
* @param {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x Number to be inverted.
* @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} Returns the value with inverted sign.
*/
return typed(name, {
number: unaryMinusNumber,
'Complex | BigNumber | Fraction': x => x.neg(),
bigint: x => -x,
Unit: typed.referToSelf(self => x => {
var res = x.clone();
res.value = typed.find(self, res.valueType())(x.value);
return res;
}),
// deep map collection, skip zeros since unaryMinus(0) = 0
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self, true))
// TODO: add support for string
});
});

View File

@@ -0,0 +1,63 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
import { unaryPlusNumber } from '../../plain/number/index.js';
import { safeNumberType } from '../../utils/number.js';
var name = 'unaryPlus';
var dependencies = ['typed', 'config', 'numeric'];
export var createUnaryPlus = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
numeric
} = _ref;
/**
* Unary plus operation.
* Boolean values and strings will be converted to a number, numeric values will be returned as is.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.unaryPlus(x)
*
* Examples:
*
* math.unaryPlus(3.5) // returns 3.5
* math.unaryPlus(1) // returns 1
*
* See also:
*
* unaryMinus, add, subtract
*
* @param {number | BigNumber | bigint | Fraction | string | Complex | Unit | Array | Matrix} x
* Input value
* @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix}
* Returns the input value when numeric, converts to a number when input is non-numeric.
*/
return typed(name, {
number: unaryPlusNumber,
Complex: function Complex(x) {
return x; // complex numbers are immutable
},
BigNumber: function BigNumber(x) {
return x; // bignumbers are immutable
},
bigint: function bigint(x) {
return x;
},
Fraction: function Fraction(x) {
return x; // fractions are immutable
},
Unit: function Unit(x) {
return x.clone();
},
// deep map collection, skip zeros since unaryPlus(0) = 0
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self, true)),
boolean: function boolean(x) {
return numeric(x ? 1 : 0, config.number);
},
string: function string(x) {
return numeric(x, safeNumberType(x, config));
}
});
});

View File

@@ -0,0 +1,91 @@
import { factory } from '../../utils/factory.js';
import { xgcdNumber } from '../../plain/number/index.js';
var name = 'xgcd';
var dependencies = ['typed', 'config', 'matrix', 'BigNumber'];
export var createXgcd = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
config,
matrix,
BigNumber
} = _ref;
/**
* Calculate the extended greatest common divisor for two values.
* See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
*
* Syntax:
*
* math.xgcd(a, b)
*
* Examples:
*
* math.xgcd(8, 12) // returns [4, -1, 1]
* math.gcd(8, 12) // returns 4
* math.xgcd(36163, 21199) // returns [1247, -7, 12]
*
* See also:
*
* gcd, lcm
*
* @param {number | BigNumber} a An integer number
* @param {number | BigNumber} b An integer number
* @return {Array} Returns an array containing 3 integers `[div, m, n]`
* where `div = gcd(a, b)` and `a*m + b*n = div`
*/
return typed(name, {
'number, number': function number_number(a, b) {
var res = xgcdNumber(a, b);
return config.matrix === 'Array' ? res : matrix(res);
},
'BigNumber, BigNumber': _xgcdBigNumber
// TODO: implement support for Fraction
});
/**
* Calculate xgcd for two BigNumbers
* @param {BigNumber} a
* @param {BigNumber} b
* @return {BigNumber[]} result
* @private
*/
function _xgcdBigNumber(a, b) {
// source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
var
// used to swap two variables
t;
var
// quotient
q;
var
// remainder
r;
var zero = new BigNumber(0);
var one = new BigNumber(1);
var x = zero;
var lastx = one;
var y = one;
var lasty = zero;
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function xgcd must be integer numbers');
}
while (!b.isZero()) {
q = a.div(b).floor();
r = a.mod(b);
t = x;
x = lastx.minus(q.times(x));
lastx = t;
t = y;
y = lasty.minus(q.times(y));
lasty = t;
a = b;
b = r;
}
var res;
if (a.lt(zero)) {
res = [a.neg(), lastx.neg(), lasty.neg()];
} else {
res = [a, !a.isZero() ? lastx : 0, lasty];
}
return config.matrix === 'Array' ? res : matrix(res);
}
});

66
node_modules/mathjs/lib/esm/function/bitwise/bitAnd.js generated vendored Normal file
View File

@@ -0,0 +1,66 @@
import { bitAndBigNumber } from '../../utils/bignumber/bitwise.js';
import { createMatAlgo02xDS0 } from '../../type/matrix/utils/matAlgo02xDS0.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo06xS0S0 } from '../../type/matrix/utils/matAlgo06xS0S0.js';
import { factory } from '../../utils/factory.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
import { bitAndNumber } from '../../plain/number/index.js';
var name = 'bitAnd';
var dependencies = ['typed', 'matrix', 'equalScalar', 'concat'];
export var createBitAnd = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
concat
} = _ref;
var matAlgo02xDS0 = createMatAlgo02xDS0({
typed,
equalScalar
});
var matAlgo06xS0S0 = createMatAlgo06xS0S0({
typed,
equalScalar
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Bitwise AND two values, `x & y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitAnd(x, y)
*
* Examples:
*
* math.bitAnd(53, 131) // returns number 1
*
* math.bitAnd([1, 12, 31], 42) // returns Array [0, 8, 10]
*
* See also:
*
* bitNot, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
*
* @param {number | BigNumber | bigint | Array | Matrix} x First value to and
* @param {number | BigNumber | bigint | Array | Matrix} y Second value to and
* @return {number | BigNumber | bigint | Array | Matrix} AND of `x` and `y`
*/
return typed(name, {
'number, number': bitAndNumber,
'BigNumber, BigNumber': bitAndBigNumber,
'bigint, bigint': (x, y) => x & y
}, matrixAlgorithmSuite({
SS: matAlgo06xS0S0,
DS: matAlgo02xDS0,
Ss: matAlgo11xS0s
}));
});

39
node_modules/mathjs/lib/esm/function/bitwise/bitNot.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
import { bitNotBigNumber } from '../../utils/bignumber/bitwise.js';
import { deepMap } from '../../utils/collection.js';
import { factory } from '../../utils/factory.js';
import { bitNotNumber } from '../../plain/number/index.js';
var name = 'bitNot';
var dependencies = ['typed'];
export var createBitNot = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Bitwise NOT value, `~x`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.bitNot(x)
*
* Examples:
*
* math.bitNot(1) // returns number -2
*
* math.bitNot([2, -3, 4]) // returns Array [-3, 2, -5]
*
* See also:
*
* bitAnd, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
*
* @param {number | BigNumber | bigint | Array | Matrix} x Value to not
* @return {number | BigNumber | bigint | Array | Matrix} NOT of `x`
*/
return typed(name, {
number: bitNotNumber,
BigNumber: bitNotBigNumber,
bigint: x => ~x,
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
});
});

67
node_modules/mathjs/lib/esm/function/bitwise/bitOr.js generated vendored Normal file
View File

@@ -0,0 +1,67 @@
import { bitOrBigNumber } from '../../utils/bignumber/bitwise.js';
import { factory } from '../../utils/factory.js';
import { createMatAlgo10xSids } from '../../type/matrix/utils/matAlgo10xSids.js';
import { createMatAlgo04xSidSid } from '../../type/matrix/utils/matAlgo04xSidSid.js';
import { createMatAlgo01xDSid } from '../../type/matrix/utils/matAlgo01xDSid.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
import { bitOrNumber } from '../../plain/number/index.js';
var name = 'bitOr';
var dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix', 'concat'];
export var createBitOr = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
DenseMatrix,
concat
} = _ref;
var matAlgo01xDSid = createMatAlgo01xDSid({
typed
});
var matAlgo04xSidSid = createMatAlgo04xSidSid({
typed,
equalScalar
});
var matAlgo10xSids = createMatAlgo10xSids({
typed,
DenseMatrix
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Bitwise OR two values, `x | y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the lowest print base.
*
* Syntax:
*
* math.bitOr(x, y)
*
* Examples:
*
* math.bitOr(1, 2) // returns number 3
*
* math.bitOr([1, 2, 3], 4) // returns Array [5, 6, 7]
*
* See also:
*
* bitAnd, bitNot, bitXor, leftShift, rightArithShift, rightLogShift
*
* @param {number | BigNumber | bigint | Array | Matrix} x First value to or
* @param {number | BigNumber | bigint | Array | Matrix} y Second value to or
* @return {number | BigNumber | bigint | Array | Matrix} OR of `x` and `y`
*/
return typed(name, {
'number, number': bitOrNumber,
'BigNumber, BigNumber': bitOrBigNumber,
'bigint, bigint': (x, y) => x | y
}, matrixAlgorithmSuite({
SS: matAlgo04xSidSid,
DS: matAlgo01xDSid,
Ss: matAlgo10xSids
}));
});

65
node_modules/mathjs/lib/esm/function/bitwise/bitXor.js generated vendored Normal file
View File

@@ -0,0 +1,65 @@
import { bitXor as bigBitXor } from '../../utils/bignumber/bitwise.js';
import { createMatAlgo03xDSf } from '../../type/matrix/utils/matAlgo03xDSf.js';
import { createMatAlgo07xSSf } from '../../type/matrix/utils/matAlgo07xSSf.js';
import { createMatAlgo12xSfs } from '../../type/matrix/utils/matAlgo12xSfs.js';
import { factory } from '../../utils/factory.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
import { bitXorNumber } from '../../plain/number/index.js';
var name = 'bitXor';
var dependencies = ['typed', 'matrix', 'DenseMatrix', 'concat'];
export var createBitXor = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
DenseMatrix,
concat
} = _ref;
var matAlgo03xDSf = createMatAlgo03xDSf({
typed
});
var matAlgo07xSSf = createMatAlgo07xSSf({
typed,
DenseMatrix
});
var matAlgo12xSfs = createMatAlgo12xSfs({
typed,
DenseMatrix
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
/**
* Bitwise XOR two values, `x ^ y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitXor(x, y)
*
* Examples:
*
* math.bitXor(1, 2) // returns number 3
*
* math.bitXor([2, 3, 4], 4) // returns Array [6, 7, 0]
*
* See also:
*
* bitAnd, bitNot, bitOr, leftShift, rightArithShift, rightLogShift
*
* @param {number | BigNumber | bigint | Array | Matrix} x First value to xor
* @param {number | BigNumber | bigint | Array | Matrix} y Second value to xor
* @return {number | BigNumber | bigint | Array | Matrix} XOR of `x` and `y`
*/
return typed(name, {
'number, number': bitXorNumber,
'BigNumber, BigNumber': bigBitXor,
'bigint, bigint': (x, y) => x ^ y
}, matrixAlgorithmSuite({
SS: matAlgo07xSSf,
DS: matAlgo03xDSf,
Ss: matAlgo12xSfs
}));
});

View File

@@ -0,0 +1,115 @@
import { createMatAlgo02xDS0 } from '../../type/matrix/utils/matAlgo02xDS0.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo14xDs } from '../../type/matrix/utils/matAlgo14xDs.js';
import { createMatAlgo01xDSid } from '../../type/matrix/utils/matAlgo01xDSid.js';
import { createMatAlgo10xSids } from '../../type/matrix/utils/matAlgo10xSids.js';
import { createMatAlgo08xS0Sid } from '../../type/matrix/utils/matAlgo08xS0Sid.js';
import { factory } from '../../utils/factory.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
import { createUseMatrixForArrayScalar } from './useMatrixForArrayScalar.js';
import { leftShiftNumber } from '../../plain/number/index.js';
import { leftShiftBigNumber } from '../../utils/bignumber/bitwise.js';
var name = 'leftShift';
var dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix', 'concat'];
export var createLeftShift = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
zeros,
DenseMatrix,
concat
} = _ref;
var matAlgo01xDSid = createMatAlgo01xDSid({
typed
});
var matAlgo02xDS0 = createMatAlgo02xDS0({
typed,
equalScalar
});
var matAlgo08xS0Sid = createMatAlgo08xS0Sid({
typed,
equalScalar
});
var matAlgo10xSids = createMatAlgo10xSids({
typed,
DenseMatrix
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo14xDs = createMatAlgo14xDs({
typed
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
var useMatrixForArrayScalar = createUseMatrixForArrayScalar({
typed,
matrix
});
/**
* Bitwise left logical shift of a value x by y number of bits, `x << y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.leftShift(x, y)
*
* Examples:
*
* math.leftShift(1, 2) // returns number 4
*
* math.leftShift([1, 2, 4], 4) // returns Array [16, 32, 64]
*
* See also:
*
* leftShift, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
*
* @param {number | BigNumber | bigint | Array | Matrix} x Value to be shifted
* @param {number | BigNumber | bigint} y Amount of shifts
* @return {number | BigNumber | bigint | Array | Matrix} `x` shifted left `y` times
*/
return typed(name, {
'number, number': leftShiftNumber,
'BigNumber, BigNumber': leftShiftBigNumber,
'bigint, bigint': (x, y) => x << y,
'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(y, 0)) {
return x.clone();
}
return matAlgo11xS0s(x, y, self, false);
}),
'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(y, 0)) {
return x.clone();
}
return matAlgo14xDs(x, y, self, false);
}),
'number | BigNumber, SparseMatrix': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(x, 0)) {
return zeros(y.size(), y.storage());
}
return matAlgo10xSids(y, x, self, true);
}),
'number | BigNumber, DenseMatrix': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(x, 0)) {
return zeros(y.size(), y.storage());
}
return matAlgo14xDs(y, x, self, true);
})
}, useMatrixForArrayScalar, matrixAlgorithmSuite({
SS: matAlgo08xS0Sid,
DS: matAlgo01xDSid,
SD: matAlgo02xDS0
}));
});

View File

@@ -0,0 +1,115 @@
import { rightArithShiftBigNumber } from '../../utils/bignumber/bitwise.js';
import { createMatAlgo02xDS0 } from '../../type/matrix/utils/matAlgo02xDS0.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo14xDs } from '../../type/matrix/utils/matAlgo14xDs.js';
import { createMatAlgo01xDSid } from '../../type/matrix/utils/matAlgo01xDSid.js';
import { createMatAlgo10xSids } from '../../type/matrix/utils/matAlgo10xSids.js';
import { createMatAlgo08xS0Sid } from '../../type/matrix/utils/matAlgo08xS0Sid.js';
import { factory } from '../../utils/factory.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
import { createUseMatrixForArrayScalar } from './useMatrixForArrayScalar.js';
import { rightArithShiftNumber } from '../../plain/number/index.js';
var name = 'rightArithShift';
var dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix', 'concat'];
export var createRightArithShift = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
zeros,
DenseMatrix,
concat
} = _ref;
var matAlgo01xDSid = createMatAlgo01xDSid({
typed
});
var matAlgo02xDS0 = createMatAlgo02xDS0({
typed,
equalScalar
});
var matAlgo08xS0Sid = createMatAlgo08xS0Sid({
typed,
equalScalar
});
var matAlgo10xSids = createMatAlgo10xSids({
typed,
DenseMatrix
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo14xDs = createMatAlgo14xDs({
typed
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
var useMatrixForArrayScalar = createUseMatrixForArrayScalar({
typed,
matrix
});
/**
* Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightArithShift(x, y)
*
* Examples:
*
* math.rightArithShift(4, 2) // returns number 1
*
* math.rightArithShift([16, -32, 64], 4) // returns Array [1, -2, 4]
*
* See also:
*
* bitAnd, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
*
* @param {number | BigNumber | bigint | Array | Matrix} x Value to be shifted
* @param {number | BigNumber | bigint} y Amount of shifts
* @return {number | BigNumber | bigint | Array | Matrix} `x` zero-filled shifted right `y` times
*/
return typed(name, {
'number, number': rightArithShiftNumber,
'BigNumber, BigNumber': rightArithShiftBigNumber,
'bigint, bigint': (x, y) => x >> y,
'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(y, 0)) {
return x.clone();
}
return matAlgo11xS0s(x, y, self, false);
}),
'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(y, 0)) {
return x.clone();
}
return matAlgo14xDs(x, y, self, false);
}),
'number | BigNumber, SparseMatrix': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(x, 0)) {
return zeros(y.size(), y.storage());
}
return matAlgo10xSids(y, x, self, true);
}),
'number | BigNumber, DenseMatrix': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(x, 0)) {
return zeros(y.size(), y.storage());
}
return matAlgo14xDs(y, x, self, true);
})
}, useMatrixForArrayScalar, matrixAlgorithmSuite({
SS: matAlgo08xS0Sid,
DS: matAlgo01xDSid,
SD: matAlgo02xDS0
}));
});

View File

@@ -0,0 +1,115 @@
import { createMatAlgo02xDS0 } from '../../type/matrix/utils/matAlgo02xDS0.js';
import { createMatAlgo11xS0s } from '../../type/matrix/utils/matAlgo11xS0s.js';
import { createMatAlgo14xDs } from '../../type/matrix/utils/matAlgo14xDs.js';
import { createMatAlgo01xDSid } from '../../type/matrix/utils/matAlgo01xDSid.js';
import { createMatAlgo10xSids } from '../../type/matrix/utils/matAlgo10xSids.js';
import { createMatAlgo08xS0Sid } from '../../type/matrix/utils/matAlgo08xS0Sid.js';
import { factory } from '../../utils/factory.js';
import { createMatrixAlgorithmSuite } from '../../type/matrix/utils/matrixAlgorithmSuite.js';
import { rightLogShiftNumber } from '../../plain/number/index.js';
import { createUseMatrixForArrayScalar } from './useMatrixForArrayScalar.js';
var name = 'rightLogShift';
var dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix', 'concat'];
export var createRightLogShift = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
matrix,
equalScalar,
zeros,
DenseMatrix,
concat
} = _ref;
var matAlgo01xDSid = createMatAlgo01xDSid({
typed
});
var matAlgo02xDS0 = createMatAlgo02xDS0({
typed,
equalScalar
});
var matAlgo08xS0Sid = createMatAlgo08xS0Sid({
typed,
equalScalar
});
var matAlgo10xSids = createMatAlgo10xSids({
typed,
DenseMatrix
});
var matAlgo11xS0s = createMatAlgo11xS0s({
typed,
equalScalar
});
var matAlgo14xDs = createMatAlgo14xDs({
typed
});
var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
typed,
matrix,
concat
});
var useMatrixForArrayScalar = createUseMatrixForArrayScalar({
typed,
matrix
});
/**
* Bitwise right logical shift of value x by y number of bits, `x >>> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightLogShift(x, y)
*
* Examples:
*
* math.rightLogShift(4, 2) // returns number 1
*
* math.rightLogShift([16, 32, 64], 4) // returns Array [1, 2, 4]
*
* See also:
*
* bitAnd, bitNot, bitOr, bitXor, leftShift, rightLogShift
*
* @param {number | Array | Matrix} x Value to be shifted
* @param {number} y Amount of shifts
* @return {number | Array | Matrix} `x` zero-filled shifted right `y` times
*/
return typed(name, {
'number, number': rightLogShiftNumber,
// 'BigNumber, BigNumber': ..., // TODO: implement BigNumber support for rightLogShift
'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(y, 0)) {
return x.clone();
}
return matAlgo11xS0s(x, y, self, false);
}),
'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(y, 0)) {
return x.clone();
}
return matAlgo14xDs(x, y, self, false);
}),
'number | BigNumber, SparseMatrix': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(x, 0)) {
return zeros(y.size(), y.storage());
}
return matAlgo10xSids(y, x, self, true);
}),
'number | BigNumber, DenseMatrix': typed.referToSelf(self => (x, y) => {
// check scalar
if (equalScalar(x, 0)) {
return zeros(y.size(), y.storage());
}
return matAlgo14xDs(y, x, self, true);
})
}, useMatrixForArrayScalar, matrixAlgorithmSuite({
SS: matAlgo08xS0Sid,
DS: matAlgo01xDSid,
SD: matAlgo02xDS0
}));
});

View File

@@ -0,0 +1,13 @@
import { factory } from '../../utils/factory.js';
export var createUseMatrixForArrayScalar = /* #__PURE__ */factory('useMatrixForArrayScalar', ['typed', 'matrix'], _ref => {
var {
typed,
matrix
} = _ref;
return {
'Array, number': typed.referTo('DenseMatrix, number', selfDn => (x, y) => selfDn(matrix(x), y).valueOf()),
'Array, BigNumber': typed.referTo('DenseMatrix, BigNumber', selfDB => (x, y) => selfDB(matrix(x), y).valueOf()),
'number, Array': typed.referTo('number, DenseMatrix', selfnD => (x, y) => selfnD(x, matrix(y)).valueOf()),
'BigNumber, Array': typed.referTo('BigNumber, DenseMatrix', selfBD => (x, y) => selfBD(x, matrix(y)).valueOf())
};
});

View File

@@ -0,0 +1,47 @@
import { factory } from '../../utils/factory.js';
var name = 'bellNumbers';
var dependencies = ['typed', 'addScalar', 'isNegative', 'isInteger', 'stirlingS2'];
export var createBellNumbers = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
addScalar,
isNegative,
isInteger,
stirlingS2
} = _ref;
/**
* The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S.
* bellNumbers only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.bellNumbers(n)
*
* Examples:
*
* math.bellNumbers(3) // returns 5
* math.bellNumbers(8) // returns 4140
*
* See also:
*
* stirlingS2
*
* @param {Number | BigNumber} n Total number of objects in the set
* @return {Number | BigNumber} B(n)
*/
return typed(name, {
'number | BigNumber': function number__BigNumber(n) {
if (!isInteger(n) || isNegative(n)) {
throw new TypeError('Non-negative integer value expected in function bellNumbers');
}
// Sum (k=0, n) S(n,k).
var result = 0;
for (var i = 0; i <= n; i++) {
result = addScalar(result, stirlingS2(n, i));
}
return result;
}
});
});

View File

@@ -0,0 +1,43 @@
import { factory } from '../../utils/factory.js';
var name = 'catalan';
var dependencies = ['typed', 'addScalar', 'divideScalar', 'multiplyScalar', 'combinations', 'isNegative', 'isInteger'];
export var createCatalan = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
addScalar,
divideScalar,
multiplyScalar,
combinations,
isNegative,
isInteger
} = _ref;
/**
* The Catalan Numbers enumerate combinatorial structures of many different types.
* catalan only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.catalan(n)
*
* Examples:
*
* math.catalan(3) // returns 5
* math.catalan(8) // returns 1430
*
* See also:
*
* bellNumbers
*
* @param {Number | BigNumber} n nth Catalan number
* @return {Number | BigNumber} Cn(n)
*/
return typed(name, {
'number | BigNumber': function number__BigNumber(n) {
if (!isInteger(n) || isNegative(n)) {
throw new TypeError('Non-negative integer value expected in function catalan');
}
return divideScalar(combinations(multiplyScalar(n, 2), n), addScalar(n, 1));
}
});
});

View File

@@ -0,0 +1,46 @@
import { factory } from '../../utils/factory.js';
var name = 'composition';
var dependencies = ['typed', 'addScalar', 'combinations', 'isNegative', 'isPositive', 'isInteger', 'larger'];
export var createComposition = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
addScalar,
combinations,
isPositive,
isNegative,
isInteger,
larger
} = _ref;
/**
* The composition counts of n into k parts.
*
* composition only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.composition(n, k)
*
* Examples:
*
* math.composition(5, 3) // returns 6
*
* See also:
*
* combinations
*
* @param {Number | BigNumber} n Total number of objects in the set
* @param {Number | BigNumber} k Number of objects in the subset
* @return {Number | BigNumber} Returns the composition counts of n into k parts.
*/
return typed(name, {
'number | BigNumber, number | BigNumber': function number__BigNumber_number__BigNumber(n, k) {
if (!isInteger(n) || !isPositive(n) || !isInteger(k) || !isPositive(k)) {
throw new TypeError('Positive integer value expected in function composition');
} else if (larger(k, n)) {
throw new TypeError('k must be less than or equal to n in function composition');
}
return combinations(addScalar(n, -1), addScalar(k, -1));
}
});
});

View File

@@ -0,0 +1,86 @@
import { factory } from '../../utils/factory.js';
import { isNumber } from '../../utils/is.js';
var name = 'stirlingS2';
var dependencies = ['typed', 'addScalar', 'subtractScalar', 'multiplyScalar', 'divideScalar', 'pow', 'factorial', 'combinations', 'isNegative', 'isInteger', 'number', '?bignumber', 'larger'];
export var createStirlingS2 = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed,
addScalar,
subtractScalar,
multiplyScalar,
divideScalar,
pow,
factorial,
combinations,
isNegative,
isInteger,
number,
bignumber,
larger
} = _ref;
var smallCache = [];
var bigCache = [];
/**
* The Stirling numbers of the second kind, counts the number of ways to partition
* a set of n labelled objects into k nonempty unlabelled subsets.
* stirlingS2 only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* If n = k or k = 1 <= n, then s(n,k) = 1
* If k = 0 < n, then s(n,k) = 0
*
* Note that if either n or k is supplied as a BigNumber, the result will be
* as well.
*
* Syntax:
*
* math.stirlingS2(n, k)
*
* Examples:
*
* math.stirlingS2(5, 3) //returns 25
*
* See also:
*
* bellNumbers
*
* @param {Number | BigNumber} n Total number of objects in the set
* @param {Number | BigNumber} k Number of objects in the subset
* @return {Number | BigNumber} S(n,k)
*/
return typed(name, {
'number | BigNumber, number | BigNumber': function number__BigNumber_number__BigNumber(n, k) {
if (!isInteger(n) || isNegative(n) || !isInteger(k) || isNegative(k)) {
throw new TypeError('Non-negative integer value expected in function stirlingS2');
} else if (larger(k, n)) {
throw new TypeError('k must be less than or equal to n in function stirlingS2');
}
var big = !(isNumber(n) && isNumber(k));
var cache = big ? bigCache : smallCache;
var make = big ? bignumber : number;
var nn = number(n);
var nk = number(k);
/* See if we already have the value: */
if (cache[nn] && cache[nn].length > nk) {
return cache[nn][nk];
}
/* Fill the cache */
for (var m = 0; m <= nn; ++m) {
if (!cache[m]) {
cache[m] = [m === 0 ? make(1) : make(0)];
}
if (m === 0) continue;
var row = cache[m];
var prev = cache[m - 1];
for (var i = row.length; i <= m && i <= nk; ++i) {
if (i === m) {
row[i] = 1;
} else {
row[i] = addScalar(multiplyScalar(make(i), prev[i]), prev[i - 1]);
}
}
}
return cache[nn][nk];
}
});
});

50
node_modules/mathjs/lib/esm/function/complex/arg.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
var name = 'arg';
var dependencies = ['typed'];
export var createArg = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Compute the argument of a complex value.
* For a complex number `a + bi`, the argument is computed as `atan2(b, a)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.arg(x)
*
* Examples:
*
* const a = math.complex(2, 2)
* math.arg(a) / math.pi // returns number 0.25
*
* const b = math.complex('2 + 3i')
* math.arg(b) // returns number 0.982793723247329
* math.atan2(3, 2) // returns number 0.982793723247329
*
* See also:
*
* re, im, conj, abs
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* A complex number or array with complex numbers
* @return {number | BigNumber | Array | Matrix} The argument of x
*/
return typed(name, {
number: function number(x) {
return Math.atan2(0, x);
},
BigNumber: function BigNumber(x) {
return x.constructor.atan2(0, x);
},
Complex: function Complex(x) {
return x.arg();
},
// TODO: implement BigNumber support for function arg
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
});
});

39
node_modules/mathjs/lib/esm/function/complex/conj.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
var name = 'conj';
var dependencies = ['typed'];
export var createConj = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Compute the complex conjugate of a complex value.
* If `x = a+bi`, the complex conjugate of `x` is `a - bi`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.conj(x)
*
* Examples:
*
* math.conj(math.complex('2 + 3i')) // returns Complex 2 - 3i
* math.conj(math.complex('2 - 3i')) // returns Complex 2 + 3i
* math.conj(math.complex('-5.2i')) // returns Complex 5.2i
*
* See also:
*
* re, im, arg, abs
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* A complex number or array with complex numbers
* @return {number | BigNumber | Complex | Array | Matrix}
* The complex conjugate of x
*/
return typed(name, {
'number | BigNumber | Fraction': x => x,
Complex: x => x.conjugate(),
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
});
});

42
node_modules/mathjs/lib/esm/function/complex/im.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
var name = 'im';
var dependencies = ['typed'];
export var createIm = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Get the imaginary part of a complex number.
* For a complex number `a + bi`, the function returns `b`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.im(x)
*
* Examples:
*
* const a = math.complex(2, 3)
* math.re(a) // returns number 2
* math.im(a) // returns number 3
*
* math.re(math.complex('-5.2i')) // returns number -5.2
* math.re(math.complex(2.4)) // returns number 0
*
* See also:
*
* re, conj, abs, arg
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* A complex number or array with complex numbers
* @return {number | BigNumber | Array | Matrix} The imaginary part of x
*/
return typed(name, {
number: () => 0,
'BigNumber | Fraction': x => x.mul(0),
Complex: x => x.im,
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
});
});

41
node_modules/mathjs/lib/esm/function/complex/re.js generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import { factory } from '../../utils/factory.js';
import { deepMap } from '../../utils/collection.js';
var name = 're';
var dependencies = ['typed'];
export var createRe = /* #__PURE__ */factory(name, dependencies, _ref => {
var {
typed
} = _ref;
/**
* Get the real part of a complex number.
* For a complex number `a + bi`, the function returns `a`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.re(x)
*
* Examples:
*
* const a = math.complex(2, 3)
* math.re(a) // returns number 2
* math.im(a) // returns number 3
*
* math.re(math.complex('-5.2i')) // returns number 0
* math.re(math.complex(2.4)) // returns number 2.4
*
* See also:
*
* im, conj, abs, arg
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* A complex number or array with complex numbers
* @return {number | BigNumber | Array | Matrix} The real part of x
*/
return typed(name, {
'number | BigNumber | Fraction': x => x,
Complex: x => x.re,
'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
});
});

Some files were not shown because too many files have changed in this diff Show More