code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function _import(name, value, options) { // TODO: refactor this function, it's to complicated and contains duplicate code if (options.wrap && typeof value === 'function') { // create a wrapper around the function value = _wrap(value); } if (isTypedFunction(math[name]) && isTypedFunction(value)) { if (options.override) { // give the typed function the right name value = typed(name, value.signatures); } else { // merge the existing and typed function value = typed(math[name], value); } math[name] = value; _importTransform(name, value); math.emit('import', name, function resolver() { return value; }); return; } if (math[name] === undefined || options.override) { math[name] = value; _importTransform(name, value); math.emit('import', name, function resolver() { return value; }); return; } if (!options.silent) { throw new Error('Cannot import "' + name + '": already exists'); } }
Add a property to the math namespace and create a chain proxy for it. @param {string} name @param {*} value @param {Object} options See import for a description of the options @private
_import
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _importTransform(name, value) { if (value && typeof value.transform === 'function') { math.expression.transform[name] = value.transform; if (allowedInExpressions(name)) { math.expression.mathWithTransform[name] = value.transform; } } else { // remove existing transform delete math.expression.transform[name]; if (allowedInExpressions(name)) { math.expression.mathWithTransform[name] = value; } } }
Add a property to the math namespace and create a chain proxy for it. @param {string} name @param {*} value @param {Object} options See import for a description of the options @private
_importTransform
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _deleteTransform(name) { delete math.expression.transform[name]; if (allowedInExpressions(name)) { math.expression.mathWithTransform[name] = math[name]; } else { delete math.expression.mathWithTransform[name]; } }
Add a property to the math namespace and create a chain proxy for it. @param {string} name @param {*} value @param {Object} options See import for a description of the options @private
_deleteTransform
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _importFactory(factory, options) { if (typeof factory.name === 'string') { var name = factory.name; var existingTransform = name in math.expression.transform; var namespace = factory.path ? traverse(math, factory.path) : math; var existing = namespace.hasOwnProperty(name) ? namespace[name] : undefined; var resolver = function resolver() { var instance = load(factory); if (instance && typeof instance.transform === 'function') { throw new Error('Transforms cannot be attached to factory functions. ' + 'Please create a separate function for it with exports.path="expression.transform"'); } if (isTypedFunction(existing) && isTypedFunction(instance)) { if (options.override) {// replace the existing typed function (nothing to do) } else { // merge the existing and new typed function instance = typed(existing, instance); } return instance; } if (existing === undefined || options.override) { return instance; } if (!options.silent) { throw new Error('Cannot import "' + name + '": already exists'); } }; if (factory.lazy !== false) { lazy(namespace, name, resolver); if (existingTransform) { _deleteTransform(name); } else { if (factory.path === 'expression.transform' || factoryAllowedInExpressions(factory)) { lazy(math.expression.mathWithTransform, name, resolver); } } } else { namespace[name] = resolver(); if (existingTransform) { _deleteTransform(name); } else { if (factory.path === 'expression.transform' || factoryAllowedInExpressions(factory)) { math.expression.mathWithTransform[name] = resolver(); } } } math.emit('import', name, resolver, factory.path); } else { // unnamed factory. // no lazy loading load(factory); } }
Import an instance of a factory into math.js @param {{factory: Function, name: string, path: string, math: boolean}} factory @param {Object} options See import for a description of the options @private
_importFactory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
resolver = function resolver() { var instance = load(factory); if (instance && typeof instance.transform === 'function') { throw new Error('Transforms cannot be attached to factory functions. ' + 'Please create a separate function for it with exports.path="expression.transform"'); } if (isTypedFunction(existing) && isTypedFunction(instance)) { if (options.override) {// replace the existing typed function (nothing to do) } else { // merge the existing and new typed function instance = typed(existing, instance); } return instance; } if (existing === undefined || options.override) { return instance; } if (!options.silent) { throw new Error('Cannot import "' + name + '": already exists'); } }
Import an instance of a factory into math.js @param {{factory: Function, name: string, path: string, math: boolean}} factory @param {Object} options See import for a description of the options @private
resolver
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isSupportedType(object) { return typeof object === 'function' || typeof object === 'number' || typeof object === 'string' || typeof object === 'boolean' || object === null || object && type.isUnit(object) || object && type.isComplex(object) || object && type.isBigNumber(object) || object && type.isFraction(object) || object && type.isMatrix(object) || object && Array.isArray(object); }
Check whether given object is a type which can be imported @param {Function | number | string | boolean | null | Unit | Complex} object @return {boolean} @private
isSupportedType
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isTypedFunction(fn) { return typeof fn === 'function' && _typeof(fn.signatures) === 'object'; }
Test whether a given thing is a typed-function @param {*} fn @return {boolean} Returns true when `fn` is a typed-function
isTypedFunction
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function allowedInExpressions(name) { return !unsafe.hasOwnProperty(name); }
Test whether a given thing is a typed-function @param {*} fn @return {boolean} Returns true when `fn` is a typed-function
allowedInExpressions
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factoryAllowedInExpressions(factory) { return factory.path === undefined && !unsafe.hasOwnProperty(factory.name); } // namespaces and functions not available in the parser for safety reasons
Test whether a given thing is a typed-function @param {*} fn @return {boolean} Returns true when `fn` is a typed-function
factoryAllowedInExpressions
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function contains(array, item) { return array.indexOf(item) !== -1; }
Test whether an Array contains a specific item. @param {Array.<string>} array @param {string} item @return {boolean}
contains
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function findIndex(array, item) { return array.map(function (i) { return i.toLowerCase(); }).indexOf(item.toLowerCase()); }
Find a string in an array. Case insensitive search @param {Array.<string>} array @param {string} item @return {number} Returns the index when found. Returns -1 when not found
findIndex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function validateOption(options, name, values) { if (options[name] !== undefined && !contains(values, options[name])) { var index = findIndex(values, options[name]); if (index !== -1) { // right value, wrong casing // TODO: lower case values are deprecated since v3, remove this warning some day. console.warn('Warning: Wrong casing for configuration option "' + name + '", should be "' + values[index] + '" instead of "' + options[name] + '".'); options[name] = values[index]; // change the option to the right casing } else { // unknown value console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". Available options: ' + values.map(JSON.stringify).join(', ') + '.'); } } }
Validate an option @param {Object} options Object with options @param {string} name Name of the option to validate @param {Array.<string>} values Array with valid values for this option
validateOption
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Chain(value) { if (!(this instanceof Chain)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (type.isChain(value)) { this.value = value.value; } else { this.value = value; } }
@constructor Chain Wrap any value in a chain, allowing to perform chained operations on the value. All methods available in the math.js library can be called upon the chain, and then will be evaluated with the value itself as first argument. The chain can be closed by executing chain.done(), which will return the final value. The Chain has a number of special functions: - done() Finalize the chained operation and return the chain's value. - valueOf() The same as done() - toString() Returns a string representation of the chain's value. @param {*} [value]
Chain
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createProxy(name, fn) { if (typeof fn === 'function') { Chain.prototype[name] = chainify(fn); } }
Create a proxy method for the chain @param {string} name @param {Function} fn The function to be proxied If fn is no function, it is silently ignored. @private
createProxy
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createLazyProxy(name, resolver) { lazy(Chain.prototype, name, function outerResolver() { var fn = resolver(); if (typeof fn === 'function') { return chainify(fn); } return undefined; // if not a function, ignore }); }
Create a proxy method for the chain @param {string} name @param {function} resolver The function resolving with the function to be proxied @private
createLazyProxy
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function chainify(fn) { return function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }; }
Make a function chainable @param {function} fn @return {Function} chain function @private
chainify
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
cosh = function(x) { return (Math.exp(x) + Math.exp(-x)) * 0.5; }
This class allows the manipulation of complex numbers. You can pass a complex number in different formats. Either as object, double, string or two integer parameters. Object form { re: <real>, im: <imaginary> } { arg: <angle>, abs: <radius> } { phi: <angle>, r: <radius> } Array / Vector form [ real, imaginary ] Double form 99.3 - Single double value String form '23.1337' - Simple real number '15+3i' - a simple complex number '3-i' - a simple complex number Example: var c = new Complex('99.3+8i'); c.mul({r: 3, i: 9}).div(4.9).sub(3, 2);
cosh
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
sinh = function(x) { return (Math.exp(x) - Math.exp(-x)) * 0.5; }
This class allows the manipulation of complex numbers. You can pass a complex number in different formats. Either as object, double, string or two integer parameters. Object form { re: <real>, im: <imaginary> } { arg: <angle>, abs: <radius> } { phi: <angle>, r: <radius> } Array / Vector form [ real, imaginary ] Double form 99.3 - Single double value String form '23.1337' - Simple real number '15+3i' - a simple complex number '3-i' - a simple complex number Example: var c = new Complex('99.3+8i'); c.mul({r: 3, i: 9}).div(4.9).sub(3, 2);
sinh
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
cosm1 = function(x) { var limit = Math.PI/4; if (x < -limit || x > limit) { return (Math.cos(x) - 1.0); } var xx = x * x; return xx * (-0.5 + xx * (1/24 + xx * (-1/720 + xx * (1/40320 + xx * (-1/3628800 + xx * (1/4790014600 + xx * (-1/87178291200 + xx * (1/20922789888000) ) ) ) ) ) ) ) }
Calculates cos(x) - 1 using Taylor series if x is small. @param {number} x @returns {number} cos(x) - 1
cosm1
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
hypot = function(x, y) { var a = Math.abs(x); var b = Math.abs(y); if (a < 3000 && b < 3000) { return Math.sqrt(a * a + b * b); } if (a < b) { a = b; b = x / y; } else { b = y / x; } return a * Math.sqrt(1 + b * b); }
Calculates cos(x) - 1 using Taylor series if x is small. @param {number} x @returns {number} cos(x) - 1
hypot
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
parser_exit = function() { throw SyntaxError('Invalid Param'); }
Calculates cos(x) - 1 using Taylor series if x is small. @param {number} x @returns {number} cos(x) - 1
parser_exit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
parse = function(a, b) { var z = {'re': 0, 'im': 0}; if (a === undefined || a === null) { z['re'] = z['im'] = 0; } else if (b !== undefined) { z['re'] = a; z['im'] = b; } else switch (typeof a) { case 'object': if ('im' in a && 're' in a) { z['re'] = a['re']; z['im'] = a['im']; } else if ('abs' in a && 'arg' in a) { if (!Number.isFinite(a['abs']) && Number.isFinite(a['arg'])) { return Complex['INFINITY']; } z['re'] = a['abs'] * Math.cos(a['arg']); z['im'] = a['abs'] * Math.sin(a['arg']); } else if ('r' in a && 'phi' in a) { if (!Number.isFinite(a['r']) && Number.isFinite(a['phi'])) { return Complex['INFINITY']; } z['re'] = a['r'] * Math.cos(a['phi']); z['im'] = a['r'] * Math.sin(a['phi']); } else if (a.length === 2) { // Quick array check z['re'] = a[0]; z['im'] = a[1]; } else { parser_exit(); } break; case 'string': z['im'] = /* void */ z['re'] = 0; var tokens = a.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g); var plus = 1; var minus = 0; if (tokens === null) { parser_exit(); } for (var i = 0; i < tokens.length; i++) { var c = tokens[i]; if (c === ' ' || c === '\t' || c === '\n') { /* void */ } else if (c === '+') { plus++; } else if (c === '-') { minus++; } else if (c === 'i' || c === 'I') { if (plus + minus === 0) { parser_exit(); } if (tokens[i + 1] !== ' ' && !isNaN(tokens[i + 1])) { z['im'] += parseFloat((minus % 2 ? '-' : '') + tokens[i + 1]); i++; } else { z['im'] += parseFloat((minus % 2 ? '-' : '') + '1'); } plus = minus = 0; } else { if (plus + minus === 0 || isNaN(c)) { parser_exit(); } if (tokens[i + 1] === 'i' || tokens[i + 1] === 'I') { z['im'] += parseFloat((minus % 2 ? '-' : '') + c); i++; } else { z['re'] += parseFloat((minus % 2 ? '-' : '') + c); } plus = minus = 0; } } // Still something on the stack if (plus + minus > 0) { parser_exit(); } break; case 'number': z['im'] = 0; z['re'] = a; break; default: parser_exit(); } if (isNaN(z['re']) || isNaN(z['im'])) { // If a calculation is NaN, we treat it as NaN and don't throw //parser_exit(); } return z; }
Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows @param {number} a @param {number} b @returns {number}
parse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_loop = function _loop() { var specialCharFound = false; escapeKeys.forEach(function (key, index) { if (specialCharFound) { return; } if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) { result += escapes[escapeKeys[index]]; runningStr = runningStr.slice(key.length, runningStr.length); specialCharFound = true; } }); if (!specialCharFound) { result += runningStr.slice(0, 1); runningStr = runningStr.slice(1, runningStr.length); } }
Escape a string to be used in LaTeX documents. @param {string} str the string to be escaped. @param {boolean} params.preserveFormatting whether formatting escapes should be performed (default: false). @param {function} params.escapeMapFn the function to modify the escape maps. @return {string} the escaped string, ready to be used in LaTeX.
_loop
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { return Fraction; }
Instantiate a Fraction from a JSON object @param {Object} json a JSON object structured as: `{"mathjs": "Fraction", "n": 3, "d": 8}` @return {BigNumber}
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createError(name) { function errorConstructor() { var temp = Error.apply(this, arguments); temp['name'] = this['name'] = name; this['stack'] = temp['stack']; this['message'] = temp['message']; } /** * Error constructor * * @constructor */ function IntermediateInheritor() {} IntermediateInheritor.prototype = Error.prototype; errorConstructor.prototype = new IntermediateInheritor(); return errorConstructor; }
This class offers the possibility to calculate fractions. You can pass a fraction in different formats. Either as array, as double, as string or as an integer. Array/Object form [ 0 => <nominator>, 1 => <denominator> ] [ n => <nominator>, d => <denominator> ] Integer form - Single integer value Double form - Single double value String form 123.456 - a simple double 123/456 - a string fraction 123.'456' - a double with repeating decimal places 123.(456) - synonym 123.45'6' - a double with repeating last place 123.45(6) - synonym Example: var f = new Fraction("9.4'31'"); f.mul([-4, 3]).div(4.9);
createError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function errorConstructor() { var temp = Error.apply(this, arguments); temp['name'] = this['name'] = name; this['stack'] = temp['stack']; this['message'] = temp['message']; }
This class offers the possibility to calculate fractions. You can pass a fraction in different formats. Either as array, as double, as string or as an integer. Array/Object form [ 0 => <nominator>, 1 => <denominator> ] [ n => <nominator>, d => <denominator> ] Integer form - Single integer value Double form - Single double value String form 123.456 - a simple double 123/456 - a string fraction 123.'456' - a double with repeating decimal places 123.(456) - synonym 123.45'6' - a double with repeating last place 123.45(6) - synonym Example: var f = new Fraction("9.4'31'"); f.mul([-4, 3]).div(4.9);
errorConstructor
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Fraction(a, b) { if (!(this instanceof Fraction)) { return new Fraction(a, b); } parse(a, b); if (Fraction['REDUCE']) { a = gcd(P["d"], P["n"]); // Abuse a } else { a = 1; } this["s"] = P["s"]; this["n"] = P["n"] / a; this["d"] = P["d"] / a; }
Module constructor @constructor @param {number|Fraction=} a @param {number=} b
Fraction
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function rec(a) { if (a.length === 1) return new Fraction(a[0]); return rec(a.slice(1))['inverse']()['add'](a[0]); }
Check if two rational numbers are the same Ex: new Fraction(19.6).equals([98, 5]);
rec
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function SparseMatrix(data, datatype) { if (!(this instanceof SparseMatrix)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (datatype && !isString(datatype)) { throw new Error('Invalid datatype: ' + datatype); } if (type.isMatrix(data)) { // create from matrix _createFromMatrix(this, data, datatype); } else if (data && isArray(data.index) && isArray(data.ptr) && isArray(data.size)) { // initialize fields this._values = data.values; this._index = data.index; this._ptr = data.ptr; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // create from array _createFromArray(this, data, datatype); } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._values = []; this._index = []; this._ptr = [0]; this._size = [0, 0]; this._datatype = datatype; } }
Sparse Matrix implementation. This type implements a Compressed Column Storage format for sparse matrices. @class SparseMatrix
SparseMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _createFromMatrix(matrix, source, datatype) { // check matrix type if (source.type === 'SparseMatrix') { // clone arrays matrix._values = source._values ? object.clone(source._values) : undefined; matrix._index = object.clone(source._index); matrix._ptr = object.clone(source._ptr); matrix._size = object.clone(source._size); matrix._datatype = datatype || source._datatype; } else { // build from matrix data _createFromArray(matrix, source.valueOf(), datatype || source._datatype); } }
Sparse Matrix implementation. This type implements a Compressed Column Storage format for sparse matrices. @class SparseMatrix
_createFromMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _createFromArray(matrix, data, datatype) { // initialize fields matrix._values = []; matrix._index = []; matrix._ptr = []; matrix._datatype = datatype; // discover rows & columns, do not use math.size() to avoid looping array twice var rows = data.length; var columns = 0; // equal signature to use var eq = equalScalar; // zero value var zero = 0; if (isString(datatype)) { // find signature that matches (datatype, datatype) eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype zero = typed.convert(0, datatype); } // check we have rows (empty array) if (rows > 0) { // column index var j = 0; do { // store pointer to values index matrix._ptr.push(matrix._index.length); // loop rows for (var i = 0; i < rows; i++) { // current row var row = data[i]; // check row is an array if (isArray(row)) { // update columns if needed (only on first column) if (j === 0 && columns < row.length) { columns = row.length; } // check row has column if (j < row.length) { // value var v = row[j]; // check value != 0 if (!eq(v, zero)) { // store value matrix._values.push(v); // index matrix._index.push(i); } } } else { // update columns if needed (only on first column) if (j === 0 && columns < 1) { columns = 1; } // check value != 0 (row is a scalar) if (!eq(row, zero)) { // store value matrix._values.push(row); // index matrix._index.push(i); } } } // increment index j++; } while (j < columns); } // store number of values in ptr matrix._ptr.push(matrix._index.length); // size matrix._size = [rows, columns]; }
Sparse Matrix implementation. This type implements a Compressed Column Storage format for sparse matrices. @class SparseMatrix
_createFromArray
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _getsubset(matrix, idx) { // check idx if (!type.isIndex(idx)) { throw new TypeError('Invalid index'); } var isScalar = idx.isScalar(); if (isScalar) { // return a scalar return matrix.get(idx.min()); } // validate dimensions var size = idx.size(); if (size.length !== matrix._size.length) { throw new DimensionError(size.length, matrix._size.length); } // vars var i, ii, k, kk; // validate if any of the ranges in the index is out of range var min = idx.min(); var max = idx.max(); for (i = 0, ii = matrix._size.length; i < ii; i++) { validateIndex(min[i], matrix._size[i]); validateIndex(max[i], matrix._size[i]); } // matrix arrays var mvalues = matrix._values; var mindex = matrix._index; var mptr = matrix._ptr; // rows & columns dimensions for result matrix var rows = idx.dimension(0); var columns = idx.dimension(1); // workspace & permutation vector var w = []; var pv = []; // loop rows in resulting matrix rows.forEach(function (i, r) { // update permutation vector pv[i] = r[0]; // mark i in workspace w[i] = true; }); // result matrix arrays var values = mvalues ? [] : undefined; var index = []; var ptr = []; // loop columns in result matrix columns.forEach(function (j) { // update ptr ptr.push(index.length); // loop values in column j for (k = mptr[j], kk = mptr[j + 1]; k < kk; k++) { // row i = mindex[k]; // check row is in result matrix if (w[i] === true) { // push index index.push(pv[i]); // check we need to process values if (values) { values.push(mvalues[k]); } } } }); // update ptr ptr.push(index.length); // return matrix return new SparseMatrix({ values: values, index: index, ptr: ptr, size: size, datatype: matrix._datatype }); }
Get a subset of the matrix, or replace a subset of the matrix. Usage: const subset = matrix.subset(index) // retrieve subset const value = matrix.subset(index, replacement) // replace subset @memberof SparseMatrix @param {Index} index @param {Array | Matrix | *} [replacement] @param {*} [defaultValue=0] Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be filled with zeros.
_getsubset
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _setsubset(matrix, index, submatrix, defaultValue) { // check index if (!index || index.isIndex !== true) { throw new TypeError('Invalid index'); } // get index size and check whether the index contains a single value var iSize = index.size(); var isScalar = index.isScalar(); // calculate the size of the submatrix, and convert it into an Array if needed var sSize; if (type.isMatrix(submatrix)) { // submatrix size sSize = submatrix.size(); // use array representation submatrix = submatrix.toArray(); } else { // get submatrix size (array, scalar) sSize = array.size(submatrix); } // check index is a scalar if (isScalar) { // verify submatrix is a scalar if (sSize.length !== 0) { throw new TypeError('Scalar expected'); } // set value matrix.set(index.min(), submatrix, defaultValue); } else { // validate dimensions, index size must be one or two dimensions if (iSize.length !== 1 && iSize.length !== 2) { throw new DimensionError(iSize.length, matrix._size.length, '<'); } // check submatrix and index have the same dimensions if (sSize.length < iSize.length) { // calculate number of missing outer dimensions var i = 0; var outer = 0; while (iSize[i] === 1 && sSize[i] === 1) { i++; } while (iSize[i] === 1) { outer++; i++; } // unsqueeze both outer and inner dimensions submatrix = array.unsqueeze(submatrix, iSize.length, outer, sSize); } // check whether the size of the submatrix matches the index size if (!object.deepEqual(iSize, sSize)) { throw new DimensionError(iSize, sSize, '>'); } // offsets var x0 = index.min()[0]; var y0 = index.min()[1]; // submatrix rows and columns var m = sSize[0]; var n = sSize[1]; // loop submatrix for (var x = 0; x < m; x++) { // loop columns for (var y = 0; y < n; y++) { // value at i, j var v = submatrix[x][y]; // invoke set (zero value will remove entry from matrix) matrix.set([x + x0, y + y0], v, defaultValue); } } } return matrix; }
Get a subset of the matrix, or replace a subset of the matrix. Usage: const subset = matrix.subset(index) // retrieve subset const value = matrix.subset(index, replacement) // replace subset @memberof SparseMatrix @param {Index} index @param {Array | Matrix | *} [replacement] @param {*} [defaultValue=0] Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be filled with zeros.
_setsubset
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _getValueIndex(i, top, bottom, index) { // check row is on the bottom side if (bottom - top === 0) { return bottom; } // loop rows [top, bottom[ for (var r = top; r < bottom; r++) { // check we found value index if (index[r] === i) { return r; } } // we did not find row return top; }
Replace a single element in the matrix. @memberof SparseMatrix @param {number[]} index Zero-based index @param {*} v @param {*} [defaultValue] Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be set to zero. @return {SparseMatrix} self
_getValueIndex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _remove(k, j, values, index, ptr) { // remove value @ k values.splice(k, 1); index.splice(k, 1); // update pointers for (var x = j + 1; x < ptr.length; x++) { ptr[x]--; } }
Replace a single element in the matrix. @memberof SparseMatrix @param {number[]} index Zero-based index @param {*} v @param {*} [defaultValue] Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be set to zero. @return {SparseMatrix} self
_remove
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _insert(k, i, j, v, values, index, ptr) { // insert value values.splice(k, 0, v); // update row for k index.splice(k, 0, i); // update column pointers for (var x = j + 1; x < ptr.length; x++) { ptr[x]++; } }
Replace a single element in the matrix. @memberof SparseMatrix @param {number[]} index Zero-based index @param {*} v @param {*} [defaultValue] Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elements will be set to zero. @return {SparseMatrix} self
_insert
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _resize(matrix, rows, columns, defaultValue) { // value to insert at the time of growing matrix var value = defaultValue || 0; // equal signature to use var eq = equalScalar; // zero value var zero = 0; if (isString(matrix._datatype)) { // find signature that matches (datatype, datatype) eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype zero = typed.convert(0, matrix._datatype); // convert value to the same datatype value = typed.convert(value, matrix._datatype); } // should we insert the value? var ins = !eq(value, zero); // old columns and rows var r = matrix._size[0]; var c = matrix._size[1]; var i, j, k; // check we need to increase columns if (columns > c) { // loop new columns for (j = c; j < columns; j++) { // update matrix._ptr for current column matrix._ptr[j] = matrix._values.length; // check we need to insert matrix._values if (ins) { // loop rows for (i = 0; i < r; i++) { // add new matrix._values matrix._values.push(value); // update matrix._index matrix._index.push(i); } } } // store number of matrix._values in matrix._ptr matrix._ptr[columns] = matrix._values.length; } else if (columns < c) { // truncate matrix._ptr matrix._ptr.splice(columns + 1, c - columns); // truncate matrix._values and matrix._index matrix._values.splice(matrix._ptr[columns], matrix._values.length); matrix._index.splice(matrix._ptr[columns], matrix._index.length); } // update columns c = columns; // check we need to increase rows if (rows > r) { // check we have to insert values if (ins) { // inserts var n = 0; // loop columns for (j = 0; j < c; j++) { // update matrix._ptr for current column matrix._ptr[j] = matrix._ptr[j] + n; // where to insert matrix._values k = matrix._ptr[j + 1] + n; // pointer var p = 0; // loop new rows, initialize pointer for (i = r; i < rows; i++, p++) { // add value matrix._values.splice(k + p, 0, value); // update matrix._index matrix._index.splice(k + p, 0, i); // increment inserts n++; } } // store number of matrix._values in matrix._ptr matrix._ptr[c] = matrix._values.length; } } else if (rows < r) { // deletes var d = 0; // loop columns for (j = 0; j < c; j++) { // update matrix._ptr for current column matrix._ptr[j] = matrix._ptr[j] - d; // where matrix._values start for next column var k0 = matrix._ptr[j]; var k1 = matrix._ptr[j + 1] - d; // loop matrix._index for (k = k0; k < k1; k++) { // row i = matrix._index[k]; // check we need to delete value and matrix._index if (i > rows - 1) { // remove value matrix._values.splice(k, 1); // remove item from matrix._index matrix._index.splice(k, 1); // increase deletes d++; } } } // update matrix._ptr for current column matrix._ptr[j] = matrix._values.length; } // update matrix._size matrix._size[0] = rows; matrix._size[1] = columns; // return matrix return matrix; }
Resize the matrix to the given size. Returns a copy of the matrix when `copy=true`, otherwise return the matrix itself (resize in place). @memberof SparseMatrix @param {number[]} size The new size the matrix should have. @param {*} [defaultValue=0] Default value, filled in on new entries. If not provided, the matrix elements will be filled with zeros. @param {boolean} [copy] Return a resized copy of the matrix @return {Matrix} The resized matrix
_resize
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
invoke = function invoke(v, i, j) { // invoke callback return callback(v, [i, j], me); }
Create a new matrix with the results of the callback function executed on each entry of the matrix. @memberof SparseMatrix @param {Function} callback The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed. @param {boolean} [skipZeros] Invoke callback function for non-zero values only. @return {SparseMatrix} matrix
invoke
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _map(matrix, minRow, maxRow, minColumn, maxColumn, callback, skipZeros) { // result arrays var values = []; var index = []; var ptr = []; // equal signature to use var eq = equalScalar; // zero value var zero = 0; if (isString(matrix._datatype)) { // find signature that matches (datatype, datatype) eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype zero = typed.convert(0, matrix._datatype); } // invoke callback var invoke = function invoke(v, x, y) { // invoke callback v = callback(v, x, y); // check value != 0 if (!eq(v, zero)) { // store value values.push(v); // index index.push(x); } }; // loop columns for (var j = minColumn; j <= maxColumn; j++) { // store pointer to values index ptr.push(values.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] var k0 = matrix._ptr[j]; var k1 = matrix._ptr[j + 1]; if (skipZeros) { // loop k within [k0, k1[ for (var k = k0; k < k1; k++) { // row index var i = matrix._index[k]; // check i is in range if (i >= minRow && i <= maxRow) { // value @ k invoke(matrix._values[k], i - minRow, j - minColumn); } } } else { // create a cache holding all defined values var _values = {}; for (var _k = k0; _k < k1; _k++) { var _i4 = matrix._index[_k]; _values[_i4] = matrix._values[_k]; } // loop over all rows (indexes can be unordered so we can't use that), // and either read the value or zero for (var _i5 = minRow; _i5 <= maxRow; _i5++) { var value = _i5 in _values ? _values[_i5] : 0; invoke(value, _i5 - minRow, j - minColumn); } } } // store number of values in ptr ptr.push(values.length); // return sparse matrix return new SparseMatrix({ values: values, index: index, ptr: ptr, size: [maxRow - minRow + 1, maxColumn - minColumn + 1] }); }
Create a new matrix with the results of the callback function executed on the interval [minRow..maxRow, minColumn..maxColumn].
_map
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
invoke = function invoke(v, x, y) { // invoke callback v = callback(v, x, y); // check value != 0 if (!eq(v, zero)) { // store value values.push(v); // index index.push(x); } }
Create a new matrix with the results of the callback function executed on the interval [minRow..maxRow, minColumn..maxColumn].
invoke
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Spa() { if (!(this instanceof Spa)) { throw new SyntaxError('Constructor must be called with the new operator'); } // allocate vector, TODO use typed arrays this._values = []; this._heap = new type.FibonacciHeap(); }
An ordered Sparse Accumulator is a representation for a sparse vector that includes a dense array of the vector elements and an ordered list of non-zero elements.
Spa
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function FibonacciHeap() { if (!(this instanceof FibonacciHeap)) { throw new SyntaxError('Constructor must be called with the new operator'); } // initialize fields this._minimum = null; this._size = 0; }
Fibonacci Heap implementation, used interally for Matrix math. @class FibonacciHeap @constructor FibonacciHeap
FibonacciHeap
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _decreaseKey(minimum, node, key) { // set node key node.key = key; // get parent node var parent = node.parent; if (parent && smaller(node.key, parent.key)) { // remove node from parent _cut(minimum, node, parent); // remove all nodes from parent to the root parent _cascadingCut(minimum, parent); } // update minimum node if needed if (smaller(node.key, minimum.key)) { minimum = node; } // return minimum return minimum; }
Decreases the key value for a heap node, given the new value to take on. The structure of the heap may be changed and will not be consolidated. Running time: O(1) amortized. @memberof FibonacciHeap
_decreaseKey
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _cut(minimum, node, parent) { // remove node from parent children and decrement Degree[parent] node.left.right = node.right; node.right.left = node.left; parent.degree--; // reset y.child if necessary if (parent.child === node) { parent.child = node.right; } // remove child if degree is 0 if (parent.degree === 0) { parent.child = null; } // add node to root list of heap node.left = minimum; node.right = minimum.right; minimum.right = node; node.right.left = node; // set parent[node] to null node.parent = null; // set mark[node] to false node.mark = false; }
The reverse of the link operation: removes node from the child list of parent. This method assumes that min is non-null. Running time: O(1). @memberof FibonacciHeap
_cut
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _cascadingCut(minimum, node) { // store parent node var parent = node.parent; // if there's a parent... if (!parent) { return; } // if node is unmarked, set it marked if (!node.mark) { node.mark = true; } else { // it's marked, cut it from parent _cut(minimum, node, parent); // cut its parent as well _cascadingCut(parent); } }
Performs a cascading cut operation. This cuts node from its parent and then does the same for its parent, and so on up the tree. Running time: O(log n); O(1) excluding the recursion. @memberof FibonacciHeap
_cascadingCut
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_linkNodes = function _linkNodes(node, parent) { // remove node from root list of heap node.left.right = node.right; node.right.left = node.left; // make node a Child of parent node.parent = parent; if (!parent.child) { parent.child = node; node.right = node; node.left = node; } else { node.left = parent.child; node.right = parent.child.right; parent.child.right = node; node.right.left = node; } // increase degree[parent] parent.degree++; // set mark[node] false node.mark = false; }
Make the first node a child of the second one. Running time: O(1) actual. @memberof FibonacciHeap
_linkNodes
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _findMinimumNode(minimum, size) { // to find trees of the same degree efficiently we use an array of length O(log n) in which we keep a pointer to one root of each degree var arraySize = Math.floor(Math.log(size) * oneOverLogPhi) + 1; // create list with initial capacity var array = new Array(arraySize); // find the number of root nodes. var numRoots = 0; var x = minimum; if (x) { numRoots++; x = x.right; while (x !== minimum) { numRoots++; x = x.right; } } // vars var y; // For each node in root list do... while (numRoots > 0) { // access this node's degree.. var d = x.degree; // get next node var next = x.right; // check if there is a node already in array with the same degree while (true) { // get node with the same degree is any y = array[d]; if (!y) { break; } // make one node with the same degree a child of the other, do this based on the key value. if (larger(x.key, y.key)) { var temp = y; y = x; x = temp; } // make y a child of x _linkNodes(y, x); // we have handled this degree, go to next one. array[d] = null; d++; } // save this node for later when we might encounter another of the same degree. array[d] = x; // move forward through list. x = next; numRoots--; } // Set min to null (effectively losing the root list) and reconstruct the root list from the array entries in array[]. minimum = null; // loop nodes in array for (var i = 0; i < arraySize; i++) { // get current node y = array[i]; if (!y) { continue; } // check if we have a linked list if (minimum) { // First remove node from root list. y.left.right = y.right; y.right.left = y.left; // now add to root list, again. y.left = minimum; y.right = minimum.right; minimum.right = y; y.right.left = y; // check if this is a new min. if (smaller(y.key, minimum.key)) { minimum = y; } } else { minimum = y; } } return minimum; }
Make the first node a child of the second one. Running time: O(1) actual. @memberof FibonacciHeap
_findMinimumNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Unit(value, name) { if (!(this instanceof Unit)) { throw new Error('Constructor must be called with the new operator'); } if (!(value === null || value === undefined || isNumeric(value) || type.isComplex(value))) { throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined'); } if (name !== undefined && (typeof name !== 'string' || name === '')) { throw new TypeError('Second parameter in Unit constructor must be a string'); } if (name !== undefined) { var u = Unit.parse(name); this.units = u.units; this.dimensions = u.dimensions; } else { this.units = [{ unit: UNIT_NONE, prefix: PREFIXES.NONE, // link to a list with supported prefixes power: 0 }]; this.dimensions = []; for (var i = 0; i < BASE_DIMENSIONS.length; i++) { this.dimensions[i] = 0; } } this.value = value !== undefined && value !== null ? this._normalize(value) : null; this.fixPrefix = false; // if true, function format will not search for the // best prefix but leave it as initially provided. // fixPrefix is set true by the method Unit.to // The justification behind this is that if the constructor is explicitly called, // the caller wishes the units to be returned exactly as he supplied. this.skipAutomaticSimplification = true; }
A unit can be constructed in the following ways: const a = new Unit(value, name) const b = new Unit(null, name) const c = Unit.parse(str) Example usage: const a = new Unit(5, 'cm') // 50 mm const b = Unit.parse('23 kg') // 23 kg const c = math.in(a, new Unit(null, 'm') // 0.05 m const d = new Unit(9.81, "m/s^2") // 9.81 m/s^2 @class Unit @constructor Unit @param {number | BigNumber | Fraction | Complex | boolean} [value] A value like 5.2 @param {string} [name] A unit name like "cm" or "inch", or a derived unit of the form: "u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3] [u4[^ex4]]]", such as "kg m^2/s^2", where each unit appearing after the forward slash is taken to be in the denominator. "kg m^2 s^-2" is a synonym and is also acceptable. Any of the units can include a prefix.
Unit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _findUnit(str) { // First, match units names exactly. For example, a user could define 'mm' as 10^-4 m, which is silly, but then we would want 'mm' to match the user-defined unit. if (UNITS.hasOwnProperty(str)) { var unit = UNITS[str]; var prefix = unit.prefixes['']; return { unit: unit, prefix: prefix }; } for (var name in UNITS) { if (UNITS.hasOwnProperty(name)) { if (endsWith(str, name)) { var _unit = UNITS[name]; var prefixLen = str.length - name.length; var prefixName = str.substring(0, prefixLen); var _prefix = _unit.prefixes.hasOwnProperty(prefixName) ? _unit.prefixes[prefixName] : undefined; if (_prefix !== undefined) { // store unit, prefix, and value return { unit: _unit, prefix: _prefix }; } } } } return null; }
Find a unit from a string @memberof Unit @param {string} str A string like 'cm' or 'inch' @returns {Object | null} result When found, an object with fields unit and prefix is returned. Else, null is returned. @private
_findUnit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function getNumericIfUnitless(unit) { if (unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) { return unit.value; } else { return unit; } }
Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise @param {Unit} unit @returns {number | Fraction | BigNumber | Unit} The numeric value of the unit if conditions are met, or the original unit otherwise
getNumericIfUnitless
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function calculateAngleValues(config) { if (config.number === 'BigNumber') { var pi = constants.pi(type.BigNumber); UNITS.rad.value = new type.BigNumber(1); UNITS.deg.value = pi.div(180); // 2 * pi / 360 UNITS.grad.value = pi.div(200); // 2 * pi / 400 UNITS.cycle.value = pi.times(2); // 2 * pi UNITS.arcsec.value = pi.div(648000); // 2 * pi / 360 / 3600 UNITS.arcmin.value = pi.div(10800); // 2 * pi / 360 / 60 } else { // number UNITS.rad.value = 1; UNITS.deg.value = Math.PI / 180; // 2 * pi / 360 UNITS.grad.value = Math.PI / 200; // 2 * pi / 400 UNITS.cycle.value = Math.PI * 2; // 2 * pi UNITS.arcsec.value = Math.PI / 648000; // 2 * pi / 360 / 3600 UNITS.arcmin.value = Math.PI / 10800; // 2 * pi / 360 / 60 } // copy to the full names of the angles UNITS.radian.value = UNITS.rad.value; UNITS.degree.value = UNITS.deg.value; UNITS.gradian.value = UNITS.grad.value; } // apply the angle values now
Calculate the values for the angle units. Value is calculated as number or BigNumber depending on the configuration @param {{number: 'number' | 'BigNumber'}} config
calculateAngleValues
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function assertUnitNameIsValid(name) { for (var i = 0; i < name.length; i++) { var _c = name.charAt(i); var isValidAlpha = function isValidAlpha(p) { return /^[a-zA-Z]$/.test(p); }; var _isDigit = function _isDigit(c) { return c >= '0' && c <= '9'; }; if (i === 0 && !isValidAlpha(_c)) { throw new Error('Invalid unit name (must begin with alpha character): "' + name + '"'); } if (i > 0 && !(isValidAlpha(_c) || _isDigit(_c))) { throw new Error('Invalid unit name (only alphanumeric characters are allowed): "' + name + '"'); } } }
Retrieve the right convertor function corresponding with the type of provided exampleValue. @param {string} type A string 'number', 'BigNumber', or 'Fraction' In case of an unknown type, @return {Function}
assertUnitNameIsValid
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
isValidAlpha = function isValidAlpha(p) { return /^[a-zA-Z]$/.test(p); }
Retrieve the right convertor function corresponding with the type of provided exampleValue. @param {string} type A string 'number', 'BigNumber', or 'Fraction' In case of an unknown type, @return {Function}
isValidAlpha
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_isDigit = function _isDigit(c) { return c >= '0' && c <= '9'; }
Retrieve the right convertor function corresponding with the type of provided exampleValue. @param {string} type A string 'number', 'BigNumber', or 'Fraction' In case of an unknown type, @return {Function}
_isDigit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function funcArgsCheck(node) { // TODO add min, max etc if ((node.name === 'log' || node.name === 'nthRoot' || node.name === 'pow') && node.args.length === 2) { return; } // There should be an incorrect number of arguments if we reach here // Change all args to constants to avoid unidentified // symbol error when compiling function for (var i = 0; i < node.args.length; ++i) { node.args[i] = createConstantNode(0); } node.compile().eval(); throw new Error('Expected TypeError, but none found'); }
Ensures the number of arguments for a function are correct, and will throw an error otherwise. @param {FunctionNode} node
funcArgsCheck
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createConstantNode(value, valueType) { return new ConstantNode(numeric(value, valueType || config.number)); }
Helper function to create a constant node with a specific type (number, BigNumber, Fraction) @param {number} value @param {string} [valueType] @return {ConstantNode}
createConstantNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function resolve(node, scope) { if (!scope) { return node; } if (type.isSymbolNode(node)) { var value = scope[node.name]; if (value instanceof Node) { return resolve(value, scope); } else if (typeof value === 'number') { return math.parse(String(value)); } } else if (type.isOperatorNode(node)) { var args = node.args.map(function (arg) { return resolve(arg, scope); }); return new OperatorNode(node.op, node.fn, args, node.implicit); } else if (type.isParenthesisNode(node)) { return new ParenthesisNode(resolve(node.content, scope)); } else if (type.isFunctionNode(node)) { var _args = node.args.map(function (arg) { return resolve(arg, scope); }); return new FunctionNode(node.name, _args); } return node; }
resolve(expr, scope) replaces variable nodes with their scoped values Syntax: simplify.resolve(expr, scope) Examples: math.simplify.resolve('x + y', {x:1, y:2}) // Node {1 + 2} math.simplify.resolve(math.parse('x+y'), {x:1, y:2}) // Node {1 + 2} math.simplify('x+y', {x:2, y:'x+x'}).toString() // "6" @param {Node} node The expression tree to be simplified @param {Object} scope with variables to be resolved
resolve
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function polynomial(expr, scope, extended, rules) { var variables = []; var node = simplify(expr, rules, scope, { exactFractions: false }); // Resolves any variables and functions with all defined parameters extended = !!extended; var oper = '+-*' + (extended ? '/' : ''); recPoly(node); var retFunc = {}; retFunc.expression = node; retFunc.variables = variables; return retFunc; // ------------------------------------------------------------------------------------------------------- /** * Function to simplify an expression using an optional scope and * return it if the expression is a polynomial expression, i.e. * an expression with one or more variables and the operators * +, -, *, and ^, where the exponent can only be a positive integer. * * Syntax: * * recPoly(node) * * * @param {Node} node The current sub tree expression in recursion * * @return nothing, throw an exception if error */ function recPoly(node) { var tp = node.type; // node type if (tp === 'FunctionNode') { // No function call in polynomial expression throw new Error('There is an unsolved function call'); } else if (tp === 'OperatorNode') { if (node.op === '^') { if (node.args[1].fn === 'unaryMinus') { node = node.args[0]; } if (node.args[1].type !== 'ConstantNode' || !number.isInteger(parseFloat(node.args[1].value))) { throw new Error('There is a non-integer exponent'); } else { recPoly(node.args[0]); } } else { if (oper.indexOf(node.op) === -1) { throw new Error('Operator ' + node.op + ' invalid in polynomial expression'); } for (var i = 0; i < node.args.length; i++) { recPoly(node.args[i]); } } // type of operator } else if (tp === 'SymbolNode') { var name = node.name; // variable name var pos = variables.indexOf(name); if (pos === -1) { // new variable in expression variables.push(name); } } else if (tp === 'ParenthesisNode') { recPoly(node.content); } else if (tp !== 'ConstantNode') { throw new Error('type ' + tp + ' is not allowed in polynomial expression'); } } // end of recPoly }
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
polynomial
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function recPoly(node) { var tp = node.type; // node type if (tp === 'FunctionNode') { // No function call in polynomial expression throw new Error('There is an unsolved function call'); } else if (tp === 'OperatorNode') { if (node.op === '^') { if (node.args[1].fn === 'unaryMinus') { node = node.args[0]; } if (node.args[1].type !== 'ConstantNode' || !number.isInteger(parseFloat(node.args[1].value))) { throw new Error('There is a non-integer exponent'); } else { recPoly(node.args[0]); } } else { if (oper.indexOf(node.op) === -1) { throw new Error('Operator ' + node.op + ' invalid in polynomial expression'); } for (var i = 0; i < node.args.length; i++) { recPoly(node.args[i]); } } // type of operator } else if (tp === 'SymbolNode') { var name = node.name; // variable name var pos = variables.indexOf(name); if (pos === -1) { // new variable in expression variables.push(name); } } else if (tp === 'ParenthesisNode') { recPoly(node.content); } else if (tp !== 'ConstantNode') { throw new Error('type ' + tp + ' is not allowed in polynomial expression'); } }
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
recPoly
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function expandPower(node, parent, indParent) { var tp = node.type; var internal = arguments.length > 1; // TRUE in internal calls if (tp === 'OperatorNode' && node.isBinary()) { var does = false; var val; if (node.op === '^') { // First operator: Parenthesis or UnaryMinus if ((node.args[0].type === 'ParenthesisNode' || node.args[0].type === 'OperatorNode') && node.args[1].type === 'ConstantNode') { // Second operator: Constant val = parseFloat(node.args[1].value); does = val >= 2 && 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 // var nEsqTopo = node.args[0]; var nDirTopo = new OperatorNode('^', 'pow', [node.args[0].cloneDeep(), new ConstantNode(val - 1)]); node = new OperatorNode('*', 'multiply', [nEsqTopo, nDirTopo]); } else { // Expo = 2 - no power // AFTER: (exponent = 2) // operator A --> Subtree // parent oper // deep clone (operator A --> Subtree) // node = new OperatorNode('*', 'multiply', [node.args[0], node.args[0].cloneDeep()]); } if (internal) { // Change parent references in internal recursive calls if (indParent === 'content') { parent.content = node; } else { parent.args[indParent] = node; } } } // does } // binary OperatorNode if (tp === 'ParenthesisNode') { // Recursion expandPower(node.content, node, 'content'); } else if (tp !== 'ConstantNode' && tp !== 'SymbolNode') { for (var i = 0; i < node.args.length; i++) { expandPower(node.args[i], node, i); } } if (!internal) { // return the root node return node; } }
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.
expandPower
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function recurPol(node, noPai, o) { var tp = node.type; if (tp === 'FunctionNode') { // ***** FunctionName ***** // No function call in polynomial expression throw new Error('There is an unsolved function call'); } else if (tp === 'OperatorNode') { // ***** OperatorName ***** if ('+-*^'.indexOf(node.op) === -1) throw new Error('Operator ' + node.op + ' invalid'); if (noPai !== null) { // -(unary),^ : children of *,+,- if ((node.fn === 'unaryMinus' || node.fn === 'pow') && noPai.fn !== 'add' && noPai.fn !== 'subtract' && noPai.fn !== 'multiply') { throw new Error('Invalid ' + node.op + ' placing'); } // -,+,* : children of +,- if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'multiply') && noPai.fn !== 'add' && noPai.fn !== 'subtract') { throw new Error('Invalid ' + node.op + ' placing'); } // -,+ : first child if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'unaryMinus') && o.noFil !== 0) { throw new Error('Invalid ' + node.op + ' placing'); } } // Has parent // Firers: ^,* Old: ^,&,-(unary): firers if (node.op === '^' || node.op === '*') { o.fire = node.op; } for (var _i = 0; _i < node.args.length; _i++) { // +,-: reset fire if (node.fn === 'unaryMinus') o.oper = '-'; if (node.op === '+' || node.fn === 'subtract') { o.fire = ''; o.cte = 1; // default if there is no constant o.oper = _i === 0 ? '+' : node.op; } o.noFil = _i; // number of son recurPol(node.args[_i], node, o); } // for in children } else if (tp === 'SymbolNode') { // ***** SymbolName ***** if (node.name !== varname && varname !== '') { throw new Error('There is more than one variable'); } varname = node.name; if (noPai === null) { coefficients[1] = 1; return; } // ^: Symbol is First child if (noPai.op === '^' && o.noFil !== 0) { throw new Error('In power the variable should be the first parameter'); } // *: Symbol is Second child if (noPai.op === '*' && o.noFil !== 1) { throw new Error('In multiply the variable should be the second parameter'); } // Symbol: firers '',* => it means there is no exponent above, so it's 1 (cte * var) if (o.fire === '' || o.fire === '*') { if (maxExpo < 1) coefficients[1] = 0; coefficients[1] += o.cte * (o.oper === '+' ? 1 : -1); maxExpo = Math.max(1, maxExpo); } } else if (tp === 'ConstantNode') { var valor = parseFloat(node.value); if (noPai === null) { coefficients[0] = valor; return; } if (noPai.op === '^') { // cte: second child of power if (o.noFil !== 1) throw new Error('Constant cannot be powered'); if (!number.isInteger(valor) || valor <= 0) { throw new Error('Non-integer exponent is not allowed'); } for (var _i2 = maxExpo + 1; _i2 < valor; _i2++) { coefficients[_i2] = 0; } if (valor > maxExpo) coefficients[valor] = 0; coefficients[valor] += o.cte * (o.oper === '+' ? 1 : -1); maxExpo = Math.max(valor, maxExpo); return; } o.cte = valor; // Cte: firer '' => There is no exponent and no multiplication, so the exponent is 0. if (o.fire === '') { coefficients[0] += o.cte * (o.oper === '+' ? 1 : -1); } } else { throw new Error('Type ' + tp + ' is not allowed'); } }
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
recurPol
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _denseQR(m) { // rows & columns (m x n) var rows = m._size[0]; // m var cols = m._size[1]; // n var Q = identity([rows], 'dense'); var Qdata = Q._data; var R = m.clone(); var Rdata = R._data; // vars var i, j, k; var w = zeros([rows], ''); for (k = 0; k < Math.min(cols, rows); ++k) { /* * **k-th Household matrix** * * The matrix I - 2*v*transpose(v) * x = first column of A * x1 = first element of x * alpha = x1 / |x1| * |x| * e1 = tranpose([1, 0, 0, ...]) * u = x - alpha * e1 * v = u / |u| * * Household matrix = I - 2 * v * tranpose(v) * * * Initially Q = I and R = A. * * Household matrix is a reflection in a plane normal to v which * will zero out all but the top right element in R. * * Appplying reflection to both Q and R will not change product. * * Repeat this process on the (1,1) minor to get R as an upper * triangular matrix. * * Reflections leave the magnitude of the columns of Q unchanged * so Q remains othoganal. * */ var pivot = Rdata[k][k]; var sgn = unaryMinus(sign(pivot)); var conjSgn = conj(sgn); var alphaSquared = 0; for (i = k; i < rows; i++) { alphaSquared = addScalar(alphaSquared, multiplyScalar(Rdata[i][k], conj(Rdata[i][k]))); } var alpha = multiplyScalar(sgn, sqrt(alphaSquared)); if (!isZero(alpha)) { // first element in vector u var u1 = subtract(pivot, alpha); // w = v * u1 / |u| (only elements k to (rows-1) are used) w[k] = 1; for (i = k + 1; i < rows; i++) { w[i] = divideScalar(Rdata[i][k], u1); } // tau = - conj(u1 / alpha) var tau = unaryMinus(conj(divideScalar(u1, alpha))); var s = void 0; /* * tau and w have been choosen so that * * 2 * v * tranpose(v) = tau * w * tranpose(w) */ /* * -- calculate R = R - tau * w * tranpose(w) * R -- * Only do calculation with rows k to (rows-1) * Additionally columns 0 to (k-1) will not be changed by this * multiplication so do not bother recalculating them */ for (j = k; j < cols; j++) { s = 0.0; // calculate jth element of [tranpose(w) * R] for (i = k; i < rows; i++) { s = addScalar(s, multiplyScalar(conj(w[i]), Rdata[i][j])); } // calculate the jth element of [tau * transpose(w) * R] s = multiplyScalar(s, tau); for (i = k; i < rows; i++) { Rdata[i][j] = multiplyScalar(subtract(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(subtract(Qdata[i][j], multiplyScalar(s, conj(w[j]))), conjSgn); } } } } // coerse almost zero elements to zero // TODO I feel uneasy just zeroing these values for (i = 0; i < rows; ++i) { for (j = 0; j < i && j < cols; ++j) { if (unequal(0, divideScalar(Rdata[i][j], 1e5))) { throw new Error('math.qr(): unknown error - ' + 'R is not lower triangular (element (' + i + ', ' + j + ') = ' + Rdata[i][j] + ')'); } Rdata[i][j] = multiplyScalar(Rdata[i][j], 0); } } // return matrices return { Q: Q, R: R, toString: function toString() { return 'Q: ' + this.Q.toString() + '\nR: ' + this.R.toString(); } }; }
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
_denseQR
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sparseQR(m) { throw new Error('qr not implemented for sparse matrices yet'); }
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
_sparseQR
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csSqr = function csSqr(order, a, qr) { // a arrays var aptr = a._ptr; var asize = a._size; // columns var n = asize[1]; // vars var k; // symbolic analysis result var s = {}; // fill-reducing ordering s.q = csAmd(order, a); // validate results if (order && !s.q) { return null; } // QR symbolic analysis if (qr) { // apply permutations if needed var c = order ? csPermute(a, null, s.q, 0) : a; // etree of C'*C, where C=A(:,q) s.parent = csEtree(c, 1); // post order elimination tree var post = csPost(s.parent, n); // col counts chol(C'*C) s.cp = csCounts(c, s.parent, post, 1); // check we have everything needed to calculate number of nonzero elements if (c && s.parent && s.cp && _vcount(c, s)) { // calculate number of nonzero elements for (s.unz = 0, k = 0; k < n; k++) { s.unz += s.cp[k]; } } } else { // for LU factorization only, guess nnz(L) and nnz(U) s.unz = 4 * aptr[n] + n; s.lnz = s.unz; } // return result S return s; }
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 Reference: http://faculty.cse.tamu.edu/davis/publications.html
csSqr
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _vcount(a, s) { // a arrays var aptr = a._ptr; var aindex = a._index; var asize = a._size; // rows & columns var m = asize[0]; var n = asize[1]; // initialize s arrays s.pinv = []; // (m + n) s.leftmost = []; // (m) // vars var parent = s.parent; var pinv = s.pinv; var leftmost = s.leftmost; // workspace, next: first m entries, head: next n entries, tail: next n entries, nque: next n entries var w = []; // (m + 3 * n) var next = 0; var head = m; var tail = m + n; var nque = m + 2 * n; // vars var i, k, p, p0, p1; // initialize w for (k = 0; k < n; k++) { // queue k is empty w[head + k] = -1; w[tail + k] = -1; w[nque + k] = 0; } // initialize row arrays for (i = 0; i < m; i++) { leftmost[i] = -1; } // loop columns backwards for (k = n - 1; k >= 0; k--) { // values & index for column k for (p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) { // leftmost[i] = min(find(A(i,:))) leftmost[aindex[p]] = k; } } // scan rows in reverse order for (i = m - 1; i >= 0; i--) { // row i is not yet ordered pinv[i] = -1; k = leftmost[i]; // check row i is empty if (k === -1) { continue; } // first row in queue k if (w[nque + k]++ === 0) { w[tail + k] = i; } // put i at head of queue k w[next + i] = w[head + k]; w[head + k] = i; } s.lnz = 0; s.m2 = m; // find row permutation and nnz(V) for (k = 0; k < n; k++) { // remove row i from queue k i = w[head + k]; // count V(k,k) as nonzero s.lnz++; // add a fictitious row if (i < 0) { i = s.m2++; } // associate row i with V(:,k) pinv[i] = k; // skip if V(k+1:m,k) is empty if (--nque[k] <= 0) { continue; } // nque[k] is nnz (V(k+1:m,k)) s.lnz += w[nque + k]; // move all rows to parent of k var pa = parent[k]; if (pa !== -1) { if (w[nque + pa] === 0) { w[tail + pa] = w[tail + k]; } w[next + w[tail + k]] = w[head + pa]; w[head + pa] = w[next + i]; w[nque + pa] += w[nque + k]; } } for (i = 0; i < m; i++) { if (pinv[i] < 0) { pinv[i] = k++; } } return true; }
Compute nnz(V) = s.lnz, s.pinv, s.leftmost, s.m2 from A and s.parent
_vcount
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csAmd = function csAmd(order, a) { // check input parameters if (!a || order <= 0 || order > 3) { return null; } // a matrix arrays var asize = a._size; // rows and columns var m = asize[0]; var n = asize[1]; // initialize vars var lemax = 0; // dense threshold var dense = Math.max(16, 10 * Math.sqrt(n)); dense = Math.min(n - 2, dense); // create target matrix C var cm = _createTargetMatrix(order, a, m, n, dense); // drop diagonal entries csFkeep(cm, _diag, null); // C matrix arrays var cindex = cm._index; var cptr = cm._ptr; // number of nonzero elements in C var cnz = cptr[n]; // allocate result (n+1) var P = []; // create workspace (8 * (n + 1)) var W = []; var len = 0; // first n + 1 entries var nv = n + 1; // next n + 1 entries var next = 2 * (n + 1); // next n + 1 entries var head = 3 * (n + 1); // next n + 1 entries var elen = 4 * (n + 1); // next n + 1 entries var degree = 5 * (n + 1); // next n + 1 entries var w = 6 * (n + 1); // next n + 1 entries var hhead = 7 * (n + 1); // last n + 1 entries // use P as workspace for last var last = P; // initialize quotient graph var mark = _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree); // initialize degree lists var nel = _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next); // minimum degree node var mindeg = 0; // vars var i, j, k, k1, k2, e, pj, ln, nvi, pk, eln, p1, p2, pn, h, d; // while (selecting pivots) do while (nel < n) { // select node of minimum approximate degree. amd() is now ready to start eliminating the graph. It first // finds a node k of minimum degree and removes it from its degree list. The variable nel keeps track of thow // many nodes have been eliminated. for (k = -1; mindeg < n && (k = W[head + mindeg]) === -1; mindeg++) { ; } if (W[next + k] !== -1) { last[W[next + k]] = -1; } // remove k from degree list W[head + mindeg] = W[next + k]; // elenk = |Ek| var elenk = W[elen + k]; // # of nodes k represents var nvk = W[nv + k]; // W[nv + k] nodes of A eliminated nel += nvk; // Construct a new element. The new element Lk is constructed in place if |Ek| = 0. nv[i] is // negated for all nodes i in Lk to flag them as members of this set. Each node i is removed from the // degree lists. All elements e in Ek are absorved into element k. var dk = 0; // flag k as in Lk W[nv + k] = -nvk; var p = cptr[k]; // do in place if W[elen + k] === 0 var pk1 = elenk === 0 ? p : cnz; var pk2 = pk1; for (k1 = 1; k1 <= elenk + 1; k1++) { if (k1 > elenk) { // search the nodes in k e = k; // list of nodes starts at cindex[pj] pj = p; // length of list of nodes in k ln = W[len + k] - elenk; } else { // search the nodes in e e = cindex[p++]; pj = cptr[e]; // length of list of nodes in e ln = W[len + e]; } for (k2 = 1; k2 <= ln; k2++) { i = cindex[pj++]; // check node i dead, or seen if ((nvi = W[nv + i]) <= 0) { continue; } // W[degree + Lk] += size of node i dk += nvi; // negate W[nv + i] to denote i in Lk W[nv + i] = -nvi; // place i in Lk cindex[pk2++] = i; if (W[next + i] !== -1) { last[W[next + i]] = last[i]; } // check we need to remove i from degree list if (last[i] !== -1) { W[next + last[i]] = W[next + i]; } else { W[head + W[degree + i]] = W[next + i]; } } if (e !== k) { // absorb e into k cptr[e] = csFlip(k); // e is now a dead element W[w + e] = 0; } } // cindex[cnz...nzmax] is free if (elenk !== 0) { cnz = pk2; } // external degree of k - |Lk\i| W[degree + k] = dk; // element k is in cindex[pk1..pk2-1] cptr[k] = pk1; W[len + k] = pk2 - pk1; // k is now an element W[elen + k] = -2; // Find set differences. The scan1 function now computes the set differences |Le \ Lk| for all elements e. At the start of the // scan, no entry in the w array is greater than or equal to mark. // clear w if necessary mark = _wclear(mark, lemax, W, w, n); // scan 1: find |Le\Lk| for (pk = pk1; pk < pk2; pk++) { i = cindex[pk]; // check if W[elen + i] empty, skip it if ((eln = W[elen + i]) <= 0) { continue; } // W[nv + i] was negated nvi = -W[nv + i]; var wnvi = mark - nvi; // scan Ei for (p = cptr[i], p1 = cptr[i] + eln - 1; p <= p1; p++) { e = cindex[p]; if (W[w + e] >= mark) { // decrement |Le\Lk| W[w + e] -= nvi; } else if (W[w + e] !== 0) { // ensure e is a live element, 1st time e seen in scan 1 W[w + e] = W[degree + e] + wnvi; } } } // degree update // The second pass computes the approximate degree di, prunes the sets Ei and Ai, and computes a hash // function h(i) for all nodes in Lk. // scan2: degree update for (pk = pk1; pk < pk2; pk++) { // consider node i in Lk i = cindex[pk]; p1 = cptr[i]; p2 = p1 + W[elen + i] - 1; pn = p1; // scan Ei for (h = 0, d = 0, p = p1; p <= p2; p++) { e = cindex[p]; // check e is an unabsorbed element if (W[w + e] !== 0) { // dext = |Le\Lk| var dext = W[w + e] - mark; if (dext > 0) { // sum up the set differences d += dext; // keep e in Ei cindex[pn++] = e; // compute the hash of node i h += e; } else { // aggressive absorb. e->k cptr[e] = csFlip(k); // e is a dead element W[w + e] = 0; } } } // W[elen + i] = |Ei| W[elen + i] = pn - p1 + 1; var p3 = pn; var p4 = p1 + W[len + i]; // prune edges in Ai for (p = p2 + 1; p < p4; p++) { j = cindex[p]; // check node j dead or in Lk var nvj = W[nv + j]; if (nvj <= 0) { continue; } // degree(i) += |j| d += nvj; // place j in node list of i cindex[pn++] = j; // compute hash for node i h += j; } // check for mass elimination if (d === 0) { // absorb i into k cptr[i] = csFlip(k); nvi = -W[nv + i]; // |Lk| -= |i| dk -= nvi; // |k| += W[nv + i] nvk += nvi; nel += nvi; W[nv + i] = 0; // node i is dead W[elen + i] = -1; } else { // update degree(i) W[degree + i] = Math.min(W[degree + i], d); // move first node to end cindex[pn] = cindex[p3]; // move 1st el. to end of Ei cindex[p3] = cindex[p1]; // add k as 1st element in of Ei cindex[p1] = k; // new len of adj. list of node i W[len + i] = pn - p1 + 1; // finalize hash of i h = (h < 0 ? -h : h) % n; // place i in hash bucket W[next + i] = W[hhead + h]; W[hhead + h] = i; // save hash of i in last[i] last[i] = h; } } // finalize |Lk| W[degree + k] = dk; lemax = Math.max(lemax, dk); // clear w mark = _wclear(mark + lemax, lemax, W, w, n); // Supernode detection. Supernode detection relies on the hash function h(i) computed for each node i. // If two nodes have identical adjacency lists, their hash functions wil be identical. for (pk = pk1; pk < pk2; pk++) { i = cindex[pk]; // check i is dead, skip it if (W[nv + i] >= 0) { continue; } // scan hash bucket of node i h = last[i]; i = W[hhead + h]; // hash bucket will be empty W[hhead + h] = -1; for (; i !== -1 && W[next + i] !== -1; i = W[next + i], mark++) { ln = W[len + i]; eln = W[elen + i]; for (p = cptr[i] + 1; p <= cptr[i] + ln - 1; p++) { W[w + cindex[p]] = mark; } var jlast = i; // compare i with all j for (j = W[next + i]; j !== -1;) { var ok = W[len + j] === ln && W[elen + j] === eln; for (p = cptr[j] + 1; ok && p <= cptr[j] + ln - 1; p++) { // compare i and j if (W[w + cindex[p]] !== mark) { ok = 0; } } // check i and j are identical if (ok) { // absorb j into i cptr[j] = csFlip(i); W[nv + i] += W[nv + j]; W[nv + j] = 0; // node j is dead W[elen + j] = -1; // delete j from hash bucket j = W[next + j]; W[next + jlast] = j; } else { // j and i are different jlast = j; j = W[next + j]; } } } } // Finalize new element. The elimination of node k is nearly complete. All nodes i in Lk are scanned one last time. // Node i is removed from Lk if it is dead. The flagged status of nv[i] is cleared. for (p = pk1, pk = pk1; pk < pk2; pk++) { i = cindex[pk]; // check i is dead, skip it if ((nvi = -W[nv + i]) <= 0) { continue; } // restore W[nv + i] W[nv + i] = nvi; // compute external degree(i) d = W[degree + i] + dk - nvi; d = Math.min(d, n - nel - nvi); if (W[head + d] !== -1) { last[W[head + d]] = i; } // put i back in degree list W[next + i] = W[head + d]; last[i] = -1; W[head + d] = i; // find new minimum degree mindeg = Math.min(mindeg, d); W[degree + i] = d; // place i in Lk cindex[p++] = i; } // # nodes absorbed into k W[nv + k] = nvk; // length of adj list of element k if ((W[len + k] = p - pk1) === 0) { // k is a root of the tree cptr[k] = -1; // k is now a dead element W[w + k] = 0; } if (elenk !== 0) { // free unused space in Lk cnz = p; } } // Postordering. The elimination is complete, but no permutation has been computed. All that is left // of the graph is the assembly tree (ptr) and a set of dead nodes and elements (i is a dead node if // nv[i] is zero and a dead element if nv[i] > 0). It is from this information only that the final permutation // is computed. The tree is restored by unflipping all of ptr. // fix assembly tree for (i = 0; i < n; i++) { cptr[i] = csFlip(cptr[i]); } for (j = 0; j <= n; j++) { W[head + j] = -1; } // place unordered nodes in lists for (j = n; j >= 0; j--) { // skip if j is an element if (W[nv + j] > 0) { continue; } // place j in list of its parent W[next + j] = W[head + cptr[j]]; W[head + cptr[j]] = j; } // place elements in lists for (e = n; e >= 0; e--) { // skip unless e is an element if (W[nv + e] <= 0) { continue; } if (cptr[e] !== -1) { // place e in list of its parent W[next + e] = W[head + cptr[e]]; W[head + cptr[e]] = e; } } // postorder the assembly tree for (k = 0, i = 0; i <= n; i++) { if (cptr[i] === -1) { k = csTdfs(i, k, W, head, next, P, w); } } // remove last item in array P.splice(P.length - 1, 1); // return P return P; }
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. Reference: http://faculty.cse.tamu.edu/davis/publications.html @param {Number} order 0: Natural, 1: Cholesky, 2: LU, 3: QR @param {Matrix} m Sparse Matrix
csAmd
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _createTargetMatrix(order, a, m, n, dense) { // compute A' var at = transpose(a); // check order = 1, matrix must be square if (order === 1 && n === m) { // C = A + A' return add(a, at); } // check order = 2, drop dense columns from M' if (order === 2) { // transpose arrays var tindex = at._index; var tptr = at._ptr; // new column index var p2 = 0; // loop A' columns (rows) for (var j = 0; j < m; j++) { // column j of AT starts here var p = tptr[j]; // new column j starts here tptr[j] = p2; // skip dense col j if (tptr[j + 1] - p > dense) { continue; } // map rows in column j of A for (var p1 = tptr[j + 1]; p < p1; p++) { tindex[p2++] = tindex[p]; } } // finalize AT tptr[m] = p2; // recreate A from new transpose matrix a = transpose(at); // use A' * A return multiply(at, a); } // use A' * A, square or rectangular matrix return multiply(at, a); }
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
_createTargetMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree) { // Initialize quotient graph for (var k = 0; k < n; k++) { W[len + k] = cptr[k + 1] - cptr[k]; } W[len + n] = 0; // initialize workspace for (var i = 0; i <= n; i++) { // degree list i is empty W[head + i] = -1; last[i] = -1; W[next + i] = -1; // hash list i is empty W[hhead + i] = -1; // node i is just one node W[nv + i] = 1; // node i is alive W[w + i] = 1; // Ek of node i is empty W[elen + i] = 0; // degree of node i W[degree + i] = W[len + i]; } // clear w var mark = _wclear(0, 0, W, w, n); // n is a dead element W[elen + n] = -2; // n is a root of assembly tree cptr[n] = -1; // n is a dead element W[w + n] = 0; // return mark return mark; }
Initialize 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]).
_initializeQuotientGraph
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next) { // result var nel = 0; // loop columns for (var i = 0; i < n; i++) { // degree @ i var d = W[degree + i]; // check node i is empty if (d === 0) { // element i is dead W[elen + i] = -2; nel++; // i is a root of assembly tree cptr[i] = -1; W[w + i] = 0; } else if (d > dense) { // absorb i into element n W[nv + i] = 0; // node i is dead W[elen + i] = -1; nel++; cptr[i] = csFlip(n); W[nv + n]++; } else { var h = W[head + d]; if (h !== -1) { last[h] = i; } // put node i in degree list d W[next + i] = W[head + d]; W[head + d] = i; } } return nel; }
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.
_initializeDegreeLists
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _wclear(mark, lemax, W, w, n) { if (mark < 2 || mark + lemax < 0) { for (var k = 0; k < n; k++) { if (W[w + k] !== 0) { W[w + k] = 1; } } mark = 2; } // at this point, W [0..n-1] < mark holds return mark; }
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.
_wclear
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _diag(i, j) { return i !== j; }
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.
_diag
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csFkeep = function csFkeep(a, callback, other) { // a arrays var avalues = a._values; var aindex = a._index; var aptr = a._ptr; var asize = a._size; // columns var n = asize[1]; // nonzero items var nz = 0; // loop columns for (var j = 0; j < n; j++) { // get current location of col j var p = aptr[j]; // record new location of col j aptr[j] = nz; for (; p < aptr[j + 1]; p++) { // check we need to keep this item if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) { // keep A(i,j) aindex[nz] = aindex[p]; // check we need to process values (pattern only) if (avalues) { avalues[nz] = avalues[p]; } // increment nonzero items nz++; } } } // finalize A aptr[n] = nz; // trim arrays aindex.splice(nz, aindex.length - nz); // check we need to process values (pattern only) if (avalues) { avalues.splice(nz, avalues.length - nz); } // return number of nonzero items return nz; }
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 Reference: http://faculty.cse.tamu.edu/davis/publications.html
csFkeep
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csPermute = function csPermute(a, pinv, q, values) { // a arrays var avalues = a._values; var aindex = a._index; var aptr = a._ptr; var asize = a._size; var adt = a._datatype; // rows & columns var m = asize[0]; var n = asize[1]; // c arrays var cvalues = values && a._values ? [] : null; var cindex = []; // (aptr[n]) var cptr = []; // (n + 1) // initialize vars var nz = 0; // loop columns for (var k = 0; k < n; k++) { // column k of C is column q[k] of A cptr[k] = nz; // apply column permutation var j = q ? q[k] : k; // loop values in column j of A for (var t0 = aptr[j], t1 = aptr[j + 1], t = t0; t < t1; t++) { // row i of A is row pinv[i] of C var r = pinv ? pinv[aindex[t]] : aindex[t]; // index cindex[nz] = r; // check we need to populate values if (cvalues) { cvalues[nz] = avalues[t]; } // increment number of nonzero elements nz++; } } // finalize the last column of C cptr[n] = nz; // return C matrix return new SparseMatrix({ values: cvalues, index: cindex, ptr: cptr, size: [m, n], datatype: adt }); }
Permutes a sparse matrix C = P * A * Q @param {Matrix} 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 Reference: http://faculty.cse.tamu.edu/davis/publications.html
csPermute
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csEtree = function csEtree(a, ata) { // check inputs if (!a) { return null; } // a arrays var aindex = a._index; var aptr = a._ptr; var asize = a._size; // rows & columns var m = asize[0]; var n = asize[1]; // allocate result var parent = []; // (n) // allocate workspace var w = []; // (n + (ata ? m : 0)) var ancestor = 0; // first n entries in w var prev = n; // last m entries (ata = true) var i, inext; // check we are calculating A'A if (ata) { // initialize workspace for (i = 0; i < m; i++) { w[prev + i] = -1; } } // loop columns for (var k = 0; k < n; k++) { // node k has no parent yet parent[k] = -1; // nor does k have an ancestor w[ancestor + k] = -1; // values in column k for (var p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) { // row var r = aindex[p]; // node i = ata ? w[prev + r] : r; // traverse from i to k for (; i !== -1 && i < k; i = inext) { // inext = ancestor of i inext = w[ancestor + i]; // path compression w[ancestor + i] = k; // check no anc., parent is k if (inext === -1) { parent[i] = k; } } if (ata) { w[prev + r] = k; } } } return parent; }
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 Reference: http://faculty.cse.tamu.edu/davis/publications.html
csEtree
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csPost = function csPost(parent, n) { // check inputs if (!parent) { return null; } // vars var k = 0; var j; // allocate result var post = []; // (n) // workspace, head: first n entries, next: next n entries, stack: last n entries var w = []; // (3 * n) var head = 0; var next = n; var stack = 2 * n; // initialize workspace for (j = 0; j < n; j++) { // empty linked lists w[head + j] = -1; } // traverse nodes in reverse order for (j = n - 1; j >= 0; j--) { // check j is a root if (parent[j] === -1) { continue; } // add j to list of its parent w[next + j] = w[head + parent[j]]; w[head + parent[j]] = j; } // loop nodes for (j = 0; j < n; j++) { // skip j if it is not a root if (parent[j] !== -1) { continue; } // depth-first search k = csTdfs(j, k, w, head, next, post, stack); } return post; }
Post order a tree of forest @param {Array} parent The tree or forest @param {Number} n Number of columns Reference: http://faculty.cse.tamu.edu/davis/publications.html
csPost
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csCounts = function csCounts(a, parent, post, ata) { // check inputs if (!a || !parent || !post) { return null; } // a matrix arrays var asize = a._size; // rows and columns var m = asize[0]; var n = asize[1]; // variables var i, j, k, J, p, p0, p1; // workspace size var s = 4 * n + (ata ? n + m + 1 : 0); // allocate workspace var w = []; // (s) var ancestor = 0; // first n entries var maxfirst = n; // next n entries var prevleaf = 2 * n; // next n entries var first = 3 * n; // next n entries var head = 4 * n; // next n + 1 entries (used when ata is true) var next = 5 * n + 1; // last entries in workspace // clear workspace w[0..s-1] for (k = 0; k < s; k++) { w[k] = -1; } // allocate result var colcount = []; // (n) // AT = A' var at = transpose(a); // at arrays var tindex = at._index; var tptr = at._ptr; // find w[first + j] for (k = 0; k < n; k++) { j = post[k]; // colcount[j]=1 if j is a leaf colcount[j] = w[first + j] === -1 ? 1 : 0; for (; j !== -1 && w[first + j] === -1; j = parent[j]) { w[first + j] = k; } } // initialize ata if needed if (ata) { // invert post for (k = 0; k < n; k++) { w[post[k]] = k; } // loop rows (columns in AT) for (i = 0; i < m; i++) { // values in column i of AT for (k = n, p0 = tptr[i], p1 = tptr[i + 1], p = p0; p < p1; p++) { k = Math.min(k, w[tindex[p]]); } // place row i in linked list k w[next + i] = w[head + k]; w[head + k] = i; } } // each node in its own set for (i = 0; i < n; i++) { w[ancestor + i] = i; } for (k = 0; k < n; k++) { // j is the kth node in postordered etree j = post[k]; // check j is not a root if (parent[j] !== -1) { colcount[parent[j]]--; } // J=j for LL'=A case for (J = ata ? w[head + k] : j; J !== -1; J = ata ? w[next + J] : -1) { for (p = tptr[J]; p < tptr[J + 1]; p++) { i = tindex[p]; var r = csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor); // check A(i,j) is in skeleton if (r.jleaf >= 1) { colcount[j]++; } // check account for overlap in q if (r.jleaf === 2) { colcount[r.q]--; } } } if (parent[j] !== -1) { w[ancestor + j] = parent[j]; } } // sum up colcount's of each child for (j = 0; j < n; j++) { if (parent[j] !== -1) { colcount[parent[j]] += colcount[j]; } } return colcount; }
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 Reference: http://faculty.cse.tamu.edu/davis/publications.html
csCounts
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csLeaf = function csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor) { var s, sparent, jprev; // our result var jleaf = 0; var q; // check j is a leaf if (i <= j || w[first + j] <= w[maxfirst + i]) { return -1; } // update max first[j] seen so far w[maxfirst + i] = w[first + j]; // jprev = previous leaf of ith subtree 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: jleaf, q: q }; }
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} Reference: http://faculty.cse.tamu.edu/davis/publications.html
csLeaf
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csLu = function csLu(m, s, tol) { // validate input if (!m) { return null; } // m arrays var size = m._size; // columns var n = size[1]; // symbolic analysis result var q; var lnz = 100; var unz = 100; // update symbolic analysis parameters if (s) { q = s.q; lnz = s.lnz || lnz; unz = s.unz || unz; } // L arrays var lvalues = []; // (lnz) var lindex = []; // (lnz) var lptr = []; // (n + 1) // L var L = new SparseMatrix({ values: lvalues, index: lindex, ptr: lptr, size: [n, n] }); // U arrays var uvalues = []; // (unz) var uindex = []; // (unz) var uptr = []; // (n + 1) // U var U = new SparseMatrix({ values: uvalues, index: uindex, ptr: uptr, size: [n, n] }); // inverse of permutation vector var pinv = []; // (n) // vars var i, p; // allocate arrays var x = []; // (n) var xi = []; // (2 * n) // initialize variables for (i = 0; i < n; i++) { // clear workspace x[i] = 0; // no rows pivotal yet pinv[i] = -1; // no cols of L yet lptr[i + 1] = 0; } // reset number of nonzero elements in L and U lnz = 0; unz = 0; // compute L(:,k) and U(:,k) for (var k = 0; k < n; k++) { // update ptr lptr[k] = lnz; uptr[k] = unz; // apply column permutations if needed var col = q ? q[k] : k; // solve triangular system, x = L\A(:,col) var top = csSpsolve(L, m, col, xi, x, pinv, 1); // find pivot var ipiv = -1; var a = -1; // loop xi[] from top -> n for (p = top; p < n; p++) { // x[i] is nonzero i = xi[p]; // check row i is not yet pivotal if (pinv[i] < 0) { // absolute value of x[i] var xabs = abs(x[i]); // check absoulte value is greater than pivot value if (larger(xabs, a)) { // largest pivot candidate so far a = xabs; ipiv = i; } } else { // x(i) is the entry U(pinv[i],k) uindex[unz] = pinv[i]; uvalues[unz++] = x[i]; } } // validate we found a valid pivot if (ipiv === -1 || a <= 0) { return null; } // update actual pivot column, give preference to diagonal value if (pinv[col] < 0 && largerEq(abs(x[col]), multiply(a, tol))) { ipiv = col; } // the chosen pivot var pivot = x[ipiv]; // last entry in U(:,k) is U(k,k) uindex[unz] = k; uvalues[unz++] = pivot; // ipiv is the kth pivot row pinv[ipiv] = k; // first entry in L(:,k) is L(k,k) = 1 lindex[lnz] = ipiv; lvalues[lnz++] = 1; // L(k+1:n,k) = x / pivot for (p = top; p < n; p++) { // row i = xi[p]; // check x(i) is an entry in L(:,k) if (pinv[i] < 0) { // save unpermuted row in L lindex[lnz] = i; // scale pivot column lvalues[lnz++] = divideScalar(x[i], pivot); } // x[0..n-1] = 0 for next k x[i] = 0; } } // update ptr lptr[n] = lnz; uptr[n] = unz; // fix row indices of L for final pinv for (p = 0; p < lnz; p++) { lindex[p] = pinv[lindex[p]]; } // trim arrays lvalues.splice(lnz, lvalues.length - lnz); lindex.splice(lnz, lindex.length - lnz); uvalues.splice(unz, uvalues.length - unz); uindex.splice(unz, uindex.length - unz); // return LU factor return { L: L, U: U, pinv: pinv }; }
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 Reference: http://faculty.cse.tamu.edu/davis/publications.html
csLu
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csSpsolve = function csSpsolve(g, b, k, xi, x, pinv, lo) { // g arrays var gvalues = g._values; var gindex = g._index; var gptr = g._ptr; var gsize = g._size; // columns var n = gsize[1]; // b arrays var bvalues = b._values; var bindex = b._index; var bptr = b._ptr; // vars var p, p0, p1, q; // xi[top..n-1] = csReach(B(:,k)) var top = csReach(g, b, k, xi, pinv); // clear x for (p = top; p < n; p++) { x[xi[p]] = 0; } // scatter b for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) { x[bindex[p]] = bvalues[p]; } // loop columns for (var px = top; px < n; px++) { // x array index for px var j = xi[px]; // apply permutation vector (U x = b), j maps to column J of G var J = pinv ? pinv[j] : j; // check column J is empty if (J < 0) { continue; } // column value indeces in G, p0 <= p < p1 p0 = gptr[J]; p1 = gptr[J + 1]; // x(j) /= G(j,j) x[j] = divideScalar(x[j], gvalues[lo ? p0 : p1 - 1]); // first entry L(j,j) p = lo ? p0 + 1 : p0; q = lo ? p1 : p1 - 1; // loop for (; p < q; p++) { // row var i = gindex[p]; // x(i) -= G(i,j) * x(j) x[i] = subtract(x[i], multiply(gvalues[p], x[j])); } } // return top of stack return top; }
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 Reference: http://faculty.cse.tamu.edu/davis/publications.html
csSpsolve
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csReach = function csReach(g, b, k, xi, pinv) { // g arrays var gptr = g._ptr; var gsize = g._size; // b arrays var bindex = b._index; var bptr = b._ptr; // columns var n = gsize[1]; // vars var p, p0, p1; // initialize top var top = n; // loop column indeces in B for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) { // node i var i = bindex[p]; // check node i is marked if (!csMarked(gptr, i)) { // start a dfs at unmarked node i top = csDfs(i, g, top, xi, pinv); } } // loop columns from top -> n - 1 for (p = top; p < n; p++) { // restore G csMark(gptr, xi[p]); } return top; }
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 Reference: http://faculty.cse.tamu.edu/davis/publications.html
csReach
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csDfs = function csDfs(j, g, top, xi, pinv) { // g arrays var index = g._index; var ptr = g._ptr; var size = g._size; // columns var n = size[1]; // vars var i, p, p2; // initialize head var head = 0; // initialize the recursion stack xi[0] = j; // loop while (head >= 0) { // get j from the top of the recursion stack j = xi[head]; // apply permutation vector var jnew = pinv ? pinv[j] : j; // check node j is marked if (!csMarked(ptr, j)) { // mark node j as visited csMark(ptr, j); // update stack (last n entries in xi) xi[n + head] = jnew < 0 ? 0 : csUnflip(ptr[jnew]); } // node j done if no unvisited neighbors var done = 1; // examine all neighbors of j, stack (last n entries in xi) for (p = xi[n + head], p2 = jnew < 0 ? 0 : csUnflip(ptr[jnew + 1]); p < p2; p++) { // consider neighbor node i i = index[p]; // check we have visited node i, skip it if (csMarked(ptr, i)) { continue; } // pause depth-first search of node j, update stack (last n entries in xi) xi[n + head] = p; // start dfs at node i xi[++head] = i; // node j is not done done = 0; // break, to start dfs(i) break; } // check depth-first search at node j is done if (done) { // remove j from the recursion stack head--; // and place in the output stack xi[--top] = j; } } return top; }
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 Reference: http://faculty.cse.tamu.edu/davis/publications.html
csDfs
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csUnflip = function csUnflip(i) { // flip the value if it is negative return i < 0 ? csFlip(i) : i; }
Flips the value if it is negative of returns the same value otherwise. @param {Number} i The value to flip Reference: http://faculty.cse.tamu.edu/davis/publications.html
csUnflip
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_toMatrix = function _toMatrix(a) { // check it is a matrix if (type.isMatrix(a)) { return a; } // check array if (isArray(a)) { return matrix(a); } // throw throw new TypeError('Invalid Matrix LU decomposition'); }
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
_toMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _lusolve(l, u, p, q, b) { // verify L, U, P l = _toMatrix(l); u = _toMatrix(u); // validate matrix and vector b = solveValidation(l, b, false); // apply row permutations if needed (b is a DenseMatrix) if (p) { b._data = csIpvec(p, b._data); } // use forward substitution to resolve L * y = b var y = lsolve(l, b); // use backward substitution to resolve U * x = y var x = usolve(u, y); // apply column permutations if needed (x is a DenseMatrix) if (q) { x._data = csIpvec(q, x._data); } // return solution return x; }
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
_lusolve
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function csIpvec(p, b) { // vars var k; var n = b.length; var x = []; // check permutation vector was provided, p = null denotes identity if (p) { // loop vector for (k = 0; k < n; k++) { // apply permutation x[p[k]] = b[k]; } } else { // loop vector for (k = 0; k < n; k++) { // x[i] = b[i] x[k] = b[k]; } } return x; }
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
csIpvec
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _cbrtComplex(x, allRoots) { // https://www.wikiwand.com/en/Cube_root#/Complex_numbers var arg3 = x.arg() / 3; var abs = x.abs(); // principal root: var principal = new type.Complex(_cbrtNumber(abs), 0).mul(new type.Complex(0, arg3).exp()); if (allRoots) { var all = [principal, new type.Complex(_cbrtNumber(abs), 0).mul(new type.Complex(0, arg3 + Math.PI * 2 / 3).exp()), new type.Complex(_cbrtNumber(abs), 0).mul(new type.Complex(0, arg3 - Math.PI * 2 / 3).exp())]; return config.matrix === 'Array' ? all : matrix(all); } else { return principal; } }
Calculate the cubic root for a complex number @param {Complex} x @param {boolean} [allRoots] If true, the function will return an array with all three roots. If false or undefined, the principal root is returned. @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x @private
_cbrtComplex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _cbrtUnit(x) { if (x.value && type.isComplex(x.value)) { var result = x.clone(); result.value = 1.0; result = result.pow(1.0 / 3); // Compute the units result.value = _cbrtComplex(x.value); // Compute the value return result; } else { var negate = isNegative(x.value); if (negate) { x.value = unaryMinus(x.value); } // TODO: create a helper function for this var third; if (type.isBigNumber(x.value)) { third = new type.BigNumber(1).div(3); } else if (type.isFraction(x.value)) { third = new type.Fraction(1, 3); } else { third = 1 / 3; } var _result = x.pow(third); if (negate) { _result.value = unaryMinus(_result.value); } return _result; } }
Calculate the cubic root for a Unit @param {Unit} x @return {Unit} Returns the cubic root of x @private
_cbrtUnit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _expm1(x) { return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6; }
Calculates exponentiation minus 1. @param {number} x @return {number} res @private
_expm1
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _gcdBigNumber(a, b) { if (!a.isInt() || !b.isInt()) { throw new Error('Parameters in function gcd must be integer numbers'); } // https://en.wikipedia.org/wiki/Euclidean_algorithm var zero = new type.BigNumber(0); while (!b.isZero()) { var r = a.mod(b); a = b; b = r; } return a.lt(zero) ? a.neg() : a; }
Calculate gcd for BigNumbers @param {BigNumber} a @param {BigNumber} b @returns {BigNumber} Returns greatest common denominator of a and b @private
_gcdBigNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _gcd(a, b) { if (!isInteger(a) || !isInteger(b)) { throw new Error('Parameters in function gcd must be integer numbers'); } // https://en.wikipedia.org/wiki/Euclidean_algorithm var r; while (b !== 0) { r = a % b; a = b; b = r; } return a < 0 ? -a : a; }
Calculate gcd for numbers @param {number} a @param {number} b @returns {number} Returns the greatest common denominator of a and b @private
_gcd
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _hypot(args) { // code based on `hypot` from es6-shim: // https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633 var result = 0; var largest = 0; for (var i = 0; i < args.length; i++) { var value = abs(args[i]); if (smaller(largest, value)) { result = multiply(result, multiply(divide(largest, value), divide(largest, value))); result = add(result, 1); largest = value; } else { result = add(result, isPositive(value) ? multiply(divide(value, largest), divide(value, largest)) : value); } } return multiply(largest, sqrt(result)); }
Calculate the hypotenusa for an Array with values @param {Array.<number | BigNumber>} args @return {number | BigNumber} Returns the result @private
_hypot
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _lcmBigNumber(a, b) { if (!a.isInt() || !b.isInt()) { throw new Error('Parameters in function lcm must be integer numbers'); } if (a.isZero() || b.isZero()) { return new type.BigNumber(0); } // https://en.wikipedia.org/wiki/Euclidean_algorithm // evaluate lcm here inline to reduce overhead var prod = a.times(b); while (!b.isZero()) { var t = b; b = a.mod(t); a = t; } return prod.div(a).abs(); }
Calculate lcm for two BigNumbers @param {BigNumber} a @param {BigNumber} b @returns {BigNumber} Returns the least common multiple of a and b @private
_lcmBigNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _lcm(a, b) { if (!isInteger(a) || !isInteger(b)) { throw new Error('Parameters in function lcm must be integer numbers'); } if (a === 0 || b === 0) { return 0; } // https://en.wikipedia.org/wiki/Euclidean_algorithm // evaluate lcm here inline to reduce overhead var t; var prod = a * b; while (b !== 0) { t = b; b = a % t; a = t; } return Math.abs(prod / a); }
Calculate lcm for two numbers @param {number} a @param {number} b @returns {number} Returns the least common multiple of a and b @private
_lcm
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _log1pNumber(x) { if (x >= -1 || config.predictable) { return Math.log1p ? Math.log1p(x) : Math.log(x + 1); } else { // negative value -> complex value computation return _log1pComplex(new type.Complex(x, 0)); } }
Calculate the natural logarithm of a `number+1` @param {number} x @returns {number | Complex} @private
_log1pNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _log1pComplex(x) { var xRe1p = x.re + 1; return new type.Complex(Math.log(Math.sqrt(xRe1p * xRe1p + x.im * x.im)), Math.atan2(x.im, xRe1p)); }
Calculate the natural logarithm of a complex number + 1 @param {Complex} x @returns {Complex} @private
_log1pComplex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _log2Complex(x) { var newX = Math.sqrt(x.re * x.re + x.im * x.im); return new type.Complex(Math.log2 ? Math.log2(newX) : Math.log(newX) / Math.LN2, Math.atan2(x.im, x.re) / Math.LN2); }
Calculate log2 for a complex value @param {Complex} x @returns {Complex} @private
_log2Complex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _mod(x, y) { if (y > 0) { // We don't use JavaScript's % operator here as this doesn't work // correctly for x < 0 and x === 0 // see https://en.wikipedia.org/wiki/Modulo_operation return x - y * Math.floor(x / y); } else if (y === 0) { return x; } else { // y < 0 // TODO: implement mod for a negative divisor throw new Error('Cannot calculate mod for a negative divisor'); } }
Calculate the modulus of two numbers @param {number} x @param {number} y @returns {number} res @private
_mod
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _norm(x, p) { // size var sizeX = x.size(); // check if it is a vector if (sizeX.length === 1) { // check p if (p === Number.POSITIVE_INFINITY || p === 'inf') { // norm(x, Infinity) = max(abs(x)) var pinf = 0; // skip zeros since abs(0) === 0 x.forEach(function (value) { var v = abs(value); if (larger(v, pinf)) { pinf = v; } }, true); return pinf; } if (p === Number.NEGATIVE_INFINITY || p === '-inf') { // norm(x, -Infinity) = min(abs(x)) var ninf; // skip zeros since abs(0) === 0 x.forEach(function (value) { var v = abs(value); if (!ninf || smaller(v, ninf)) { ninf = v; } }, true); return ninf || 0; } if (p === 'fro') { return _norm(x, 2); } if (typeof p === 'number' && !isNaN(p)) { // check p != 0 if (!equalScalar(p, 0)) { // norm(x, p) = sum(abs(xi) ^ p) ^ 1/p var n = 0; // skip zeros since abs(0) === 0 x.forEach(function (value) { n = add(pow(abs(value), p), n); }, true); return pow(n, 1 / p); } return Number.POSITIVE_INFINITY; } // invalid parameter value throw new Error('Unsupported parameter value'); } // MxN matrix if (sizeX.length === 2) { // check p if (p === 1) { // norm(x) = the largest column sum var c = []; // result var maxc = 0; // skip zeros since abs(0) == 0 x.forEach(function (value, index) { var j = index[1]; var cj = add(c[j] || 0, abs(value)); if (larger(cj, maxc)) { maxc = cj; } c[j] = cj; }, true); return maxc; } if (p === Number.POSITIVE_INFINITY || p === 'inf') { // norm(x) = the largest row sum var r = []; // result var maxr = 0; // skip zeros since abs(0) == 0 x.forEach(function (value, index) { var i = index[0]; var ri = add(r[i] || 0, abs(value)); if (larger(ri, maxr)) { maxr = ri; } r[i] = ri; }, true); return maxr; } if (p === 'fro') { // norm(x) = sqrt(sum(diag(x'x))) var fro = 0; x.forEach(function (value, index) { fro = add(fro, multiply(value, conj(value))); }); return abs(sqrt(fro)); } if (p === 2) { // not implemented throw new Error('Unsupported parameter value, missing implementation of matrix singular value decomposition'); } // invalid parameter value throw new Error('Unsupported parameter value'); } }
Calculate the norm for an array @param {Matrix} x @param {number | string} p @returns {number} Returns the norm @private
_norm
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _bigNthRoot(a, root) { var precision = type.BigNumber.precision; var Big = type.BigNumber.clone({ precision: precision + 2 }); var zero = new type.BigNumber(0); var one = new Big(1); var inv = root.isNegative(); if (inv) { root = root.neg(); } if (root.isZero()) { throw new Error('Root must be non-zero'); } if (a.isNegative() && !root.abs().mod(2).equals(1)) { throw new Error('Root must be odd when a is negative.'); } // edge cases zero and infinity if (a.isZero()) { return inv ? new Big(Infinity) : 0; } if (!a.isFinite()) { return inv ? zero : a; } var x = a.abs().pow(one.div(root)); // If a < 0, we require that root is an odd integer, // so (-1) ^ (1/root) = -1 x = a.isNeg() ? x.neg() : x; return new type.BigNumber((inv ? one.div(x) : x).toPrecision(precision)); }
Calculate the nth root of a for BigNumbers, solve x^root == a https://rosettacode.org/wiki/Nth_root#JavaScript @param {BigNumber} a @param {BigNumber} root @private
_bigNthRoot
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _nthRoot(a, root) { var inv = root < 0; if (inv) { root = -root; } if (root === 0) { throw new Error('Root must be non-zero'); } if (a < 0 && Math.abs(root) % 2 !== 1) { throw new Error('Root must be odd when a is negative.'); } // edge cases zero and infinity if (a === 0) { return inv ? Infinity : 0; } if (!isFinite(a)) { return inv ? 0 : a; } var x = Math.pow(Math.abs(a), 1 / root); // If a < 0, we require that root is an odd integer, // so (-1) ^ (1/root) = -1 x = a < 0 ? -x : x; return inv ? 1 / x : x; // Very nice algorithm, but fails with nthRoot(-2, 3). // Newton's method has some well-known problems at times: // https://en.wikipedia.org/wiki/Newton%27s_method#Failure_analysis /* let x = 1 // Initial guess let xPrev = 1 let i = 0 const iMax = 10000 do { const delta = (a / Math.pow(x, root - 1) - x) / root xPrev = x x = x + delta i++ } while (xPrev !== x && i < iMax) if (xPrev !== x) { throw new Error('Function nthRoot failed to converge') } return inv ? 1 / x : x */ }
Calculate the nth root of a, solve x^root == a https://rosettacode.org/wiki/Nth_root#JavaScript @param {number} a @param {number} root @private
_nthRoot
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT