feat:node-modules
This commit is contained in:
382
node_modules/mathjs/lib/cjs/function/algebra/decomposition/lup.js
generated
vendored
Normal file
382
node_modules/mathjs/lib/cjs/function/algebra/decomposition/lup.js
generated
vendored
Normal file
@@ -0,0 +1,382 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createLup = void 0;
|
||||
var _object = require("../../../utils/object.js");
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
const name = 'lup';
|
||||
const dependencies = ['typed', 'matrix', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'larger', 'equalScalar', 'unaryMinus', 'DenseMatrix', 'SparseMatrix', 'Spa'];
|
||||
const createLup = exports.createLup = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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 (m) {
|
||||
return _denseLUP(m);
|
||||
},
|
||||
SparseMatrix: function (m) {
|
||||
return _sparseLUP(m);
|
||||
},
|
||||
Array: function (a) {
|
||||
// create dense matrix from array
|
||||
const m = matrix(a);
|
||||
// lup, use matrix implementation
|
||||
const r = _denseLUP(m);
|
||||
// result
|
||||
return {
|
||||
L: r.L.valueOf(),
|
||||
U: r.U.valueOf(),
|
||||
p: r.p
|
||||
};
|
||||
}
|
||||
});
|
||||
function _denseLUP(m) {
|
||||
// rows & columns
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
// minimum rows and columns
|
||||
let n = Math.min(rows, columns);
|
||||
// matrix array, clone original data
|
||||
const data = (0, _object.clone)(m._data);
|
||||
// l matrix arrays
|
||||
const ldata = [];
|
||||
const lsize = [rows, n];
|
||||
// u matrix arrays
|
||||
const udata = [];
|
||||
const usize = [n, columns];
|
||||
// vars
|
||||
let i, j, k;
|
||||
// permutation vector
|
||||
const 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
|
||||
const min = Math.min(i, j);
|
||||
// v[i, j]
|
||||
let 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
|
||||
let pi = j;
|
||||
let pabsv = 0;
|
||||
let vjj = 0;
|
||||
// loop rows
|
||||
for (i = j; i < rows; i++) {
|
||||
// data @ i, j
|
||||
const v = data[i][j];
|
||||
// absolute value
|
||||
const 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
|
||||
const 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
|
||||
const l = new DenseMatrix({
|
||||
data: ldata,
|
||||
size: lsize
|
||||
});
|
||||
// u matrix
|
||||
const u = new DenseMatrix({
|
||||
data: udata,
|
||||
size: usize
|
||||
});
|
||||
// p vector
|
||||
const 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 () {
|
||||
return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
|
||||
}
|
||||
};
|
||||
}
|
||||
function _sparseLUP(m) {
|
||||
// rows & columns
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
// minimum rows and columns
|
||||
const n = Math.min(rows, columns);
|
||||
// matrix arrays (will not be modified, thanks to permutation vector)
|
||||
const values = m._values;
|
||||
const index = m._index;
|
||||
const ptr = m._ptr;
|
||||
// l matrix arrays
|
||||
const lvalues = [];
|
||||
const lindex = [];
|
||||
const lptr = [];
|
||||
const lsize = [rows, n];
|
||||
// u matrix arrays
|
||||
const uvalues = [];
|
||||
const uindex = [];
|
||||
const uptr = [];
|
||||
const usize = [n, columns];
|
||||
// vars
|
||||
let i, j, k;
|
||||
// permutation vectors, (current index -> original index) and (original index -> current index)
|
||||
const pvCo = [];
|
||||
const pvOc = [];
|
||||
for (i = 0; i < rows; i++) {
|
||||
pvCo[i] = i;
|
||||
pvOc[i] = i;
|
||||
}
|
||||
// swap indices in permutation vectors (condition x < y)!
|
||||
const swapIndeces = function (x, y) {
|
||||
// find pv indeces getting data from x and y
|
||||
const kx = pvOc[x];
|
||||
const 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
|
||||
for (j = 0; j < columns; j++) {
|
||||
// sparse accumulator
|
||||
const 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]
|
||||
const k0 = ptr[j];
|
||||
const 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
|
||||
let pi = j;
|
||||
let vjj = spa.get(j);
|
||||
let pabsv = abs(vjj);
|
||||
// loop values in spa (order by row, below diagonal)
|
||||
spa.forEach(j + 1, rows - 1, function (x, v) {
|
||||
// absolute value
|
||||
const 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);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
// 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 () {
|
||||
return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
229
node_modules/mathjs/lib/cjs/function/algebra/decomposition/qr.js
generated
vendored
Normal file
229
node_modules/mathjs/lib/cjs/function/algebra/decomposition/qr.js
generated
vendored
Normal file
@@ -0,0 +1,229 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createQr = void 0;
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
const name = 'qr';
|
||||
const dependencies = ['typed', 'matrix', 'zeros', 'identity', 'isZero', 'equal', 'sign', 'sqrt', 'conj', 'unaryMinus', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'complex'];
|
||||
const createQr = exports.createQr = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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 (0, _extends2.default)(typed(name, {
|
||||
DenseMatrix: function (m) {
|
||||
return _denseQR(m);
|
||||
},
|
||||
SparseMatrix: function (m) {
|
||||
return _sparseQR(m);
|
||||
},
|
||||
Array: function (a) {
|
||||
// create dense matrix from array
|
||||
const m = matrix(a);
|
||||
// lup, use matrix implementation
|
||||
const r = _denseQR(m);
|
||||
// result
|
||||
return {
|
||||
Q: r.Q.valueOf(),
|
||||
R: r.R.valueOf()
|
||||
};
|
||||
}
|
||||
}), {
|
||||
_denseQRimpl
|
||||
});
|
||||
function _denseQRimpl(m) {
|
||||
// rows & columns (m x n)
|
||||
const rows = m._size[0]; // m
|
||||
const cols = m._size[1]; // n
|
||||
|
||||
const Q = identity([rows], 'dense');
|
||||
const Qdata = Q._data;
|
||||
const R = m.clone();
|
||||
const Rdata = R._data;
|
||||
|
||||
// vars
|
||||
let i, j, k;
|
||||
const 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.
|
||||
*
|
||||
*/
|
||||
|
||||
const pivot = Rdata[k][k];
|
||||
const sgn = unaryMinus(equal(pivot, 0) ? 1 : sign(pivot));
|
||||
const conjSgn = conj(sgn);
|
||||
let alphaSquared = 0;
|
||||
for (i = k; i < rows; i++) {
|
||||
alphaSquared = addScalar(alphaSquared, multiplyScalar(Rdata[i][k], conj(Rdata[i][k])));
|
||||
}
|
||||
const alpha = multiplyScalar(sgn, sqrt(alphaSquared));
|
||||
if (!isZero(alpha)) {
|
||||
// first element in vector u
|
||||
const 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)
|
||||
const tau = unaryMinus(conj(divideScalar(u1, alpha)));
|
||||
let s;
|
||||
|
||||
/*
|
||||
* 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 () {
|
||||
return 'Q: ' + this.Q.toString() + '\nR: ' + this.R.toString();
|
||||
}
|
||||
};
|
||||
}
|
||||
function _denseQR(m) {
|
||||
const ret = _denseQRimpl(m);
|
||||
const Rdata = ret.R._data;
|
||||
if (m._data.length > 0) {
|
||||
const zero = Rdata[0][0].type === 'Complex' ? complex(0) : 0;
|
||||
for (let i = 0; i < Rdata.length; ++i) {
|
||||
for (let 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');
|
||||
}
|
||||
});
|
||||
76
node_modules/mathjs/lib/cjs/function/algebra/decomposition/schur.js
generated
vendored
Normal file
76
node_modules/mathjs/lib/cjs/function/algebra/decomposition/schur.js
generated
vendored
Normal file
@@ -0,0 +1,76 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createSchur = void 0;
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
const name = 'schur';
|
||||
const dependencies = ['typed', 'matrix', 'identity', 'multiply', 'qr', 'norm', 'subtract'];
|
||||
const createSchur = exports.createSchur = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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 (X) {
|
||||
const r = _schur(matrix(X));
|
||||
return {
|
||||
U: r.U.valueOf(),
|
||||
T: r.T.valueOf()
|
||||
};
|
||||
},
|
||||
Matrix: function (X) {
|
||||
return _schur(X);
|
||||
}
|
||||
});
|
||||
function _schur(X) {
|
||||
const n = X.size()[0];
|
||||
let A = X;
|
||||
let U = identity(n);
|
||||
let k = 0;
|
||||
let A0;
|
||||
do {
|
||||
A0 = A;
|
||||
const QR = qr(A);
|
||||
const Q = QR.Q;
|
||||
const 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
|
||||
};
|
||||
}
|
||||
});
|
||||
107
node_modules/mathjs/lib/cjs/function/algebra/decomposition/slu.js
generated
vendored
Normal file
107
node_modules/mathjs/lib/cjs/function/algebra/decomposition/slu.js
generated
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createSlu = void 0;
|
||||
var _number = require("../../../utils/number.js");
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _csSqr = require("../sparse/csSqr.js");
|
||||
var _csLu = require("../sparse/csLu.js");
|
||||
const name = 'slu';
|
||||
const dependencies = ['typed', 'abs', 'add', 'multiply', 'transpose', 'divideScalar', 'subtract', 'larger', 'largerEq', 'SparseMatrix'];
|
||||
const createSlu = exports.createSlu = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
typed,
|
||||
abs,
|
||||
add,
|
||||
multiply,
|
||||
transpose,
|
||||
divideScalar,
|
||||
subtract,
|
||||
larger,
|
||||
largerEq,
|
||||
SparseMatrix
|
||||
} = _ref;
|
||||
const csSqr = (0, _csSqr.createCsSqr)({
|
||||
add,
|
||||
multiply,
|
||||
transpose
|
||||
});
|
||||
const csLu = (0, _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 (a, order, threshold) {
|
||||
// verify order
|
||||
if (!(0, _number.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
|
||||
const s = csSqr(order, a, false);
|
||||
|
||||
// perform lu decomposition
|
||||
const f = csLu(a, s, threshold);
|
||||
|
||||
// return decomposition
|
||||
return {
|
||||
L: f.L,
|
||||
U: f.U,
|
||||
p: f.pinv,
|
||||
q: s.q,
|
||||
toString: function () {
|
||||
return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\np: ' + this.p.toString() + (this.q ? '\nq: ' + this.q.toString() : '') + '\n';
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
||||
525
node_modules/mathjs/lib/cjs/function/algebra/derivative.js
generated
vendored
Normal file
525
node_modules/mathjs/lib/cjs/function/algebra/derivative.js
generated
vendored
Normal file
@@ -0,0 +1,525 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createDerivative = void 0;
|
||||
var _is = require("../../utils/is.js");
|
||||
var _factory = require("../../utils/factory.js");
|
||||
var _number = require("../../utils/number.js");
|
||||
const name = 'derivative';
|
||||
const dependencies = ['typed', 'config', 'parse', 'simplify', 'equal', 'isZero', 'numeric', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
|
||||
const createDerivative = exports.createDerivative = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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) {
|
||||
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
|
||||
simplify: true
|
||||
};
|
||||
const constNodes = {};
|
||||
constTag(constNodes, expr, variable.name);
|
||||
const res = _derivative(expr, constNodes);
|
||||
return options.simplify ? simplify(res) : res;
|
||||
}
|
||||
function parseIdentifier(string) {
|
||||
const symbol = parse(string);
|
||||
if (!symbol.isSymbolNode) {
|
||||
throw new TypeError('Invalid variable. ' + `Cannot parse ${JSON.stringify(string)} into a variable in function derivative`);
|
||||
}
|
||||
return symbol;
|
||||
}
|
||||
const 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
|
||||
const _derivTex = typed('_derivTex', {
|
||||
'Node, SymbolNode': function (expr, x) {
|
||||
if ((0, _is.isConstantNode)(expr) && (0, _is.typeOf)(expr.value) === 'string') {
|
||||
return _derivTex(parse(expr.value).toString(), x.toString(), 1);
|
||||
} else {
|
||||
return _derivTex(expr.toTex(), x.toString(), 1);
|
||||
}
|
||||
},
|
||||
'Node, ConstantNode': function (expr, x) {
|
||||
if ((0, _is.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 (expr, x, order) {
|
||||
return _derivTex(expr.toString(), x.name, order.value);
|
||||
},
|
||||
'string, string, number': function (expr, x, order) {
|
||||
let d;
|
||||
if (order === 1) {
|
||||
d = '{d\\over d' + x + '}';
|
||||
} else {
|
||||
d = '{d^{' + order + '}\\over d' + x + '^{' + order + '}}';
|
||||
}
|
||||
return d + `\\left[${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?
|
||||
const constTag = typed('constTag', {
|
||||
'Object, ConstantNode, string': function (constNodes, node) {
|
||||
constNodes[node] = true;
|
||||
return true;
|
||||
},
|
||||
'Object, SymbolNode, string': function (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 (constNodes, node, varName) {
|
||||
return constTag(constNodes, node.content, varName);
|
||||
},
|
||||
'Object, FunctionAssignmentNode, string': function (constNodes, node, varName) {
|
||||
if (!node.params.includes(varName)) {
|
||||
constNodes[node] = true;
|
||||
return true;
|
||||
}
|
||||
return constTag(constNodes, node.expr, varName);
|
||||
},
|
||||
'Object, FunctionNode | OperatorNode, string': function (constNodes, node, varName) {
|
||||
if (node.args.length > 0) {
|
||||
let isConst = constTag(constNodes, node.args[0], varName);
|
||||
for (let 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`
|
||||
*/
|
||||
const _derivative = typed('_derivative', {
|
||||
'ConstantNode, Object': function (node) {
|
||||
return createConstantNode(0);
|
||||
},
|
||||
'SymbolNode, Object': function (node, constNodes) {
|
||||
if (constNodes[node] !== undefined) {
|
||||
return createConstantNode(0);
|
||||
}
|
||||
return createConstantNode(1);
|
||||
},
|
||||
'ParenthesisNode, Object': function (node, constNodes) {
|
||||
return new ParenthesisNode(_derivative(node.content, constNodes));
|
||||
},
|
||||
'FunctionAssignmentNode, Object': function (node, constNodes) {
|
||||
if (constNodes[node] !== undefined) {
|
||||
return createConstantNode(0);
|
||||
}
|
||||
return _derivative(node.expr, constNodes);
|
||||
},
|
||||
'FunctionNode, Object': function (node, constNodes) {
|
||||
if (constNodes[node] !== undefined) {
|
||||
return createConstantNode(0);
|
||||
}
|
||||
const arg0 = node.args[0];
|
||||
let arg1;
|
||||
let div = false; // is output a fraction?
|
||||
let negative = false; // is output negative?
|
||||
|
||||
let 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');
|
||||
}
|
||||
let 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)) */
|
||||
let chainDerivative = _derivative(arg0, constNodes);
|
||||
if (negative) {
|
||||
chainDerivative = new OperatorNode('-', 'unaryMinus', [chainDerivative]);
|
||||
}
|
||||
return new OperatorNode(op, func, [chainDerivative, funcDerivative]);
|
||||
},
|
||||
'OperatorNode, Object': function (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)
|
||||
const constantTerms = node.args.filter(function (arg) {
|
||||
return constNodes[arg] !== undefined;
|
||||
});
|
||||
if (constantTerms.length > 0) {
|
||||
const nonConstantTerms = node.args.filter(function (arg) {
|
||||
return constNodes[arg] === undefined;
|
||||
});
|
||||
const nonConstantNode = nonConstantTerms.length === 1 ? nonConstantTerms[0] : new OperatorNode('*', 'multiply', nonConstantTerms);
|
||||
const 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()) {
|
||||
const arg0 = node.args[0];
|
||||
const 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()) {
|
||||
const arg0 = node.args[0];
|
||||
const arg1 = node.args[1];
|
||||
if (constNodes[arg0] !== undefined) {
|
||||
// If is secretly constant; 0^f(x) = 1 (in JS), 1^f(x) = 1
|
||||
if ((0, _is.isConstantNode)(arg0) && (isZero(arg0.value) || equal(arg0.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', [arg0.clone()]), _derivative(arg1.clone(), constNodes)])]);
|
||||
}
|
||||
if (constNodes[arg1] !== undefined) {
|
||||
if ((0, _is.isConstantNode)(arg1)) {
|
||||
// If is secretly constant; f(x)^0 = 1 -> d/dx(1) = 0
|
||||
if (isZero(arg1.value)) {
|
||||
return createConstantNode(0);
|
||||
}
|
||||
// Ignore exponent; f(x)^1 = f(x)
|
||||
if (equal(arg1.value, 1)) {
|
||||
return _derivative(arg0, constNodes);
|
||||
}
|
||||
}
|
||||
|
||||
// Elementary Power Rule, d/dx(f(x)^c) = c*f'(x)*f(x)^(c-1)
|
||||
const powMinusOne = new OperatorNode('^', 'pow', [arg0.clone(), new OperatorNode('-', 'subtract', [arg1, createConstantNode(1)])]);
|
||||
return new OperatorNode('*', 'multiply', [arg1.clone(), new OperatorNode('*', 'multiply', [_derivative(arg0, constNodes), powMinusOne])]);
|
||||
}
|
||||
|
||||
// Functional Power Rule, d/dx(f^g) = f^g*[f'*(g/f) + g'ln(f)]
|
||||
return new OperatorNode('*', 'multiply', [new OperatorNode('^', 'pow', [arg0.clone(), arg1.clone()]), new OperatorNode('+', 'add', [new OperatorNode('*', 'multiply', [_derivative(arg0, constNodes), new OperatorNode('/', 'divide', [arg1.clone(), arg0.clone()])]), new OperatorNode('*', 'multiply', [_derivative(arg1, constNodes), new FunctionNode('log', [arg0.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 || (0, _number.safeNumberType)(String(value), config)));
|
||||
}
|
||||
return derivative;
|
||||
});
|
||||
60
node_modules/mathjs/lib/cjs/function/algebra/leafCount.js
generated
vendored
Normal file
60
node_modules/mathjs/lib/cjs/function/algebra/leafCount.js
generated
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createLeafCount = void 0;
|
||||
var _factory = require("../../utils/factory.js");
|
||||
const name = 'leafCount';
|
||||
const dependencies = ['parse', 'typed'];
|
||||
const createLeafCount = exports.createLeafCount = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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) {
|
||||
let 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 (expr) {
|
||||
return countLeaves(expr);
|
||||
}
|
||||
});
|
||||
});
|
||||
58
node_modules/mathjs/lib/cjs/function/algebra/lyap.js
generated
vendored
Normal file
58
node_modules/mathjs/lib/cjs/function/algebra/lyap.js
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createLyap = void 0;
|
||||
var _factory = require("../../utils/factory.js");
|
||||
const name = 'lyap';
|
||||
const dependencies = ['typed', 'matrix', 'sylvester', 'multiply', 'transpose'];
|
||||
const createLyap = exports.createLyap = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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 (A, Q) {
|
||||
return sylvester(A, transpose(A), multiply(-1, Q));
|
||||
},
|
||||
'Array, Matrix': function (A, Q) {
|
||||
return sylvester(matrix(A), transpose(matrix(A)), multiply(-1, Q));
|
||||
},
|
||||
'Matrix, Array': function (A, Q) {
|
||||
return sylvester(A, transpose(matrix(A)), matrix(multiply(-1, Q)));
|
||||
},
|
||||
'Array, Array': function (A, Q) {
|
||||
return sylvester(matrix(A), transpose(matrix(A)), matrix(multiply(-1, Q))).toArray();
|
||||
}
|
||||
});
|
||||
});
|
||||
128
node_modules/mathjs/lib/cjs/function/algebra/polynomialRoot.js
generated
vendored
Normal file
128
node_modules/mathjs/lib/cjs/function/algebra/polynomialRoot.js
generated
vendored
Normal file
@@ -0,0 +1,128 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createPolynomialRoot = void 0;
|
||||
var _factory = require("../../utils/factory.js");
|
||||
const name = 'polynomialRoot';
|
||||
const dependencies = ['typed', 'isZero', 'equalScalar', 'add', 'subtract', 'multiply', 'divide', 'sqrt', 'unaryMinus', 'cbrt', 'typeOf', 'im', 're'];
|
||||
const createPolynomialRoot = exports.createPolynomialRoot = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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) => {
|
||||
const coeffs = [constant, ...restCoeffs];
|
||||
while (coeffs.length > 0 && isZero(coeffs[coeffs.length - 1])) {
|
||||
coeffs.pop();
|
||||
}
|
||||
if (coeffs.length < 2) {
|
||||
throw new RangeError(`Polynomial [${constant}, ${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
|
||||
const [c, b, a] = coeffs;
|
||||
const denom = multiply(2, a);
|
||||
const d1 = multiply(b, b);
|
||||
const d2 = multiply(4, a, c);
|
||||
if (equalScalar(d1, d2)) return [divide(unaryMinus(b), denom)];
|
||||
const 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
|
||||
const [d, c, b, a] = coeffs;
|
||||
const denom = unaryMinus(multiply(3, a));
|
||||
const D0_1 = multiply(b, b);
|
||||
const D0_2 = multiply(3, a, c);
|
||||
const D1_1 = add(multiply(2, b, b, b), multiply(27, a, a, d));
|
||||
const D1_2 = multiply(9, a, b, c);
|
||||
if (equalScalar(D0_1, D0_2) && equalScalar(D1_1, D1_2)) {
|
||||
return [divide(b, denom)];
|
||||
}
|
||||
const Delta0 = subtract(D0_1, D0_2);
|
||||
const Delta1 = subtract(D1_1, D1_2);
|
||||
const discriminant1 = add(multiply(18, a, b, c, d), multiply(b, b, c, c));
|
||||
const 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
|
||||
let 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);
|
||||
}
|
||||
const allRoots = true;
|
||||
const 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 ${coeffs}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
825
node_modules/mathjs/lib/cjs/function/algebra/rationalize.js
generated
vendored
Normal file
825
node_modules/mathjs/lib/cjs/function/algebra/rationalize.js
generated
vendored
Normal file
@@ -0,0 +1,825 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createRationalize = void 0;
|
||||
var _number = require("../../utils/number.js");
|
||||
var _factory = require("../../utils/factory.js");
|
||||
const name = 'rationalize';
|
||||
const 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'];
|
||||
const createRationalize = exports.createRationalize = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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) {
|
||||
let scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
||||
let detailed = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
|
||||
const setRules = rulesRationalize(); // Rules for change polynomial in near canonical form
|
||||
const polyRet = polynomial(expr, scope, true, setRules.firstRules); // Check if expression is a rationalizable polynomial
|
||||
const nVars = polyRet.variables.length;
|
||||
const noExactFractions = {
|
||||
exactFractions: false
|
||||
};
|
||||
const 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!)
|
||||
let sBefore; // Previous expression
|
||||
let rules;
|
||||
let eDistrDiv = true;
|
||||
let redoInic = false;
|
||||
// Apply the initial rules, including succ div rules:
|
||||
expr = simplify(expr, setRules.firstRules, {}, noExactFractions);
|
||||
let 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
|
||||
|
||||
const coefficients = [];
|
||||
const 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) {
|
||||
const variables = [];
|
||||
const node = simplify(expr, rules, scope, {
|
||||
exactFractions: false
|
||||
}); // Resolves any variables and functions with all defined parameters
|
||||
extended = !!extended;
|
||||
const oper = '+-*' + (extended ? '/' : '');
|
||||
recPoly(node);
|
||||
const 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) {
|
||||
const 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' || !(0, _number.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 (let i = 0; i < node.args.length; i++) {
|
||||
recPoly(node.args[i]);
|
||||
}
|
||||
} // type of operator
|
||||
} else if (tp === 'SymbolNode') {
|
||||
const name = node.name; // variable name
|
||||
const 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() {
|
||||
const 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'
|
||||
}];
|
||||
const 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
|
||||
|
||||
const 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
|
||||
|
||||
const rulesSucDiv = [{
|
||||
l: '(n1/(n2/n3))',
|
||||
r: '((n1*n3)/n2)'
|
||||
},
|
||||
// Division simplification
|
||||
{
|
||||
l: '(n1/n2/n3)',
|
||||
r: '(n1/(n2*n3))'
|
||||
}];
|
||||
const 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) {
|
||||
const tp = node.type;
|
||||
const internal = arguments.length > 1; // TRUE in internal calls
|
||||
|
||||
if (tp === 'OperatorNode' && node.isBinary()) {
|
||||
let does = false;
|
||||
let 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 && (0, _number.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
|
||||
//
|
||||
const nEsqTopo = node.args[0];
|
||||
const 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 (let 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
|
||||
const 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 = '';
|
||||
let maxExpo = 0; // maximum exponent
|
||||
let varname = ''; // variable name
|
||||
|
||||
recurPol(node, null, o);
|
||||
maxExpo = coefficients.length - 1;
|
||||
let first = true;
|
||||
let no;
|
||||
for (let i = maxExpo; i >= 0; i--) {
|
||||
if (coefficients[i] === 0) continue;
|
||||
let n1 = new ConstantNode(first ? coefficients[i] : Math.abs(coefficients[i]));
|
||||
const op = coefficients[i] < 0 ? '-' : '+';
|
||||
if (i > 0) {
|
||||
// Is not a constant without variable
|
||||
let n2 = new SymbolNode(varname);
|
||||
if (i > 1) {
|
||||
const 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) {
|
||||
const 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 (let 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') {
|
||||
const 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 (!(0, _number.isInteger)(valor) || valor <= 0) {
|
||||
throw new Error('Non-integer exponent is not allowed');
|
||||
}
|
||||
for (let i = maxExpo + 1; i < valor; i++) coefficients[i] = 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
|
||||
});
|
||||
103
node_modules/mathjs/lib/cjs/function/algebra/resolve.js
generated
vendored
Normal file
103
node_modules/mathjs/lib/cjs/function/algebra/resolve.js
generated
vendored
Normal file
@@ -0,0 +1,103 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createResolve = void 0;
|
||||
var _map = require("../../utils/map.js");
|
||||
var _is = require("../../utils/is.js");
|
||||
var _factory = require("../../utils/factory.js");
|
||||
const name = 'resolve';
|
||||
const dependencies = ['typed', 'parse', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode'];
|
||||
const createResolve = exports.createResolve = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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) {
|
||||
let 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 ((0, _is.isSymbolNode)(node)) {
|
||||
if (within.has(node.name)) {
|
||||
const variables = Array.from(within).join(', ');
|
||||
throw new ReferenceError(`recursive loop of variable definitions among {${variables}}`);
|
||||
}
|
||||
const value = scope.get(node.name);
|
||||
if ((0, _is.isNode)(value)) {
|
||||
const 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 ((0, _is.isOperatorNode)(node)) {
|
||||
const args = node.args.map(function (arg) {
|
||||
return _resolve(arg, scope, within);
|
||||
});
|
||||
return new OperatorNode(node.op, node.fn, args, node.implicit);
|
||||
} else if ((0, _is.isParenthesisNode)(node)) {
|
||||
return new ParenthesisNode(_resolve(node.content, scope, within));
|
||||
} else if ((0, _is.isFunctionNode)(node)) {
|
||||
const 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, (0, _map.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, (0, _map.createMap)(scope))),
|
||||
'Matrix, Object': typed.referTo('Matrix,Map', selfMM => (A, scope) => selfMM(A, (0, _map.createMap)(scope))),
|
||||
'Array | Matrix, Map': typed.referToSelf(self => (A, scope) => A.map(n => self(n, scope)))
|
||||
});
|
||||
});
|
||||
1251
node_modules/mathjs/lib/cjs/function/algebra/simplify.js
generated
vendored
Normal file
1251
node_modules/mathjs/lib/cjs/function/algebra/simplify.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
269
node_modules/mathjs/lib/cjs/function/algebra/simplify/util.js
generated
vendored
Normal file
269
node_modules/mathjs/lib/cjs/function/algebra/simplify/util.js
generated
vendored
Normal file
@@ -0,0 +1,269 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createUtil = void 0;
|
||||
var _is = require("../../../utils/is.js");
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _object = require("../../../utils/object.js");
|
||||
const name = 'simplifyUtil';
|
||||
const dependencies = ['FunctionNode', 'OperatorNode', 'SymbolNode'];
|
||||
const createUtil = exports.createUtil = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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: */
|
||||
const T = true;
|
||||
const F = false;
|
||||
const defaultName = 'defaultF';
|
||||
const 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
|
||||
}
|
||||
};
|
||||
const realContext = {
|
||||
divide: {
|
||||
total: F
|
||||
},
|
||||
log: {
|
||||
total: F
|
||||
}
|
||||
};
|
||||
const positiveContext = {
|
||||
subtract: {
|
||||
total: F
|
||||
},
|
||||
abs: {
|
||||
trivial: T
|
||||
},
|
||||
log: {
|
||||
total: T
|
||||
}
|
||||
};
|
||||
function hasProperty(nodeOrName, property) {
|
||||
let context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultContext;
|
||||
let name = defaultName;
|
||||
if (typeof nodeOrName === 'string') {
|
||||
name = nodeOrName;
|
||||
} else if ((0, _is.isOperatorNode)(nodeOrName)) {
|
||||
name = nodeOrName.fn.toString();
|
||||
} else if ((0, _is.isFunctionNode)(nodeOrName)) {
|
||||
name = nodeOrName.name;
|
||||
} else if ((0, _is.isParenthesisNode)(nodeOrName)) {
|
||||
name = 'paren';
|
||||
}
|
||||
if ((0, _object.hasOwnProperty)(context, name)) {
|
||||
const properties = context[name];
|
||||
if ((0, _object.hasOwnProperty)(properties, property)) {
|
||||
return properties[property];
|
||||
}
|
||||
if ((0, _object.hasOwnProperty)(defaultContext, name)) {
|
||||
return defaultContext[name][property];
|
||||
}
|
||||
}
|
||||
if ((0, _object.hasOwnProperty)(context, defaultName)) {
|
||||
const properties = context[defaultName];
|
||||
if ((0, _object.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 ((0, _object.hasOwnProperty)(defaultContext, name)) {
|
||||
const properties = defaultContext[name];
|
||||
if ((0, _object.hasOwnProperty)(properties, property)) {
|
||||
return properties[property];
|
||||
}
|
||||
}
|
||||
return defaultContext[defaultName][property];
|
||||
}
|
||||
function isCommutative(node) {
|
||||
let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultContext;
|
||||
return hasProperty(node, 'commutative', context);
|
||||
}
|
||||
function isAssociative(node) {
|
||||
let 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) {
|
||||
const merged = {
|
||||
...primary
|
||||
};
|
||||
for (const prop in secondary) {
|
||||
if ((0, _object.hasOwnProperty)(primary, prop)) {
|
||||
merged[prop] = {
|
||||
...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 (let 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) {
|
||||
let op;
|
||||
const children = [];
|
||||
const findChildren = function (node) {
|
||||
for (let i = 0; i < node.args.length; i++) {
|
||||
const child = node.args[i];
|
||||
if ((0, _is.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;
|
||||
}
|
||||
const makeNode = createMakeNodeFunction(node);
|
||||
const l = node.args.length;
|
||||
for (let i = 0; i < l; i++) {
|
||||
unflattenr(node.args[i], context);
|
||||
}
|
||||
if (l > 2 && isAssociative(node, context)) {
|
||||
let 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;
|
||||
}
|
||||
const makeNode = createMakeNodeFunction(node);
|
||||
const l = node.args.length;
|
||||
for (let i = 0; i < l; i++) {
|
||||
unflattenl(node.args[i], context);
|
||||
}
|
||||
if (l > 2 && isAssociative(node, context)) {
|
||||
let curnode = node.args.shift();
|
||||
while (node.args.length > 0) {
|
||||
curnode = makeNode([curnode, node.args.shift()]);
|
||||
}
|
||||
node.args = curnode.args;
|
||||
}
|
||||
}
|
||||
function createMakeNodeFunction(node) {
|
||||
if ((0, _is.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
|
||||
};
|
||||
});
|
||||
38
node_modules/mathjs/lib/cjs/function/algebra/simplify/wildcards.js
generated
vendored
Normal file
38
node_modules/mathjs/lib/cjs/function/algebra/simplify/wildcards.js
generated
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.isConstantExpression = isConstantExpression;
|
||||
Object.defineProperty(exports, "isConstantNode", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _is.isConstantNode;
|
||||
}
|
||||
});
|
||||
exports.isNumericNode = isNumericNode;
|
||||
Object.defineProperty(exports, "isVariableNode", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return _is.isSymbolNode;
|
||||
}
|
||||
});
|
||||
var _is = require("../../../utils/is.js");
|
||||
function isNumericNode(x) {
|
||||
return (0, _is.isConstantNode)(x) || (0, _is.isOperatorNode)(x) && x.isUnary() && (0, _is.isConstantNode)(x.args[0]);
|
||||
}
|
||||
function isConstantExpression(x) {
|
||||
if ((0, _is.isConstantNode)(x)) {
|
||||
// Basic Constant types
|
||||
return true;
|
||||
}
|
||||
if (((0, _is.isFunctionNode)(x) || (0, _is.isOperatorNode)(x)) && x.args.every(isConstantExpression)) {
|
||||
// Can be constant depending on arguments
|
||||
return true;
|
||||
}
|
||||
if ((0, _is.isParenthesisNode)(x) && isConstantExpression(x.content)) {
|
||||
// Parenthesis are transparent
|
||||
return true;
|
||||
}
|
||||
return false; // Probably missing some edge cases
|
||||
}
|
||||
478
node_modules/mathjs/lib/cjs/function/algebra/simplifyConstant.js
generated
vendored
Normal file
478
node_modules/mathjs/lib/cjs/function/algebra/simplifyConstant.js
generated
vendored
Normal file
@@ -0,0 +1,478 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createSimplifyConstant = void 0;
|
||||
var _is = require("../../utils/is.js");
|
||||
var _factory = require("../../utils/factory.js");
|
||||
var _number = require("../../utils/number.js");
|
||||
var _util = require("./simplify/util.js");
|
||||
var _noop = require("../../utils/noop.js");
|
||||
const name = 'simplifyConstant';
|
||||
const dependencies = ['typed', 'config', 'mathWithTransform', 'matrix', '?fraction', '?bignumber', 'AccessorNode', 'ArrayNode', 'ConstantNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'SymbolNode'];
|
||||
const createSimplifyConstant = exports.createSimplifyConstant = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
typed,
|
||||
config,
|
||||
mathWithTransform,
|
||||
matrix,
|
||||
fraction,
|
||||
bignumber,
|
||||
AccessorNode,
|
||||
ArrayNode,
|
||||
ConstantNode,
|
||||
FunctionNode,
|
||||
IndexNode,
|
||||
ObjectNode,
|
||||
OperatorNode,
|
||||
SymbolNode
|
||||
} = _ref;
|
||||
const {
|
||||
isCommutative,
|
||||
isAssociative,
|
||||
allChildren,
|
||||
createMakeNodeFunction
|
||||
} = (0, _util.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
|
||||
*/
|
||||
const simplifyConstant = typed('simplifyConstant', {
|
||||
Node: node => _ensureNode(foldFraction(node, {})),
|
||||
'Node, Object': function (expr, options) {
|
||||
return _ensureNode(foldFraction(expr, options));
|
||||
}
|
||||
});
|
||||
function _removeFractions(thing) {
|
||||
if ((0, _is.isFraction)(thing)) {
|
||||
return thing.valueOf();
|
||||
}
|
||||
if (thing instanceof Array) {
|
||||
return thing.map(_removeFractions);
|
||||
}
|
||||
if ((0, _is.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);
|
||||
}
|
||||
}
|
||||
const _toNode = typed({
|
||||
Fraction: _fractionToNode,
|
||||
number: function (n) {
|
||||
if (n < 0) {
|
||||
return unaryMinusNode(new ConstantNode(-n));
|
||||
}
|
||||
return new ConstantNode(n);
|
||||
},
|
||||
BigNumber: function (n) {
|
||||
if (n < 0) {
|
||||
return unaryMinusNode(new ConstantNode(-n));
|
||||
}
|
||||
return new ConstantNode(n); // old parameters: (n.toString(), 'number')
|
||||
},
|
||||
bigint: function (n) {
|
||||
if (n < 0n) {
|
||||
return unaryMinusNode(new ConstantNode(-n));
|
||||
}
|
||||
return new ConstantNode(n);
|
||||
},
|
||||
Complex: function (s) {
|
||||
throw new Error('Cannot convert Complex number to Node');
|
||||
},
|
||||
string: function (s) {
|
||||
return new ConstantNode(s);
|
||||
},
|
||||
Matrix: function (m) {
|
||||
return new ArrayNode(m.valueOf().map(e => _toNode(e)));
|
||||
}
|
||||
});
|
||||
function _ensureNode(thing) {
|
||||
if ((0, _is.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) {
|
||||
const exactFractions = options && options.exactFractions !== false;
|
||||
if (exactFractions && isFinite(n) && fraction) {
|
||||
const f = fraction(n);
|
||||
const 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
|
||||
const _toNumber = typed({
|
||||
'string, Object': function (s, options) {
|
||||
const numericType = (0, _number.safeNumberType)(s, config);
|
||||
if (numericType === 'BigNumber') {
|
||||
if (bignumber === undefined) {
|
||||
(0, _noop.noBignumber)();
|
||||
}
|
||||
return bignumber(s);
|
||||
} else if (numericType === 'bigint') {
|
||||
return BigInt(s);
|
||||
} else if (numericType === 'Fraction') {
|
||||
if (fraction === undefined) {
|
||||
(0, _noop.noFraction)();
|
||||
}
|
||||
return fraction(s);
|
||||
} else {
|
||||
const n = parseFloat(s);
|
||||
return _exactFraction(n, options);
|
||||
}
|
||||
},
|
||||
'Fraction, Object': function (s, options) {
|
||||
return s;
|
||||
},
|
||||
// we don't need options here
|
||||
|
||||
'BigNumber, Object': function (s, options) {
|
||||
return s;
|
||||
},
|
||||
// we don't need options here
|
||||
|
||||
'number, Object': function (s, options) {
|
||||
return _exactFraction(s, options);
|
||||
},
|
||||
'bigint, Object': function (s, options) {
|
||||
return s;
|
||||
},
|
||||
'Complex, Object': function (s, options) {
|
||||
if (s.im !== 0) {
|
||||
return s;
|
||||
}
|
||||
return _exactFraction(s.re, options);
|
||||
},
|
||||
'Matrix, Object': function (s, options) {
|
||||
return matrix(_exactFraction(s.valueOf()));
|
||||
},
|
||||
'Array, Object': function (s, options) {
|
||||
return s.map(_exactFraction);
|
||||
}
|
||||
});
|
||||
function unaryMinusNode(n) {
|
||||
return new OperatorNode('-', 'unaryMinus', [n]);
|
||||
}
|
||||
function _fractionToNode(f) {
|
||||
let n;
|
||||
const 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 (!(0, _is.isIndexNode)(index)) {
|
||||
// don't know what to do with that...
|
||||
return new AccessorNode(_ensureNode(obj), _ensureNode(index));
|
||||
}
|
||||
if ((0, _is.isArrayNode)(obj) || (0, _is.isMatrix)(obj)) {
|
||||
const 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 ((0, _is.isConstantNode)(remainingDims[0]) && typeof remainingDims[0].value !== 'string') {
|
||||
const first = _toNumber(remainingDims.shift().value, options);
|
||||
if ((0, _is.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 && (0, _is.isConstantNode)(remainingDims[1]) && typeof remainingDims[1].value !== 'string') {
|
||||
const second = _toNumber(remainingDims[1].value, options);
|
||||
const tryItems = [];
|
||||
const fromItems = (0, _is.isArrayNode)(obj) ? obj.items : obj.valueOf();
|
||||
for (const item of fromItems) {
|
||||
if ((0, _is.isArrayNode)(item)) {
|
||||
tryItems.push(item.items[second - 1]);
|
||||
} else if ((0, _is.isMatrix)(obj)) {
|
||||
tryItems.push(item[second - 1]);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (tryItems.length === fromItems.length) {
|
||||
if ((0, _is.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 ((0, _is.isObjectNode)(obj) && index.dimensions.length === 1 && (0, _is.isConstantNode)(index.dimensions[0])) {
|
||||
const 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) {
|
||||
const first = args.shift();
|
||||
|
||||
// In the following reduction, sofar always has one of the three following
|
||||
// forms: [NODE], [CONSTANT], or [NODE, CONSTANT]
|
||||
const reduction = args.reduce((sofar, next) => {
|
||||
if (!(0, _is.isNode)(next)) {
|
||||
const last = sofar.pop();
|
||||
if ((0, _is.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()));
|
||||
const 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
|
||||
const operatorFunctions = ['add', 'multiply'];
|
||||
if (!operatorFunctions.includes(node.name)) {
|
||||
const args = node.args.map(arg => foldFraction(arg, options));
|
||||
|
||||
// If all args are numbers
|
||||
if (!args.some(_is.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 && (0, _is.isArrayNode)(args[0])) {
|
||||
const sz = [];
|
||||
let section = args[0];
|
||||
while ((0, _is.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':
|
||||
{
|
||||
const fn = node.fn.toString();
|
||||
let args;
|
||||
let res;
|
||||
const makeNode = createMakeNodeFunction(node);
|
||||
if ((0, _is.isOperatorNode)(node) && node.isUnary()) {
|
||||
args = [foldFraction(node.args[0], options)];
|
||||
if (!(0, _is.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
|
||||
const consts = [];
|
||||
const vars = [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (!(0, _is.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':
|
||||
{
|
||||
const foldItems = node.items.map(item => foldFraction(item, options));
|
||||
if (foldItems.some(_is.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':
|
||||
{
|
||||
const foldProps = {};
|
||||
for (const 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: ${node.type}`);
|
||||
}
|
||||
}
|
||||
return simplifyConstant;
|
||||
});
|
||||
297
node_modules/mathjs/lib/cjs/function/algebra/simplifyCore.js
generated
vendored
Normal file
297
node_modules/mathjs/lib/cjs/function/algebra/simplifyCore.js
generated
vendored
Normal file
@@ -0,0 +1,297 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createSimplifyCore = void 0;
|
||||
var _is = require("../../utils/is.js");
|
||||
var _operators = require("../../expression/operators.js");
|
||||
var _util = require("./simplify/util.js");
|
||||
var _factory = require("../../utils/factory.js");
|
||||
const name = 'simplifyCore';
|
||||
const dependencies = ['typed', 'parse', 'equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'AccessorNode', 'ArrayNode', 'ConstantNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
|
||||
const createSimplifyCore = exports.createSimplifyCore = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
typed,
|
||||
parse,
|
||||
equal,
|
||||
isZero,
|
||||
add,
|
||||
subtract,
|
||||
multiply,
|
||||
divide,
|
||||
pow,
|
||||
AccessorNode,
|
||||
ArrayNode,
|
||||
ConstantNode,
|
||||
FunctionNode,
|
||||
IndexNode,
|
||||
ObjectNode,
|
||||
OperatorNode,
|
||||
ParenthesisNode,
|
||||
SymbolNode
|
||||
} = _ref;
|
||||
const node0 = new ConstantNode(0);
|
||||
const node1 = new ConstantNode(1);
|
||||
const nodeT = new ConstantNode(true);
|
||||
const 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 (0, _is.isOperatorNode)(node) && ['and', 'not', 'or'].includes(node.op);
|
||||
}
|
||||
const {
|
||||
hasProperty,
|
||||
isCommutative
|
||||
} = (0, _util.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) {
|
||||
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
||||
const 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 ((0, _is.isFunctionNode)(nodeToSimplify) && nodeToSimplify.args.length === 1) {
|
||||
return _simplifyCore(nodeToSimplify.args[0], options);
|
||||
}
|
||||
// For other node types, we try the generic methods
|
||||
let simpChild = false;
|
||||
let childCount = 0;
|
||||
nodeToSimplify.forEach(c => {
|
||||
++childCount;
|
||||
if (childCount === 1) {
|
||||
simpChild = _simplifyCore(c, options);
|
||||
}
|
||||
});
|
||||
if (childCount === 1) {
|
||||
return simpChild;
|
||||
}
|
||||
}
|
||||
let node = nodeToSimplify;
|
||||
if ((0, _is.isFunctionNode)(node)) {
|
||||
const op = (0, _operators.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) {
|
||||
const last = node.args.pop();
|
||||
const 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 ((0, _is.isOperatorNode)(node) && node.isUnary()) {
|
||||
const a0 = _simplifyCore(node.args[0], options);
|
||||
if (node.op === '~') {
|
||||
// bitwise not
|
||||
if ((0, _is.isOperatorNode)(a0) && a0.isUnary() && a0.op === '~') {
|
||||
return a0.args[0];
|
||||
}
|
||||
}
|
||||
if (node.op === 'not') {
|
||||
// logical not
|
||||
if ((0, _is.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];
|
||||
}
|
||||
}
|
||||
}
|
||||
let finish = true;
|
||||
if (node.op === '-') {
|
||||
// unary minus
|
||||
if ((0, _is.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 ((0, _is.isOperatorNode)(node) && node.isBinary()) {
|
||||
const a0 = _simplifyCore(node.args[0], options);
|
||||
let a1 = _simplifyCore(node.args[1], options);
|
||||
if (node.op === '+') {
|
||||
if ((0, _is.isConstantNode)(a0) && isZero(a0.value)) {
|
||||
return a1;
|
||||
}
|
||||
if ((0, _is.isConstantNode)(a1) && isZero(a1.value)) {
|
||||
return a0;
|
||||
}
|
||||
if ((0, _is.isOperatorNode)(a1) && a1.isUnary() && a1.op === '-') {
|
||||
a1 = a1.args[0];
|
||||
node = new OperatorNode('-', 'subtract', [a0, a1]);
|
||||
}
|
||||
}
|
||||
if (node.op === '-') {
|
||||
if ((0, _is.isOperatorNode)(a1) && a1.isUnary() && a1.op === '-') {
|
||||
return _simplifyCore(new OperatorNode('+', 'add', [a0, a1.args[0]]), options);
|
||||
}
|
||||
if ((0, _is.isConstantNode)(a0) && isZero(a0.value)) {
|
||||
return _simplifyCore(new OperatorNode('-', 'unaryMinus', [a1]));
|
||||
}
|
||||
if ((0, _is.isConstantNode)(a1) && isZero(a1.value)) {
|
||||
return a0;
|
||||
}
|
||||
return new OperatorNode(node.op, node.fn, [a0, a1]);
|
||||
}
|
||||
if (node.op === '*') {
|
||||
if ((0, _is.isConstantNode)(a0)) {
|
||||
if (isZero(a0.value)) {
|
||||
return node0;
|
||||
} else if (equal(a0.value, 1)) {
|
||||
return a1;
|
||||
}
|
||||
}
|
||||
if ((0, _is.isConstantNode)(a1)) {
|
||||
if (isZero(a1.value)) {
|
||||
return node0;
|
||||
} else if (equal(a1.value, 1)) {
|
||||
return a0;
|
||||
}
|
||||
if (isCommutative(node, context)) {
|
||||
return new OperatorNode(node.op, node.fn, [a1, a0], node.implicit); // constants on left
|
||||
}
|
||||
}
|
||||
return new OperatorNode(node.op, node.fn, [a0, a1], node.implicit);
|
||||
}
|
||||
if (node.op === '/') {
|
||||
if ((0, _is.isConstantNode)(a0) && isZero(a0.value)) {
|
||||
return node0;
|
||||
}
|
||||
if ((0, _is.isConstantNode)(a1) && equal(a1.value, 1)) {
|
||||
return a0;
|
||||
}
|
||||
return new OperatorNode(node.op, node.fn, [a0, a1]);
|
||||
}
|
||||
if (node.op === '^') {
|
||||
if ((0, _is.isConstantNode)(a1)) {
|
||||
if (isZero(a1.value)) {
|
||||
return node1;
|
||||
} else if (equal(a1.value, 1)) {
|
||||
return a0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (node.op === 'and') {
|
||||
if ((0, _is.isConstantNode)(a0)) {
|
||||
if (a0.value) {
|
||||
if (isAlwaysBoolean(a1)) return a1;
|
||||
if ((0, _is.isConstantNode)(a1)) {
|
||||
return a1.value ? nodeT : nodeF;
|
||||
}
|
||||
} else {
|
||||
return nodeF;
|
||||
}
|
||||
}
|
||||
if ((0, _is.isConstantNode)(a1)) {
|
||||
if (a1.value) {
|
||||
if (isAlwaysBoolean(a0)) return a0;
|
||||
} else {
|
||||
return nodeF;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (node.op === 'or') {
|
||||
if ((0, _is.isConstantNode)(a0)) {
|
||||
if (a0.value) {
|
||||
return nodeT;
|
||||
} else {
|
||||
if (isAlwaysBoolean(a1)) return a1;
|
||||
}
|
||||
}
|
||||
if ((0, _is.isConstantNode)(a1)) {
|
||||
if (a1.value) {
|
||||
return nodeT;
|
||||
} else {
|
||||
if (isAlwaysBoolean(a0)) return a0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new OperatorNode(node.op, node.fn, [a0, a1]);
|
||||
}
|
||||
if ((0, _is.isOperatorNode)(node)) {
|
||||
return new OperatorNode(node.op, node.fn, node.args.map(a => _simplifyCore(a, options)));
|
||||
}
|
||||
if ((0, _is.isArrayNode)(node)) {
|
||||
return new ArrayNode(node.items.map(n => _simplifyCore(n, options)));
|
||||
}
|
||||
if ((0, _is.isAccessorNode)(node)) {
|
||||
return new AccessorNode(_simplifyCore(node.object, options), _simplifyCore(node.index, options));
|
||||
}
|
||||
if ((0, _is.isIndexNode)(node)) {
|
||||
return new IndexNode(node.dimensions.map(n => _simplifyCore(n, options)));
|
||||
}
|
||||
if ((0, _is.isObjectNode)(node)) {
|
||||
const newProps = {};
|
||||
for (const 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
|
||||
});
|
||||
});
|
||||
163
node_modules/mathjs/lib/cjs/function/algebra/solver/lsolve.js
generated
vendored
Normal file
163
node_modules/mathjs/lib/cjs/function/algebra/solver/lsolve.js
generated
vendored
Normal file
@@ -0,0 +1,163 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createLsolve = void 0;
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _solveValidation = require("./utils/solveValidation.js");
|
||||
const name = 'lsolve';
|
||||
const dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
|
||||
const createLsolve = exports.createLsolve = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
typed,
|
||||
matrix,
|
||||
divideScalar,
|
||||
multiplyScalar,
|
||||
subtractScalar,
|
||||
equalScalar,
|
||||
DenseMatrix
|
||||
} = _ref;
|
||||
const solveValidation = (0, _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 (m, b) {
|
||||
return _sparseForwardSubstitution(m, b);
|
||||
},
|
||||
'DenseMatrix, Array | Matrix': function (m, b) {
|
||||
return _denseForwardSubstitution(m, b);
|
||||
},
|
||||
'Array, Array | Matrix': function (a, b) {
|
||||
const m = matrix(a);
|
||||
const 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);
|
||||
const bdata = b._data;
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
|
||||
// result
|
||||
const x = [];
|
||||
const mdata = m._data;
|
||||
|
||||
// loop columns
|
||||
for (let j = 0; j < columns; j++) {
|
||||
const bj = bdata[j][0] || 0;
|
||||
let xj;
|
||||
if (!equalScalar(bj, 0)) {
|
||||
// non-degenerate row, find solution
|
||||
|
||||
const 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 (let 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);
|
||||
const bdata = b._data;
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
const values = m._values;
|
||||
const index = m._index;
|
||||
const ptr = m._ptr;
|
||||
|
||||
// result
|
||||
const x = [];
|
||||
|
||||
// loop columns
|
||||
for (let j = 0; j < columns; j++) {
|
||||
const bj = bdata[j][0] || 0;
|
||||
if (!equalScalar(bj, 0)) {
|
||||
// non-degenerate row, find solution
|
||||
|
||||
let vjj = 0;
|
||||
// matrix values & indices (column j)
|
||||
const jValues = [];
|
||||
const jIndices = [];
|
||||
|
||||
// first and last index in the column
|
||||
const firstIndex = ptr[j];
|
||||
const lastIndex = ptr[j + 1];
|
||||
|
||||
// values in column, find value at [j, j]
|
||||
for (let k = firstIndex; k < lastIndex; k++) {
|
||||
const 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');
|
||||
}
|
||||
const xj = divideScalar(bj, vjj);
|
||||
for (let k = 0, l = jIndices.length; k < l; k++) {
|
||||
const 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]
|
||||
});
|
||||
}
|
||||
});
|
||||
192
node_modules/mathjs/lib/cjs/function/algebra/solver/lsolveAll.js
generated
vendored
Normal file
192
node_modules/mathjs/lib/cjs/function/algebra/solver/lsolveAll.js
generated
vendored
Normal file
@@ -0,0 +1,192 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createLsolveAll = void 0;
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _solveValidation = require("./utils/solveValidation.js");
|
||||
const name = 'lsolveAll';
|
||||
const dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
|
||||
const createLsolveAll = exports.createLsolveAll = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
typed,
|
||||
matrix,
|
||||
divideScalar,
|
||||
multiplyScalar,
|
||||
subtractScalar,
|
||||
equalScalar,
|
||||
DenseMatrix
|
||||
} = _ref;
|
||||
const solveValidation = (0, _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 (m, b) {
|
||||
return _sparseForwardSubstitution(m, b);
|
||||
},
|
||||
'DenseMatrix, Array | Matrix': function (m, b) {
|
||||
return _denseForwardSubstitution(m, b);
|
||||
},
|
||||
'Array, Array | Matrix': function (a, b) {
|
||||
const m = matrix(a);
|
||||
const 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
|
||||
const B = [solveValidation(m, b_, true)._data.map(e => e[0])];
|
||||
const M = m._data;
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
|
||||
// loop columns
|
||||
for (let i = 0; i < columns; i++) {
|
||||
let L = B.length;
|
||||
|
||||
// loop right-hand sides
|
||||
for (let k = 0; k < L; k++) {
|
||||
const b = B[k];
|
||||
if (!equalScalar(M[i][i], 0)) {
|
||||
// non-singular row
|
||||
|
||||
b[i] = divideScalar(b[i], M[i][i]);
|
||||
for (let 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
|
||||
|
||||
const bNew = [...b];
|
||||
bNew[i] = 1;
|
||||
for (let 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
|
||||
const B = [solveValidation(m, b_, true)._data.map(e => e[0])];
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
const values = m._values;
|
||||
const index = m._index;
|
||||
const ptr = m._ptr;
|
||||
|
||||
// loop columns
|
||||
for (let i = 0; i < columns; i++) {
|
||||
let L = B.length;
|
||||
|
||||
// loop right-hand sides
|
||||
for (let k = 0; k < L; k++) {
|
||||
const b = B[k];
|
||||
|
||||
// values & indices (column i)
|
||||
const iValues = [];
|
||||
const iIndices = [];
|
||||
|
||||
// first & last indeces in column
|
||||
const firstIndex = ptr[i];
|
||||
const lastIndex = ptr[i + 1];
|
||||
|
||||
// find the value at [i, i]
|
||||
let Mii = 0;
|
||||
for (let j = firstIndex; j < lastIndex; j++) {
|
||||
const 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 (let j = 0, lastIndex = iIndices.length; j < lastIndex; j++) {
|
||||
const J = iIndices[j];
|
||||
b[J] = subtractScalar(b[J], multiplyScalar(b[i], iValues[j]));
|
||||
}
|
||||
} 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
|
||||
|
||||
const bNew = [...b];
|
||||
bNew[i] = 1;
|
||||
for (let j = 0, lastIndex = iIndices.length; j < lastIndex; j++) {
|
||||
const J = iIndices[j];
|
||||
bNew[J] = subtractScalar(bNew[J], iValues[j]);
|
||||
}
|
||||
B.push(bNew);
|
||||
}
|
||||
}
|
||||
}
|
||||
return B.map(x => new DenseMatrix({
|
||||
data: x.map(e => [e]),
|
||||
size: [rows, 1]
|
||||
}));
|
||||
}
|
||||
});
|
||||
114
node_modules/mathjs/lib/cjs/function/algebra/solver/lusolve.js
generated
vendored
Normal file
114
node_modules/mathjs/lib/cjs/function/algebra/solver/lusolve.js
generated
vendored
Normal file
@@ -0,0 +1,114 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createLusolve = void 0;
|
||||
var _is = require("../../../utils/is.js");
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _solveValidation = require("./utils/solveValidation.js");
|
||||
var _csIpvec = require("../sparse/csIpvec.js");
|
||||
const name = 'lusolve';
|
||||
const dependencies = ['typed', 'matrix', 'lup', 'slu', 'usolve', 'lsolve', 'DenseMatrix'];
|
||||
const createLusolve = exports.createLusolve = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
typed,
|
||||
matrix,
|
||||
lup,
|
||||
slu,
|
||||
usolve,
|
||||
lsolve,
|
||||
DenseMatrix
|
||||
} = _ref;
|
||||
const solveValidation = (0, _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 (a, b) {
|
||||
a = matrix(a);
|
||||
const d = lup(a);
|
||||
const x = _lusolve(d.L, d.U, d.p, null, b);
|
||||
return x.valueOf();
|
||||
},
|
||||
'DenseMatrix, Array | Matrix': function (a, b) {
|
||||
const d = lup(a);
|
||||
return _lusolve(d.L, d.U, d.p, null, b);
|
||||
},
|
||||
'SparseMatrix, Array | Matrix': function (a, b) {
|
||||
const d = lup(a);
|
||||
return _lusolve(d.L, d.U, d.p, null, b);
|
||||
},
|
||||
'SparseMatrix, Array | Matrix, number, number': function (a, b, order, threshold) {
|
||||
const d = slu(a, order, threshold);
|
||||
return _lusolve(d.L, d.U, d.p, d.q, b);
|
||||
},
|
||||
'Object, Array | Matrix': function (d, b) {
|
||||
return _lusolve(d.L, d.U, d.p, d.q, b);
|
||||
}
|
||||
});
|
||||
function _toMatrix(a) {
|
||||
if ((0, _is.isMatrix)(a)) {
|
||||
return a;
|
||||
}
|
||||
if ((0, _is.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 = (0, _csIpvec.csIpvec)(p, b._data);
|
||||
}
|
||||
|
||||
// use forward substitution to resolve L * y = b
|
||||
const y = lsolve(l, b);
|
||||
// use backward substitution to resolve U * x = y
|
||||
const x = usolve(u, y);
|
||||
|
||||
// apply column permutations if needed (x is a DenseMatrix)
|
||||
if (q) {
|
||||
x._data = (0, _csIpvec.csIpvec)(q, x._data);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
});
|
||||
167
node_modules/mathjs/lib/cjs/function/algebra/solver/usolve.js
generated
vendored
Normal file
167
node_modules/mathjs/lib/cjs/function/algebra/solver/usolve.js
generated
vendored
Normal file
@@ -0,0 +1,167 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createUsolve = void 0;
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _solveValidation = require("./utils/solveValidation.js");
|
||||
const name = 'usolve';
|
||||
const dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
|
||||
const createUsolve = exports.createUsolve = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
typed,
|
||||
matrix,
|
||||
divideScalar,
|
||||
multiplyScalar,
|
||||
subtractScalar,
|
||||
equalScalar,
|
||||
DenseMatrix
|
||||
} = _ref;
|
||||
const solveValidation = (0, _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 (m, b) {
|
||||
return _sparseBackwardSubstitution(m, b);
|
||||
},
|
||||
'DenseMatrix, Array | Matrix': function (m, b) {
|
||||
return _denseBackwardSubstitution(m, b);
|
||||
},
|
||||
'Array, Array | Matrix': function (a, b) {
|
||||
const m = matrix(a);
|
||||
const r = _denseBackwardSubstitution(m, b);
|
||||
return r.valueOf();
|
||||
}
|
||||
});
|
||||
function _denseBackwardSubstitution(m, b) {
|
||||
// make b into a column vector
|
||||
b = solveValidation(m, b, true);
|
||||
const bdata = b._data;
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
|
||||
// result
|
||||
const x = [];
|
||||
const mdata = m._data;
|
||||
// loop columns backwards
|
||||
for (let j = columns - 1; j >= 0; j--) {
|
||||
// b[j]
|
||||
const bj = bdata[j][0] || 0;
|
||||
// x[j]
|
||||
let xj;
|
||||
if (!equalScalar(bj, 0)) {
|
||||
// value at [j, j]
|
||||
const 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 (let 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);
|
||||
const bdata = b._data;
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
const values = m._values;
|
||||
const index = m._index;
|
||||
const ptr = m._ptr;
|
||||
|
||||
// result
|
||||
const x = [];
|
||||
|
||||
// loop columns backwards
|
||||
for (let j = columns - 1; j >= 0; j--) {
|
||||
const bj = bdata[j][0] || 0;
|
||||
if (!equalScalar(bj, 0)) {
|
||||
// non-degenerate row, find solution
|
||||
|
||||
let vjj = 0;
|
||||
|
||||
// upper triangular matrix values & index (column j)
|
||||
const jValues = [];
|
||||
const jIndices = [];
|
||||
|
||||
// first & last indeces in column
|
||||
const firstIndex = ptr[j];
|
||||
const lastIndex = ptr[j + 1];
|
||||
|
||||
// values in column, find value at [j, j], loop backwards
|
||||
for (let k = lastIndex - 1; k >= firstIndex; k--) {
|
||||
const 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');
|
||||
}
|
||||
const xj = divideScalar(bj, vjj);
|
||||
for (let k = 0, lastIndex = jIndices.length; k < lastIndex; k++) {
|
||||
const 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]
|
||||
});
|
||||
}
|
||||
});
|
||||
196
node_modules/mathjs/lib/cjs/function/algebra/solver/usolveAll.js
generated
vendored
Normal file
196
node_modules/mathjs/lib/cjs/function/algebra/solver/usolveAll.js
generated
vendored
Normal file
@@ -0,0 +1,196 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createUsolveAll = void 0;
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _solveValidation = require("./utils/solveValidation.js");
|
||||
const name = 'usolveAll';
|
||||
const dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
|
||||
const createUsolveAll = exports.createUsolveAll = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
typed,
|
||||
matrix,
|
||||
divideScalar,
|
||||
multiplyScalar,
|
||||
subtractScalar,
|
||||
equalScalar,
|
||||
DenseMatrix
|
||||
} = _ref;
|
||||
const solveValidation = (0, _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 (m, b) {
|
||||
return _sparseBackwardSubstitution(m, b);
|
||||
},
|
||||
'DenseMatrix, Array | Matrix': function (m, b) {
|
||||
return _denseBackwardSubstitution(m, b);
|
||||
},
|
||||
'Array, Array | Matrix': function (a, b) {
|
||||
const m = matrix(a);
|
||||
const 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
|
||||
const B = [solveValidation(m, b_, true)._data.map(e => e[0])];
|
||||
const M = m._data;
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
|
||||
// loop columns backwards
|
||||
for (let i = columns - 1; i >= 0; i--) {
|
||||
let L = B.length;
|
||||
|
||||
// loop right-hand sides
|
||||
for (let k = 0; k < L; k++) {
|
||||
const b = B[k];
|
||||
if (!equalScalar(M[i][i], 0)) {
|
||||
// non-singular row
|
||||
|
||||
b[i] = divideScalar(b[i], M[i][i]);
|
||||
for (let 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
|
||||
|
||||
const bNew = [...b];
|
||||
bNew[i] = 1;
|
||||
for (let 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
|
||||
const B = [solveValidation(m, b_, true)._data.map(e => e[0])];
|
||||
const rows = m._size[0];
|
||||
const columns = m._size[1];
|
||||
const values = m._values;
|
||||
const index = m._index;
|
||||
const ptr = m._ptr;
|
||||
|
||||
// loop columns backwards
|
||||
for (let i = columns - 1; i >= 0; i--) {
|
||||
let L = B.length;
|
||||
|
||||
// loop right-hand sides
|
||||
for (let k = 0; k < L; k++) {
|
||||
const b = B[k];
|
||||
|
||||
// values & indices (column i)
|
||||
const iValues = [];
|
||||
const iIndices = [];
|
||||
|
||||
// first & last indeces in column
|
||||
const firstIndex = ptr[i];
|
||||
const lastIndex = ptr[i + 1];
|
||||
|
||||
// find the value at [i, i]
|
||||
let Mii = 0;
|
||||
for (let j = lastIndex - 1; j >= firstIndex; j--) {
|
||||
const 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 (let j = 0, lastIndex = iIndices.length; j < lastIndex; j++) {
|
||||
const J = iIndices[j];
|
||||
b[J] = subtractScalar(b[J], multiplyScalar(b[i], iValues[j]));
|
||||
}
|
||||
} 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
|
||||
|
||||
const bNew = [...b];
|
||||
bNew[i] = 1;
|
||||
|
||||
// loop upper triangular
|
||||
for (let j = 0, lastIndex = iIndices.length; j < lastIndex; j++) {
|
||||
const J = iIndices[j];
|
||||
bNew[J] = subtractScalar(bNew[J], iValues[j]);
|
||||
}
|
||||
B.push(bNew);
|
||||
}
|
||||
}
|
||||
}
|
||||
return B.map(x => new DenseMatrix({
|
||||
data: x.map(e => [e]),
|
||||
size: [rows, 1]
|
||||
}));
|
||||
}
|
||||
});
|
||||
121
node_modules/mathjs/lib/cjs/function/algebra/solver/utils/solveValidation.js
generated
vendored
Normal file
121
node_modules/mathjs/lib/cjs/function/algebra/solver/utils/solveValidation.js
generated
vendored
Normal file
@@ -0,0 +1,121 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createSolveValidation = createSolveValidation;
|
||||
var _is = require("../../../../utils/is.js");
|
||||
var _array = require("../../../../utils/array.js");
|
||||
var _string = require("../../../../utils/string.js");
|
||||
function createSolveValidation(_ref) {
|
||||
let {
|
||||
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) {
|
||||
const mSize = m.size();
|
||||
if (mSize.length !== 2) {
|
||||
throw new RangeError('Matrix must be two dimensional (size: ' + (0, _string.format)(mSize) + ')');
|
||||
}
|
||||
const rows = mSize[0];
|
||||
const columns = mSize[1];
|
||||
if (rows !== columns) {
|
||||
throw new RangeError('Matrix must be square (size: ' + (0, _string.format)(mSize) + ')');
|
||||
}
|
||||
let data = [];
|
||||
if ((0, _is.isMatrix)(b)) {
|
||||
const bSize = b.size();
|
||||
const 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 (let 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 ((0, _is.isDenseMatrix)(b)) {
|
||||
if (copy) {
|
||||
data = [];
|
||||
for (let i = 0; i < rows; i++) {
|
||||
data[i] = [bdata[i][0]];
|
||||
}
|
||||
return new DenseMatrix({
|
||||
data,
|
||||
size: [rows, 1],
|
||||
datatype: b._datatype
|
||||
});
|
||||
}
|
||||
return b;
|
||||
}
|
||||
if ((0, _is.isSparseMatrix)(b)) {
|
||||
for (let i = 0; i < rows; i++) {
|
||||
data[i] = [0];
|
||||
}
|
||||
const values = b._values;
|
||||
const index = b._index;
|
||||
const ptr = b._ptr;
|
||||
for (let k1 = ptr[1], k = ptr[0]; k < k1; k++) {
|
||||
const i = index[k];
|
||||
data[i][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 ((0, _is.isArray)(b)) {
|
||||
const bsize = (0, _array.arraySize)(b);
|
||||
if (bsize.length === 1) {
|
||||
if (bsize[0] !== rows) {
|
||||
throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
|
||||
}
|
||||
for (let i = 0; i < rows; i++) {
|
||||
data[i] = [b[i]];
|
||||
}
|
||||
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 (let i = 0; i < rows; i++) {
|
||||
data[i] = [b[i][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.');
|
||||
}
|
||||
};
|
||||
}
|
||||
587
node_modules/mathjs/lib/cjs/function/algebra/sparse/csAmd.js
generated
vendored
Normal file
587
node_modules/mathjs/lib/cjs/function/algebra/sparse/csAmd.js
generated
vendored
Normal file
@@ -0,0 +1,587 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createCsAmd = void 0;
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _csFkeep = require("./csFkeep.js");
|
||||
var _csFlip = require("./csFlip.js");
|
||||
var _csTdfs = require("./csTdfs.js");
|
||||
// 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
|
||||
|
||||
const name = 'csAmd';
|
||||
const dependencies = ['add', 'multiply', 'transpose'];
|
||||
const createCsAmd = exports.createCsAmd = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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
|
||||
const asize = a._size;
|
||||
// rows and columns
|
||||
const m = asize[0];
|
||||
const n = asize[1];
|
||||
// initialize vars
|
||||
let lemax = 0;
|
||||
// dense threshold
|
||||
let dense = Math.max(16, 10 * Math.sqrt(n));
|
||||
dense = Math.min(n - 2, dense);
|
||||
// create target matrix C
|
||||
const cm = _createTargetMatrix(order, a, m, n, dense);
|
||||
// drop diagonal entries
|
||||
(0, _csFkeep.csFkeep)(cm, _diag, null);
|
||||
// C matrix arrays
|
||||
const cindex = cm._index;
|
||||
const cptr = cm._ptr;
|
||||
|
||||
// number of nonzero elements in C
|
||||
let cnz = cptr[n];
|
||||
|
||||
// allocate result (n+1)
|
||||
const P = [];
|
||||
|
||||
// create workspace (8 * (n + 1))
|
||||
const W = [];
|
||||
const len = 0; // first n + 1 entries
|
||||
const nv = n + 1; // next n + 1 entries
|
||||
const next = 2 * (n + 1); // next n + 1 entries
|
||||
const head = 3 * (n + 1); // next n + 1 entries
|
||||
const elen = 4 * (n + 1); // next n + 1 entries
|
||||
const degree = 5 * (n + 1); // next n + 1 entries
|
||||
const w = 6 * (n + 1); // next n + 1 entries
|
||||
const hhead = 7 * (n + 1); // last n + 1 entries
|
||||
|
||||
// use P as workspace for last
|
||||
const last = P;
|
||||
|
||||
// initialize quotient graph
|
||||
let mark = _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree);
|
||||
|
||||
// initialize degree lists
|
||||
let nel = _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next);
|
||||
|
||||
// minimum degree node
|
||||
let mindeg = 0;
|
||||
|
||||
// vars
|
||||
let 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|
|
||||
const elenk = W[elen + k];
|
||||
// # of nodes k represents
|
||||
let 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.
|
||||
let dk = 0;
|
||||
// flag k as in Lk
|
||||
W[nv + k] = -nvk;
|
||||
let p = cptr[k];
|
||||
// do in place if W[elen + k] === 0
|
||||
const pk1 = elenk === 0 ? p : cnz;
|
||||
let 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] = (0, _csFlip.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];
|
||||
const 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|
|
||||
const 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] = (0, _csFlip.csFlip)(k);
|
||||
// e is a dead element
|
||||
W[w + e] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
// W[elen + i] = |Ei|
|
||||
W[elen + i] = pn - p1 + 1;
|
||||
const p3 = pn;
|
||||
const 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
|
||||
const 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] = (0, _csFlip.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;
|
||||
}
|
||||
let jlast = i;
|
||||
// compare i with all j
|
||||
for (j = W[next + i]; j !== -1;) {
|
||||
let 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] = (0, _csFlip.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] = (0, _csFlip.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 = (0, _csTdfs.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'
|
||||
const 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
|
||||
const tindex = at._index;
|
||||
const tptr = at._ptr;
|
||||
// new column index
|
||||
let p2 = 0;
|
||||
// loop A' columns (rows)
|
||||
for (let j = 0; j < m; j++) {
|
||||
// column j of AT starts here
|
||||
let 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 (const 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 (let k = 0; k < n; k++) {
|
||||
W[len + k] = cptr[k + 1] - cptr[k];
|
||||
}
|
||||
W[len + n] = 0;
|
||||
// initialize workspace
|
||||
for (let 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
|
||||
const 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
|
||||
let nel = 0;
|
||||
// loop columns
|
||||
for (let i = 0; i < n; i++) {
|
||||
// degree @ i
|
||||
const 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] = (0, _csFlip.csFlip)(n);
|
||||
W[nv + n]++;
|
||||
} else {
|
||||
const 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 (let 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;
|
||||
}
|
||||
});
|
||||
164
node_modules/mathjs/lib/cjs/function/algebra/sparse/csChol.js
generated
vendored
Normal file
164
node_modules/mathjs/lib/cjs/function/algebra/sparse/csChol.js
generated
vendored
Normal file
@@ -0,0 +1,164 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createCsChol = void 0;
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _csEreach = require("./csEreach.js");
|
||||
var _csSymperm = require("./csSymperm.js");
|
||||
// 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
|
||||
|
||||
const name = 'csChol';
|
||||
const dependencies = ['divideScalar', 'sqrt', 'subtract', 'multiply', 'im', 're', 'conj', 'equal', 'smallerEq', 'SparseMatrix'];
|
||||
const createCsChol = exports.createCsChol = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
divideScalar,
|
||||
sqrt,
|
||||
subtract,
|
||||
multiply,
|
||||
im,
|
||||
re,
|
||||
conj,
|
||||
equal,
|
||||
smallerEq,
|
||||
SparseMatrix
|
||||
} = _ref;
|
||||
const csSymperm = (0, _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
|
||||
const size = m._size;
|
||||
// columns
|
||||
const n = size[1];
|
||||
// symbolic analysis result
|
||||
const parent = s.parent;
|
||||
const cp = s.cp;
|
||||
const pinv = s.pinv;
|
||||
// L arrays
|
||||
const lvalues = [];
|
||||
const lindex = [];
|
||||
const lptr = [];
|
||||
// L
|
||||
const L = new SparseMatrix({
|
||||
values: lvalues,
|
||||
index: lindex,
|
||||
ptr: lptr,
|
||||
size: [n, n]
|
||||
});
|
||||
// vars
|
||||
const c = []; // (2 * n)
|
||||
const x = []; // (n)
|
||||
// compute C = P * A * P'
|
||||
const cm = pinv ? csSymperm(m, pinv, 1) : m;
|
||||
// C matrix arrays
|
||||
const cvalues = cm._values;
|
||||
const cindex = cm._index;
|
||||
const cptr = cm._ptr;
|
||||
// vars
|
||||
let 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,:)
|
||||
let top = (0, _csEreach.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)
|
||||
let 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,:)
|
||||
const i = s[top];
|
||||
// L(k,i) = x (i) / L(i,i)
|
||||
const 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
|
||||
const 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
|
||||
let P;
|
||||
// check we need to calculate P
|
||||
if (pinv) {
|
||||
// P arrays
|
||||
const pvalues = [];
|
||||
const pindex = [];
|
||||
const 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
|
||||
};
|
||||
};
|
||||
});
|
||||
133
node_modules/mathjs/lib/cjs/function/algebra/sparse/csCounts.js
generated
vendored
Normal file
133
node_modules/mathjs/lib/cjs/function/algebra/sparse/csCounts.js
generated
vendored
Normal file
@@ -0,0 +1,133 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createCsCounts = void 0;
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _csLeaf = require("./csLeaf.js");
|
||||
// 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
|
||||
|
||||
const name = 'csCounts';
|
||||
const dependencies = ['transpose'];
|
||||
const createCsCounts = exports.createCsCounts = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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
|
||||
const asize = a._size;
|
||||
// rows and columns
|
||||
const m = asize[0];
|
||||
const n = asize[1];
|
||||
// variables
|
||||
let i, j, k, J, p, p0, p1;
|
||||
|
||||
// workspace size
|
||||
const s = 4 * n + (ata ? n + m + 1 : 0);
|
||||
// allocate workspace
|
||||
const w = []; // (s)
|
||||
const ancestor = 0; // first n entries
|
||||
const maxfirst = n; // next n entries
|
||||
const prevleaf = 2 * n; // next n entries
|
||||
const first = 3 * n; // next n entries
|
||||
const head = 4 * n; // next n + 1 entries (used when ata is true)
|
||||
const 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
|
||||
const colcount = []; // (n)
|
||||
|
||||
// AT = A'
|
||||
const at = transpose(a);
|
||||
// at arrays
|
||||
const tindex = at._index;
|
||||
const 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];
|
||||
const r = (0, _csLeaf.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;
|
||||
};
|
||||
});
|
||||
34
node_modules/mathjs/lib/cjs/function/algebra/sparse/csCumsum.js
generated
vendored
Normal file
34
node_modules/mathjs/lib/cjs/function/algebra/sparse/csCumsum.js
generated
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csCumsum = csCumsum;
|
||||
// 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
|
||||
*/
|
||||
function csCumsum(ptr, c, n) {
|
||||
// variables
|
||||
let i;
|
||||
let 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;
|
||||
}
|
||||
82
node_modules/mathjs/lib/cjs/function/algebra/sparse/csDfs.js
generated
vendored
Normal file
82
node_modules/mathjs/lib/cjs/function/algebra/sparse/csDfs.js
generated
vendored
Normal file
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csDfs = csDfs;
|
||||
var _csMarked = require("./csMarked.js");
|
||||
var _csMark = require("./csMark.js");
|
||||
var _csUnflip = require("./csUnflip.js");
|
||||
// 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 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
|
||||
*/
|
||||
function csDfs(j, g, top, xi, pinv) {
|
||||
// g arrays
|
||||
const index = g._index;
|
||||
const ptr = g._ptr;
|
||||
const size = g._size;
|
||||
// columns
|
||||
const n = size[1];
|
||||
// vars
|
||||
let i, p, p2;
|
||||
// initialize head
|
||||
let 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
|
||||
const jnew = pinv ? pinv[j] : j;
|
||||
// check node j is marked
|
||||
if (!(0, _csMarked.csMarked)(ptr, j)) {
|
||||
// mark node j as visited
|
||||
(0, _csMark.csMark)(ptr, j);
|
||||
// update stack (last n entries in xi)
|
||||
xi[n + head] = jnew < 0 ? 0 : (0, _csUnflip.csUnflip)(ptr[jnew]);
|
||||
}
|
||||
// node j done if no unvisited neighbors
|
||||
let done = 1;
|
||||
// examine all neighbors of j, stack (last n entries in xi)
|
||||
for (p = xi[n + head], p2 = jnew < 0 ? 0 : (0, _csUnflip.csUnflip)(ptr[jnew + 1]); p < p2; p++) {
|
||||
// consider neighbor node i
|
||||
i = index[p];
|
||||
// check we have visited node i, skip it
|
||||
if ((0, _csMarked.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;
|
||||
}
|
||||
69
node_modules/mathjs/lib/cjs/function/algebra/sparse/csEreach.js
generated
vendored
Normal file
69
node_modules/mathjs/lib/cjs/function/algebra/sparse/csEreach.js
generated
vendored
Normal file
@@ -0,0 +1,69 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csEreach = csEreach;
|
||||
var _csMark = require("./csMark.js");
|
||||
var _csMarked = require("./csMarked.js");
|
||||
// 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
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function csEreach(a, k, parent, w) {
|
||||
// a arrays
|
||||
const aindex = a._index;
|
||||
const aptr = a._ptr;
|
||||
const asize = a._size;
|
||||
// columns
|
||||
const n = asize[1];
|
||||
// initialize top
|
||||
let top = n;
|
||||
// vars
|
||||
let p, p0, p1, len;
|
||||
// mark node k as visited
|
||||
(0, _csMark.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
|
||||
let i = aindex[p];
|
||||
// only use upper triangular part of A
|
||||
if (i > k) {
|
||||
continue;
|
||||
}
|
||||
// traverse up etree
|
||||
for (len = 0; !(0, _csMarked.csMarked)(w, i); i = parent[i]) {
|
||||
// L(k,i) is nonzero, last n entries in w
|
||||
w[n + len++] = i;
|
||||
// mark i as visited
|
||||
(0, _csMark.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
|
||||
(0, _csMark.csMark)(w, w[n + p]);
|
||||
}
|
||||
// unmark node k
|
||||
(0, _csMark.csMark)(w, k);
|
||||
// s[top..n-1] contains pattern of L(k,:)
|
||||
return top;
|
||||
}
|
||||
77
node_modules/mathjs/lib/cjs/function/algebra/sparse/csEtree.js
generated
vendored
Normal file
77
node_modules/mathjs/lib/cjs/function/algebra/sparse/csEtree.js
generated
vendored
Normal file
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csEtree = csEtree;
|
||||
// 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
|
||||
*/
|
||||
function csEtree(a, ata) {
|
||||
// check inputs
|
||||
if (!a) {
|
||||
return null;
|
||||
}
|
||||
// a arrays
|
||||
const aindex = a._index;
|
||||
const aptr = a._ptr;
|
||||
const asize = a._size;
|
||||
// rows & columns
|
||||
const m = asize[0];
|
||||
const n = asize[1];
|
||||
|
||||
// allocate result
|
||||
const parent = []; // (n)
|
||||
|
||||
// allocate workspace
|
||||
const w = []; // (n + (ata ? m : 0))
|
||||
const ancestor = 0; // first n entries in w
|
||||
const prev = n; // last m entries (ata = true)
|
||||
|
||||
let 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 (let 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 (let p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
|
||||
// row
|
||||
const 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;
|
||||
}
|
||||
64
node_modules/mathjs/lib/cjs/function/algebra/sparse/csFkeep.js
generated
vendored
Normal file
64
node_modules/mathjs/lib/cjs/function/algebra/sparse/csFkeep.js
generated
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csFkeep = csFkeep;
|
||||
// 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
|
||||
*/
|
||||
function csFkeep(a, callback, other) {
|
||||
// a arrays
|
||||
const avalues = a._values;
|
||||
const aindex = a._index;
|
||||
const aptr = a._ptr;
|
||||
const asize = a._size;
|
||||
// columns
|
||||
const n = asize[1];
|
||||
// nonzero items
|
||||
let nz = 0;
|
||||
// loop columns
|
||||
for (let j = 0; j < n; j++) {
|
||||
// get current location of col j
|
||||
let 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;
|
||||
}
|
||||
19
node_modules/mathjs/lib/cjs/function/algebra/sparse/csFlip.js
generated
vendored
Normal file
19
node_modules/mathjs/lib/cjs/function/algebra/sparse/csFlip.js
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csFlip = csFlip;
|
||||
// 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
|
||||
*/
|
||||
function csFlip(i) {
|
||||
// flip the value
|
||||
return -i - 2;
|
||||
}
|
||||
39
node_modules/mathjs/lib/cjs/function/algebra/sparse/csIpvec.js
generated
vendored
Normal file
39
node_modules/mathjs/lib/cjs/function/algebra/sparse/csIpvec.js
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csIpvec = csIpvec;
|
||||
// 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
|
||||
*/
|
||||
function csIpvec(p, b) {
|
||||
// vars
|
||||
let k;
|
||||
const n = b.length;
|
||||
const 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;
|
||||
}
|
||||
62
node_modules/mathjs/lib/cjs/function/algebra/sparse/csLeaf.js
generated
vendored
Normal file
62
node_modules/mathjs/lib/cjs/function/algebra/sparse/csLeaf.js
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csLeaf = csLeaf;
|
||||
// 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}
|
||||
*/
|
||||
function csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor) {
|
||||
let s, sparent;
|
||||
|
||||
// our result
|
||||
let jleaf = 0;
|
||||
let 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
|
||||
const 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
|
||||
};
|
||||
}
|
||||
188
node_modules/mathjs/lib/cjs/function/algebra/sparse/csLu.js
generated
vendored
Normal file
188
node_modules/mathjs/lib/cjs/function/algebra/sparse/csLu.js
generated
vendored
Normal file
@@ -0,0 +1,188 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createCsLu = void 0;
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
var _csSpsolve = require("./csSpsolve.js");
|
||||
// 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
|
||||
|
||||
const name = 'csLu';
|
||||
const dependencies = ['abs', 'divideScalar', 'multiply', 'subtract', 'larger', 'largerEq', 'SparseMatrix'];
|
||||
const createCsLu = exports.createCsLu = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
abs,
|
||||
divideScalar,
|
||||
multiply,
|
||||
subtract,
|
||||
larger,
|
||||
largerEq,
|
||||
SparseMatrix
|
||||
} = _ref;
|
||||
const csSpsolve = (0, _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
|
||||
const size = m._size;
|
||||
// columns
|
||||
const n = size[1];
|
||||
// symbolic analysis result
|
||||
let q;
|
||||
let lnz = 100;
|
||||
let unz = 100;
|
||||
// update symbolic analysis parameters
|
||||
if (s) {
|
||||
q = s.q;
|
||||
lnz = s.lnz || lnz;
|
||||
unz = s.unz || unz;
|
||||
}
|
||||
// L arrays
|
||||
const lvalues = []; // (lnz)
|
||||
const lindex = []; // (lnz)
|
||||
const lptr = []; // (n + 1)
|
||||
// L
|
||||
const L = new SparseMatrix({
|
||||
values: lvalues,
|
||||
index: lindex,
|
||||
ptr: lptr,
|
||||
size: [n, n]
|
||||
});
|
||||
// U arrays
|
||||
const uvalues = []; // (unz)
|
||||
const uindex = []; // (unz)
|
||||
const uptr = []; // (n + 1)
|
||||
// U
|
||||
const U = new SparseMatrix({
|
||||
values: uvalues,
|
||||
index: uindex,
|
||||
ptr: uptr,
|
||||
size: [n, n]
|
||||
});
|
||||
// inverse of permutation vector
|
||||
const pinv = []; // (n)
|
||||
// vars
|
||||
let i, p;
|
||||
// allocate arrays
|
||||
const x = []; // (n)
|
||||
const 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 (let k = 0; k < n; k++) {
|
||||
// update ptr
|
||||
lptr[k] = lnz;
|
||||
uptr[k] = unz;
|
||||
// apply column permutations if needed
|
||||
const col = q ? q[k] : k;
|
||||
// solve triangular system, x = L\A(:,col)
|
||||
const top = csSpsolve(L, m, col, xi, x, pinv, 1);
|
||||
// find pivot
|
||||
let ipiv = -1;
|
||||
let 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]
|
||||
const 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
|
||||
const 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
|
||||
};
|
||||
};
|
||||
});
|
||||
21
node_modules/mathjs/lib/cjs/function/algebra/sparse/csMark.js
generated
vendored
Normal file
21
node_modules/mathjs/lib/cjs/function/algebra/sparse/csMark.js
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csMark = csMark;
|
||||
var _csFlip = require("./csFlip.js");
|
||||
// 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
|
||||
|
||||
/**
|
||||
* Marks the node at w[j]
|
||||
*
|
||||
* @param {Array} w The array
|
||||
* @param {Number} j The array index
|
||||
*/
|
||||
function csMark(w, j) {
|
||||
// mark w[j]
|
||||
w[j] = (0, _csFlip.csFlip)(w[j]);
|
||||
}
|
||||
20
node_modules/mathjs/lib/cjs/function/algebra/sparse/csMarked.js
generated
vendored
Normal file
20
node_modules/mathjs/lib/cjs/function/algebra/sparse/csMarked.js
generated
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csMarked = csMarked;
|
||||
// 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
|
||||
*/
|
||||
function csMarked(w, j) {
|
||||
// check node is marked
|
||||
return w[j] < 0;
|
||||
}
|
||||
67
node_modules/mathjs/lib/cjs/function/algebra/sparse/csPermute.js
generated
vendored
Normal file
67
node_modules/mathjs/lib/cjs/function/algebra/sparse/csPermute.js
generated
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csPermute = csPermute;
|
||||
// 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
|
||||
*/
|
||||
function csPermute(a, pinv, q, values) {
|
||||
// a arrays
|
||||
const avalues = a._values;
|
||||
const aindex = a._index;
|
||||
const aptr = a._ptr;
|
||||
const asize = a._size;
|
||||
const adt = a._datatype;
|
||||
// rows & columns
|
||||
const m = asize[0];
|
||||
const n = asize[1];
|
||||
// c arrays
|
||||
const cvalues = values && a._values ? [] : null;
|
||||
const cindex = []; // (aptr[n])
|
||||
const cptr = []; // (n + 1)
|
||||
// initialize vars
|
||||
let nz = 0;
|
||||
// loop columns
|
||||
for (let k = 0; k < n; k++) {
|
||||
// column k of C is column q[k] of A
|
||||
cptr[k] = nz;
|
||||
// apply column permutation
|
||||
const j = q ? q[k] : k;
|
||||
// loop values in column j of A
|
||||
for (let t0 = aptr[j], t1 = aptr[j + 1], t = t0; t < t1; t++) {
|
||||
// row i of A is row pinv[i] of C
|
||||
const 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
|
||||
});
|
||||
}
|
||||
58
node_modules/mathjs/lib/cjs/function/algebra/sparse/csPost.js
generated
vendored
Normal file
58
node_modules/mathjs/lib/cjs/function/algebra/sparse/csPost.js
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csPost = csPost;
|
||||
var _csTdfs = require("./csTdfs.js");
|
||||
// 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
|
||||
|
||||
/**
|
||||
* Post order a tree of forest
|
||||
*
|
||||
* @param {Array} parent The tree or forest
|
||||
* @param {Number} n Number of columns
|
||||
*/
|
||||
function csPost(parent, n) {
|
||||
// check inputs
|
||||
if (!parent) {
|
||||
return null;
|
||||
}
|
||||
// vars
|
||||
let k = 0;
|
||||
let j;
|
||||
// allocate result
|
||||
const post = []; // (n)
|
||||
// workspace, head: first n entries, next: next n entries, stack: last n entries
|
||||
const w = []; // (3 * n)
|
||||
const head = 0;
|
||||
const next = n;
|
||||
const 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 = (0, _csTdfs.csTdfs)(j, k, w, head, next, post, stack);
|
||||
}
|
||||
return post;
|
||||
}
|
||||
57
node_modules/mathjs/lib/cjs/function/algebra/sparse/csReach.js
generated
vendored
Normal file
57
node_modules/mathjs/lib/cjs/function/algebra/sparse/csReach.js
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csReach = csReach;
|
||||
var _csMarked = require("./csMarked.js");
|
||||
var _csMark = require("./csMark.js");
|
||||
var _csDfs = require("./csDfs.js");
|
||||
// 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
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function csReach(g, b, k, xi, pinv) {
|
||||
// g arrays
|
||||
const gptr = g._ptr;
|
||||
const gsize = g._size;
|
||||
// b arrays
|
||||
const bindex = b._index;
|
||||
const bptr = b._ptr;
|
||||
// columns
|
||||
const n = gsize[1];
|
||||
// vars
|
||||
let p, p0, p1;
|
||||
// initialize top
|
||||
let top = n;
|
||||
// loop column indeces in B
|
||||
for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) {
|
||||
// node i
|
||||
const i = bindex[p];
|
||||
// check node i is marked
|
||||
if (!(0, _csMarked.csMarked)(gptr, i)) {
|
||||
// start a dfs at unmarked node i
|
||||
top = (0, _csDfs.csDfs)(i, g, top, xi, pinv);
|
||||
}
|
||||
}
|
||||
// loop columns from top -> n - 1
|
||||
for (p = top; p < n; p++) {
|
||||
// restore G
|
||||
(0, _csMark.csMark)(gptr, xi[p]);
|
||||
}
|
||||
return top;
|
||||
}
|
||||
91
node_modules/mathjs/lib/cjs/function/algebra/sparse/csSpsolve.js
generated
vendored
Normal file
91
node_modules/mathjs/lib/cjs/function/algebra/sparse/csSpsolve.js
generated
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createCsSpsolve = void 0;
|
||||
var _csReach = require("./csReach.js");
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
// 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
|
||||
|
||||
const name = 'csSpsolve';
|
||||
const dependencies = ['divideScalar', 'multiply', 'subtract'];
|
||||
const createCsSpsolve = exports.createCsSpsolve = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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
|
||||
const gvalues = g._values;
|
||||
const gindex = g._index;
|
||||
const gptr = g._ptr;
|
||||
const gsize = g._size;
|
||||
// columns
|
||||
const n = gsize[1];
|
||||
// b arrays
|
||||
const bvalues = b._values;
|
||||
const bindex = b._index;
|
||||
const bptr = b._ptr;
|
||||
// vars
|
||||
let p, p0, p1, q;
|
||||
// xi[top..n-1] = csReach(B(:,k))
|
||||
const top = (0, _csReach.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 (let px = top; px < n; px++) {
|
||||
// x array index for px
|
||||
const j = xi[px];
|
||||
// apply permutation vector (U x = b), j maps to column J of G
|
||||
const 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
|
||||
const 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;
|
||||
};
|
||||
});
|
||||
186
node_modules/mathjs/lib/cjs/function/algebra/sparse/csSqr.js
generated
vendored
Normal file
186
node_modules/mathjs/lib/cjs/function/algebra/sparse/csSqr.js
generated
vendored
Normal file
@@ -0,0 +1,186 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createCsSqr = void 0;
|
||||
var _csPermute = require("./csPermute.js");
|
||||
var _csPost = require("./csPost.js");
|
||||
var _csEtree = require("./csEtree.js");
|
||||
var _csAmd = require("./csAmd.js");
|
||||
var _csCounts = require("./csCounts.js");
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
// 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
|
||||
|
||||
const name = 'csSqr';
|
||||
const dependencies = ['add', 'multiply', 'transpose'];
|
||||
const createCsSqr = exports.createCsSqr = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
add,
|
||||
multiply,
|
||||
transpose
|
||||
} = _ref;
|
||||
const csAmd = (0, _csAmd.createCsAmd)({
|
||||
add,
|
||||
multiply,
|
||||
transpose
|
||||
});
|
||||
const csCounts = (0, _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
|
||||
const aptr = a._ptr;
|
||||
const asize = a._size;
|
||||
// columns
|
||||
const n = asize[1];
|
||||
// vars
|
||||
let k;
|
||||
// symbolic analysis result
|
||||
const 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
|
||||
const c = order ? (0, _csPermute.csPermute)(a, null, s.q, 0) : a;
|
||||
// etree of C'*C, where C=A(:,q)
|
||||
s.parent = (0, _csEtree.csEtree)(c, 1);
|
||||
// post order elimination tree
|
||||
const post = (0, _csPost.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
|
||||
const aptr = a._ptr;
|
||||
const aindex = a._index;
|
||||
const asize = a._size;
|
||||
// rows & columns
|
||||
const m = asize[0];
|
||||
const n = asize[1];
|
||||
// initialize s arrays
|
||||
s.pinv = []; // (m + n)
|
||||
s.leftmost = []; // (m)
|
||||
// vars
|
||||
const parent = s.parent;
|
||||
const pinv = s.pinv;
|
||||
const leftmost = s.leftmost;
|
||||
// workspace, next: first m entries, head: next n entries, tail: next n entries, nque: next n entries
|
||||
const w = []; // (m + 3 * n)
|
||||
const next = 0;
|
||||
const head = m;
|
||||
const tail = m + n;
|
||||
const nque = m + 2 * n;
|
||||
// vars
|
||||
let 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
|
||||
const 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;
|
||||
}
|
||||
});
|
||||
100
node_modules/mathjs/lib/cjs/function/algebra/sparse/csSymperm.js
generated
vendored
Normal file
100
node_modules/mathjs/lib/cjs/function/algebra/sparse/csSymperm.js
generated
vendored
Normal file
@@ -0,0 +1,100 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createCsSymperm = void 0;
|
||||
var _csCumsum = require("./csCumsum.js");
|
||||
var _factory = require("../../../utils/factory.js");
|
||||
// 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
|
||||
|
||||
const name = 'csSymperm';
|
||||
const dependencies = ['conj', 'SparseMatrix'];
|
||||
const createCsSymperm = exports.createCsSymperm = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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
|
||||
const avalues = a._values;
|
||||
const aindex = a._index;
|
||||
const aptr = a._ptr;
|
||||
const asize = a._size;
|
||||
// columns
|
||||
const n = asize[1];
|
||||
// C matrix arrays
|
||||
const cvalues = values && avalues ? [] : null;
|
||||
const cindex = []; // (nz)
|
||||
const cptr = []; // (n + 1)
|
||||
// variables
|
||||
let i, i2, j, j2, p, p0, p1;
|
||||
// create workspace vector
|
||||
const 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
|
||||
(0, _csCumsum.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
|
||||
const 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]
|
||||
});
|
||||
};
|
||||
});
|
||||
48
node_modules/mathjs/lib/cjs/function/algebra/sparse/csTdfs.js
generated
vendored
Normal file
48
node_modules/mathjs/lib/cjs/function/algebra/sparse/csTdfs.js
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csTdfs = csTdfs;
|
||||
// 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
|
||||
*/
|
||||
function csTdfs(j, k, w, head, next, post, stack) {
|
||||
// variables
|
||||
let top = 0;
|
||||
// place j on the stack
|
||||
w[stack] = j;
|
||||
// while (stack is not empty)
|
||||
while (top >= 0) {
|
||||
// p = top of stack
|
||||
const p = w[stack + top];
|
||||
// i = youngest child of p
|
||||
const 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;
|
||||
}
|
||||
20
node_modules/mathjs/lib/cjs/function/algebra/sparse/csUnflip.js
generated
vendored
Normal file
20
node_modules/mathjs/lib/cjs/function/algebra/sparse/csUnflip.js
generated
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.csUnflip = csUnflip;
|
||||
var _csFlip = require("./csFlip.js");
|
||||
// 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
|
||||
|
||||
/**
|
||||
* Flips the value if it is negative of returns the same value otherwise.
|
||||
*
|
||||
* @param {Number} i The value to flip
|
||||
*/
|
||||
function csUnflip(i) {
|
||||
// flip the value if it is negative
|
||||
return i < 0 ? (0, _csFlip.csFlip)(i) : i;
|
||||
}
|
||||
124
node_modules/mathjs/lib/cjs/function/algebra/sylvester.js
generated
vendored
Normal file
124
node_modules/mathjs/lib/cjs/function/algebra/sylvester.js
generated
vendored
Normal file
@@ -0,0 +1,124 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createSylvester = void 0;
|
||||
var _factory = require("../../utils/factory.js");
|
||||
const name = 'sylvester';
|
||||
const dependencies = ['typed', 'schur', 'matrixFromColumns', 'matrix', 'multiply', 'range', 'concat', 'transpose', 'index', 'subset', 'add', 'subtract', 'identity', 'lusolve', 'abs'];
|
||||
const createSylvester = exports.createSylvester = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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 (A, B, C) {
|
||||
return _sylvester(matrix(A), B, C);
|
||||
},
|
||||
'Array, Array, Matrix': function (A, B, C) {
|
||||
return _sylvester(matrix(A), matrix(B), C);
|
||||
},
|
||||
'Array, Matrix, Array': function (A, B, C) {
|
||||
return _sylvester(matrix(A), B, matrix(C));
|
||||
},
|
||||
'Matrix, Array, Matrix': function (A, B, C) {
|
||||
return _sylvester(A, matrix(B), C);
|
||||
},
|
||||
'Matrix, Array, Array': function (A, B, C) {
|
||||
return _sylvester(A, matrix(B), matrix(C));
|
||||
},
|
||||
'Matrix, Matrix, Array': function (A, B, C) {
|
||||
return _sylvester(A, B, matrix(C));
|
||||
},
|
||||
'Array, Array, Array': function (A, B, C) {
|
||||
return _sylvester(matrix(A), matrix(B), matrix(C)).toArray();
|
||||
}
|
||||
});
|
||||
function _sylvester(A, B, C) {
|
||||
const n = B.size()[0];
|
||||
const m = A.size()[0];
|
||||
const sA = schur(A);
|
||||
const F = sA.T;
|
||||
const U = sA.U;
|
||||
const sB = schur(multiply(-1, B));
|
||||
const G = sB.T;
|
||||
const V = sB.U;
|
||||
const D = multiply(multiply(transpose(U), C), V);
|
||||
const all = range(0, m);
|
||||
const y = [];
|
||||
const hc = (a, b) => concat(a, b, 1);
|
||||
const vc = (a, b) => concat(a, b, 0);
|
||||
for (let k = 0; k < n; k++) {
|
||||
if (k < n - 1 && abs(subset(G, index(k + 1, k))) > 1e-5) {
|
||||
let RHS = vc(subset(D, index(all, k)), subset(D, index(all, k + 1)));
|
||||
for (let 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)))));
|
||||
}
|
||||
const gkk = multiply(identity(m), multiply(-1, subset(G, index(k, k))));
|
||||
const gmk = multiply(identity(m), multiply(-1, subset(G, index(k + 1, k))));
|
||||
const gkm = multiply(identity(m), multiply(-1, subset(G, index(k, k + 1))));
|
||||
const gmm = multiply(identity(m), multiply(-1, subset(G, index(k + 1, k + 1))));
|
||||
const LHS = vc(hc(add(F, gkk), gmk), hc(gkm, add(F, gmm)));
|
||||
const 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 {
|
||||
let RHS = subset(D, index(all, k));
|
||||
for (let j = 0; j < k; j++) {
|
||||
RHS = add(RHS, multiply(y[j], subset(G, index(j, k))));
|
||||
}
|
||||
const gkk = subset(G, index(k, k));
|
||||
const LHS = subtract(F, multiply(gkk, identity(m)));
|
||||
y[k] = lusolve(LHS, RHS);
|
||||
}
|
||||
}
|
||||
const Y = matrix(matrixFromColumns(...y));
|
||||
const X = multiply(U, multiply(Y, transpose(V)));
|
||||
return X;
|
||||
}
|
||||
});
|
||||
66
node_modules/mathjs/lib/cjs/function/algebra/symbolicEqual.js
generated
vendored
Normal file
66
node_modules/mathjs/lib/cjs/function/algebra/symbolicEqual.js
generated
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createSymbolicEqual = void 0;
|
||||
var _is = require("../../utils/is.js");
|
||||
var _factory = require("../../utils/factory.js");
|
||||
const name = 'symbolicEqual';
|
||||
const dependencies = ['parse', 'simplify', 'typed', 'OperatorNode'];
|
||||
const createSymbolicEqual = exports.createSymbolicEqual = /* #__PURE__ */(0, _factory.factory)(name, dependencies, _ref => {
|
||||
let {
|
||||
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) {
|
||||
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
||||
const diff = new OperatorNode('-', 'subtract', [e1, e2]);
|
||||
const simplified = simplify(diff, {}, options);
|
||||
return (0, _is.isConstantNode)(simplified) && !simplified.value;
|
||||
}
|
||||
return typed(name, {
|
||||
'Node, Node': _symbolicEqual,
|
||||
'Node, Node, Object': _symbolicEqual
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user