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 parseImplicitMultiplication(state) { var node, last, previous; node = parseRule2(state); last = node; previous = last; while (true) { if (state.tokenType === TOKENTYPE.SYMBOL || state.token === 'in' && type.isConstantNode(node) || state.tokenType === TOKENTYPE.NUMBER && !type.isConstantNode(last) && (!type.isOperatorNode(last) || last.op === '!') || state.token === '(') { // parse implicit multiplication // // symbol: implicit multiplication like '2a', '(2+3)a' // number: implicit multiplication like '(2+3)2' // parenthesis: implicit multiplication like '2(3+4)', '(3+4)(1+2)' // // or join space separated symbols like 'a b' and 'a 1' last = parseRule2(state); if (previous instanceof SymbolNode && previous.name !== 'i' && last instanceof SymbolNode && last.name !== 'i') { previous.name += ' ' + last.name; } else if (previous instanceof SymbolNode && previous.name !== 'i' && last instanceof ConstantNode) { previous.name += ' ' + last.value; } else { node = new OperatorNode('*', 'multiply', [node, last], true /* implicit */ ); previous = last; } } else { break; } } return node; }
implicit multiplication @return {Node} node @private
parseImplicitMultiplication
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseRule2(state) { var node = parseUnary(state); var last = node; var tokenStates = []; while (true) { // Match the "number /" part of the pattern "number / number symbol" if (state.token === '/' && type.isConstantNode(last)) { // Look ahead to see if the next token is a number tokenStates.push(_extends({}, state)); getTokenSkipNewline(state); // Match the "number / number" part of the pattern if (state.tokenType === TOKENTYPE.NUMBER) { // Look ahead again tokenStates.push(_extends({}, state)); getTokenSkipNewline(state); // Match the "symbol" part of the pattern, or a left parenthesis if (state.tokenType === TOKENTYPE.SYMBOL || state.token === '(') { // We've matched the pattern "number / number symbol". // Rewind once and build the "number / number" node; the symbol will be consumed later _extends(state, tokenStates.pop()); tokenStates.pop(); last = parseUnary(state); node = new OperatorNode('/', 'divide', [node, last]); } else { // Not a match, so rewind tokenStates.pop(); _extends(state, tokenStates.pop()); break; } } else { // Not a match, so rewind _extends(state, tokenStates.pop()); break; } } else { break; } } return node; }
Infamous "rule 2" as described in https://github.com/josdejong/mathjs/issues/792#issuecomment-361065370 Explicit division gets higher precedence than implicit multiplication when the division matches this pattern: [number] / [number] [symbol] @return {Node} node @private
parseRule2
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseUnary(state) { var name, params, fn; var operators = { '-': 'unaryMinus', '+': 'unaryPlus', '~': 'bitNot', 'not': 'not' }; if (operators.hasOwnProperty(state.token)) { fn = operators[state.token]; name = state.token; getTokenSkipNewline(state); params = [parseUnary(state)]; return new OperatorNode(name, fn, params); } return parsePow(state); }
Unary plus and minus, and logical and bitwise not @return {Node} node @private
parseUnary
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parsePow(state) { var node, name, fn, params; node = parseLeftHandOperators(state); if (state.token === '^' || state.token === '.^') { name = state.token; fn = name === '^' ? 'pow' : 'dotPow'; getTokenSkipNewline(state); params = [node, parseUnary(state)]; // Go back to unary, we can have '2^-3' node = new OperatorNode(name, fn, params); } return node; }
power Note: power operator is right associative @return {Node} node @private
parsePow
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseLeftHandOperators(state) { var node, operators, name, fn, params; node = parseCustomNodes(state); operators = { '!': 'factorial', '\'': 'ctranspose' }; while (operators.hasOwnProperty(state.token)) { name = state.token; fn = operators[name]; getToken(state); params = [node]; node = new OperatorNode(name, fn, params); node = parseAccessors(state, node); } return node; }
Left hand operators: factorial x!, ctranspose x' @return {Node} node @private
parseLeftHandOperators
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseCustomNodes(state) { var params = []; if (state.tokenType === TOKENTYPE.SYMBOL && state.extraNodes.hasOwnProperty(state.token)) { var CustomNode = state.extraNodes[state.token]; getToken(state); // parse parameters if (state.token === '(') { params = []; openParams(state); getToken(state); if (state.token !== ')') { params.push(parseAssignment(state)); // parse a list with parameters while (state.token === ',') { // eslint-disable-line no-unmodified-loop-condition getToken(state); params.push(parseAssignment(state)); } } if (state.token !== ')') { throw createSyntaxError(state, 'Parenthesis ) expected'); } closeParams(state); getToken(state); } // create a new custom node // noinspection JSValidateTypes return new CustomNode(params); } return parseSymbol(state); }
Parse a custom node handler. A node handler can be used to process nodes in a custom way, for example for handling a plot. A handler must be passed as second argument of the parse function. - must extend math.expression.node.Node - must contain a function _compile(defs: Object) : string - must contain a function find(filter: Object) : Node[] - must contain a function toString() : string - the constructor is called with a single argument containing all parameters For example: nodes = { 'plot': PlotHandler } The constructor of the handler is called as: node = new PlotHandler(params) The handler will be invoked when evaluating an expression like: node = math.parse('plot(sin(x), x)', nodes) @return {Node} node @private
parseCustomNodes
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseSymbol(state) { var node, name; if (state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS) { name = state.token; getToken(state); if (CONSTANTS.hasOwnProperty(name)) { // true, false, null, ... node = new ConstantNode(CONSTANTS[name]); } else if (NUMERIC_CONSTANTS.indexOf(name) !== -1) { // NaN, Infinity node = new ConstantNode(numeric(name, 'number')); } else { node = new SymbolNode(name); } // parse function parameters and matrix index node = parseAccessors(state, node); return node; } return parseDoubleQuotesString(state); }
parse symbols: functions, variables, constants, units @return {Node} node @private
parseSymbol
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseAccessors(state, node, types) { var params; while ((state.token === '(' || state.token === '[' || state.token === '.') && (!types || types.indexOf(state.token) !== -1)) { // eslint-disable-line no-unmodified-loop-condition params = []; if (state.token === '(') { if (type.isSymbolNode(node) || type.isAccessorNode(node)) { // function invocation like fn(2, 3) or obj.fn(2, 3) openParams(state); getToken(state); if (state.token !== ')') { params.push(parseAssignment(state)); // parse a list with parameters while (state.token === ',') { // eslint-disable-line no-unmodified-loop-condition getToken(state); params.push(parseAssignment(state)); } } if (state.token !== ')') { throw createSyntaxError(state, 'Parenthesis ) expected'); } closeParams(state); getToken(state); node = new FunctionNode(node, params); } else { // implicit multiplication like (2+3)(4+5) or sqrt(2)(1+2) // don't parse it here but let it be handled by parseImplicitMultiplication // with correct precedence return node; } } else if (state.token === '[') { // index notation like variable[2, 3] openParams(state); getToken(state); if (state.token !== ']') { params.push(parseAssignment(state)); // parse a list with parameters while (state.token === ',') { // eslint-disable-line no-unmodified-loop-condition getToken(state); params.push(parseAssignment(state)); } } if (state.token !== ']') { throw createSyntaxError(state, 'Parenthesis ] expected'); } closeParams(state); getToken(state); node = new AccessorNode(node, new IndexNode(params)); } else { // dot notation like variable.prop getToken(state); if (state.tokenType !== TOKENTYPE.SYMBOL) { throw createSyntaxError(state, 'Property name expected after dot'); } params.push(new ConstantNode(state.token)); getToken(state); var dotNotation = true; node = new AccessorNode(node, new IndexNode(params, dotNotation)); } } return node; }
parse accessors: - function invocation in round brackets (...), for example sqrt(2) - index enclosed in square brackets [...], for example A[2,3] - dot notation for properties, like foo.bar @param {Node} node Node on which to apply the parameters. If there are no parameters in the expression, the node itself is returned @param {string[]} [types] Filter the types of notations can be ['(', '[', '.'] @return {Node} node @private
parseAccessors
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseDoubleQuotesString(state) { var node, str; if (state.token === '"') { str = parseDoubleQuotesStringToken(state); // create constant node = new ConstantNode(str); // parse index parameters node = parseAccessors(state, node); return node; } return parseSingleQuotesString(state); }
Parse a double quotes string. @return {Node} node @private
parseDoubleQuotesString
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseDoubleQuotesStringToken(state) { var str = ''; while (currentCharacter(state) !== '' && currentCharacter(state) !== '"') { if (currentCharacter(state) === '\\') { // escape character, immediately process the next // character to prevent stopping at a next '\"' str += currentCharacter(state); next(state); } str += currentCharacter(state); next(state); } getToken(state); if (state.token !== '"') { throw createSyntaxError(state, 'End of string " expected'); } getToken(state); return JSON.parse('"' + str + '"'); // unescape escaped characters }
Parse a string surrounded by double quotes "..." @return {string}
parseDoubleQuotesStringToken
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseSingleQuotesString(state) { var node, str; if (state.token === '\'') { str = parseSingleQuotesStringToken(state); // create constant node = new ConstantNode(str); // parse index parameters node = parseAccessors(state, node); return node; } return parseMatrix(state); }
Parse a single quotes string. @return {Node} node @private
parseSingleQuotesString
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseSingleQuotesStringToken(state) { var str = ''; while (currentCharacter(state) !== '' && currentCharacter(state) !== '\'') { if (currentCharacter(state) === '\\') { // escape character, immediately process the next // character to prevent stopping at a next '\'' str += currentCharacter(state); next(state); } str += currentCharacter(state); next(state); } getToken(state); if (state.token !== '\'') { throw createSyntaxError(state, 'End of string \' expected'); } getToken(state); return JSON.parse('"' + str + '"'); // unescape escaped characters }
Parse a string surrounded by single quotes '...' @return {string}
parseSingleQuotesStringToken
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseMatrix(state) { var array, params, rows, cols; if (state.token === '[') { // matrix [...] openParams(state); getToken(state); if (state.token !== ']') { // this is a non-empty matrix var row = parseRow(state); if (state.token === ';') { // 2 dimensional array rows = 1; params = [row]; // the rows of the matrix are separated by dot-comma's while (state.token === ';') { // eslint-disable-line no-unmodified-loop-condition getToken(state); params[rows] = parseRow(state); rows++; } if (state.token !== ']') { throw createSyntaxError(state, 'End of matrix ] expected'); } closeParams(state); getToken(state); // check if the number of columns matches in all rows cols = params[0].items.length; for (var r = 1; r < rows; r++) { if (params[r].items.length !== cols) { throw createError(state, 'Column dimensions mismatch ' + '(' + params[r].items.length + ' !== ' + cols + ')'); } } array = new ArrayNode(params); } else { // 1 dimensional vector if (state.token !== ']') { throw createSyntaxError(state, 'End of matrix ] expected'); } closeParams(state); getToken(state); array = row; } } else { // this is an empty matrix "[ ]" closeParams(state); getToken(state); array = new ArrayNode([]); } return parseAccessors(state, array); } return parseObject(state); }
parse the matrix @return {Node} node @private
parseMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseRow(state) { var params = [parseAssignment(state)]; var len = 1; while (state.token === ',') { // eslint-disable-line no-unmodified-loop-condition getToken(state); // parse expression params[len] = parseAssignment(state); len++; } return new ArrayNode(params); }
Parse a single comma-separated row from a matrix, like 'a, b, c' @return {ArrayNode} node
parseRow
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseObject(state) { if (state.token === '{') { openParams(state); var key; var properties = {}; do { getToken(state); if (state.token !== '}') { // parse key if (state.token === '"') { key = parseDoubleQuotesStringToken(state); } else if (state.token === '\'') { key = parseSingleQuotesStringToken(state); } else if (state.tokenType === TOKENTYPE.SYMBOL) { key = state.token; getToken(state); } else { throw createSyntaxError(state, 'Symbol or string expected as object key'); } // parse key/value separator if (state.token !== ':') { throw createSyntaxError(state, 'Colon : expected after object key'); } getToken(state); // parse key properties[key] = parseAssignment(state); } } while (state.token === ','); // eslint-disable-line no-unmodified-loop-condition if (state.token !== '}') { throw createSyntaxError(state, 'Comma , or bracket } expected after object value'); } closeParams(state); getToken(state); var node = new ObjectNode(properties); // parse index parameters node = parseAccessors(state, node); return node; } return parseNumber(state); }
parse an object, enclosed in angle brackets{...}, for example {value: 2} @return {Node} node @private
parseObject
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseNumber(state) { var numberStr; if (state.tokenType === TOKENTYPE.NUMBER) { // this is a number numberStr = state.token; getToken(state); return new ConstantNode(numeric(numberStr, config.number)); } return parseParentheses(state); }
parse a number @return {Node} node @private
parseNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseEnd(state) { if (state.token === '') { // syntax error or unexpected end of expression throw createSyntaxError(state, 'Unexpected end of expression'); } else { throw createSyntaxError(state, 'Value expected'); } }
Evaluated when the expression is not yet ended but expected to end @return {Node} res @private
parseEnd
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function col(state) { return state.index - state.token.length + 1; }
Shortcut for getting the current col value (one based) Returns the column (position) where the last state.token starts @private
col
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createSyntaxError(state, message) { var c = col(state); var error = new SyntaxError(message + ' (char ' + c + ')'); error['char'] = c; return error; }
Create an error @param {string} message @return {SyntaxError} instantiated error @private
createSyntaxError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createError(state, message) { var c = col(state); var error = new SyntaxError(message + ' (char ' + c + ')'); error['char'] = c; return error; }
Create an error @param {string} message @return {Error} instantiated error @private
createError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sqrtNumber(x) { if (isNaN(x)) { return NaN; } else if (x >= 0 || config.predictable) { return Math.sqrt(x); } else { return new type.Complex(x, 0).sqrt(); } }
Calculate sqrt for a number @param {number} x @returns {number | Complex} Returns the square root of x @private
_sqrtNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function IndexError(index, min, max) { if (!(this instanceof IndexError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.index = index; if (arguments.length < 3) { this.min = 0; this.max = min; } else { this.min = min; this.max = max; } if (this.min !== undefined && this.index < this.min) { this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')'; } else if (this.max !== undefined && this.index >= this.max) { this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')'; } else { this.message = 'Index out of range (' + this.index + ')'; } this.stack = new Error().stack; }
Create a range error with the message: 'Index out of range (index < min)' 'Index out of range (index < max)' @param {number} index The actual index @param {number} [min=0] Minimum index (included) @param {number} [max] Maximum index (excluded) @extends RangeError
IndexError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function DenseMatrix(data, datatype) { if (!(this instanceof DenseMatrix)) { 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)) { // check data is a DenseMatrix if (data.type === 'DenseMatrix') { // clone data & size this._data = object.clone(data._data); this._size = object.clone(data._size); this._datatype = datatype || data._datatype; } else { // build data from existing matrix this._data = data.toArray(); this._size = data.size(); this._datatype = datatype || data._datatype; } } else if (data && isArray(data.data) && isArray(data.size)) { // initialize fields from JSON representation this._data = data.data; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // replace nested Matrices with Arrays this._data = preprocess(data); // get the dimensions of the array this._size = array.size(this._data); // verify the dimensions of the array, TODO: compute size while processing array array.validate(this._data, this._size); // data type unknown this._datatype = datatype; } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._data = []; this._size = [0]; this._datatype = datatype; } }
Dense Matrix implementation. A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type. @class DenseMatrix
DenseMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _get(matrix, index) { if (!type.isIndex(index)) { throw new TypeError('Invalid index'); } var isScalar = index.isScalar(); if (isScalar) { // return a scalar return matrix.get(index.min()); } else { // validate dimensions var size = index.size(); if (size.length !== matrix._size.length) { throw new DimensionError(size.length, matrix._size.length); } // validate if any of the ranges in the index is out of range var min = index.min(); var max = index.max(); for (var i = 0, ii = matrix._size.length; i < ii; i++) { validateIndex(min[i], matrix._size[i]); validateIndex(max[i], matrix._size[i]); } // retrieve submatrix // TODO: more efficient when creating an empty matrix and setting _data and _size manually return new DenseMatrix(_getSubmatrix(matrix._data, index, size.length, 0), matrix._datatype); } }
Get a submatrix of this matrix @memberof DenseMatrix @param {DenseMatrix} matrix @param {Index} index Zero-based index @private
_get
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _getSubmatrix(data, index, dims, dim) { var last = dim === dims - 1; var range = index.dimension(dim); if (last) { return range.map(function (i) { validateIndex(i, data.length); return data[i]; }).valueOf(); } else { return range.map(function (i) { validateIndex(i, data.length); var child = data[i]; return _getSubmatrix(child, index, dims, dim + 1); }).valueOf(); } }
Recursively get a submatrix of a multi dimensional matrix. Index is not checked for correct number or length of dimensions. @memberof DenseMatrix @param {Array} data @param {Index} index @param {number} dims Total number of dimensions @param {number} dim Current dimension @return {Array} submatrix @private
_getSubmatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _set(matrix, index, submatrix, defaultValue) { 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)) { sSize = submatrix.size(); submatrix = submatrix.valueOf(); } else { sSize = array.size(submatrix); } if (isScalar) { // set a scalar // check whether submatrix is a scalar if (sSize.length !== 0) { throw new TypeError('Scalar expected'); } matrix.set(index.min(), submatrix, defaultValue); } else { // set a submatrix // validate dimensions if (iSize.length < matrix._size.length) { throw new DimensionError(iSize.length, matrix._size.length, '<'); } 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, '>'); } // enlarge matrix when needed var size = index.max().map(function (i) { return i + 1; }); _fit(matrix, size, defaultValue); // insert the sub matrix var dims = iSize.length; var dim = 0; _setSubmatrix(matrix._data, index, submatrix, dims, dim); } return matrix; }
Replace a submatrix in this matrix Indexes are zero-based. @memberof DenseMatrix @param {DenseMatrix} matrix @param {Index} index @param {DenseMatrix | Array | *} submatrix @param {*} defaultValue Default value, filled in on new entries when the matrix is resized. @return {DenseMatrix} matrix @private
_set
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _setSubmatrix(data, index, submatrix, dims, dim) { var last = dim === dims - 1; var range = index.dimension(dim); if (last) { range.forEach(function (dataIndex, subIndex) { validateIndex(dataIndex); data[dataIndex] = submatrix[subIndex[0]]; }); } else { range.forEach(function (dataIndex, subIndex) { validateIndex(dataIndex); _setSubmatrix(data[dataIndex], index, submatrix[subIndex[0]], dims, dim + 1); }); } }
Replace a submatrix of a multi dimensional matrix. @memberof DenseMatrix @param {Array} data @param {Index} index @param {Array} submatrix @param {number} dims Total number of dimensions @param {number} dim @private
_setSubmatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _resize(matrix, size, defaultValue) { // check size if (size.length === 0) { // first value in matrix var v = matrix._data; // go deep while (isArray(v)) { v = v[0]; } return v; } // resize matrix matrix._size = size.slice(0); // copy the array matrix._data = array.resize(matrix._data, matrix._size, defaultValue); // 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 DenseMatrix @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
function _fit(matrix, size, defaultValue) { var // copy the array newSize = matrix._size.slice(0); var changed = false; // add dimensions when needed while (newSize.length < size.length) { newSize.push(0); changed = true; } // enlarge size when needed for (var i = 0, ii = size.length; i < ii; i++) { if (size[i] > newSize[i]) { newSize[i] = size[i]; changed = true; } } if (changed) { // resize only when size is changed _resize(matrix, newSize, defaultValue); } }
Enlarge the matrix when it is smaller than given size. If the matrix is larger or equal sized, nothing is done. @memberof DenseMatrix @param {DenseMatrix} matrix The matrix to be resized @param {number[]} size @param {*} defaultValue Default value, filled in on new entries. @private
_fit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
recurse = function recurse(value, index) { if (isArray(value)) { return value.map(function (child, i) { return recurse(child, index.concat(i)); }); } else { return callback(value, index, me); } }
Create a new matrix with the results of the callback function executed on each entry of the matrix. @memberof DenseMatrix @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. @return {DenseMatrix} matrix
recurse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
recurse = function recurse(value, index) { if (isArray(value)) { value.forEach(function (child, i) { recurse(child, index.concat(i)); }); } else { callback(value, index, me); } }
Execute a callback function on each entry of the matrix. @memberof DenseMatrix @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.
recurse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function preprocess(data) { for (var i = 0, ii = data.length; i < ii; i++) { var elem = data[i]; if (isArray(elem)) { data[i] = preprocess(elem); } else if (elem && elem.isMatrix === true) { data[i] = preprocess(elem.valueOf()); } } return data; } // register this type in the base class Matrix
Preprocess data, which can be an Array or DenseMatrix with nested Arrays and Matrices. Replaces all nested Matrices with Arrays @memberof DenseMatrix @param {Array} data @return {Array} data
preprocess
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _identityVector(size, format) { switch (size.length) { case 0: return format ? matrix(format) : []; case 1: return _identity(size[0], size[0], format); case 2: return _identity(size[0], size[1], format); default: throw new Error('Vector containing two values expected'); } }
Create a 2-dimensional identity matrix with size m x n or n x n. The matrix has ones on the diagonal and zeros elsewhere. Syntax: math.identity(n) math.identity(n, format) math.identity(m, n) math.identity(m, n, format) math.identity([m, n]) math.identity([m, n], format) Examples: math.identity(3) // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]] math.identity(3, 2) // returns [[1, 0], [0, 1], [0, 0]] const A = [[1, 2, 3], [4, 5, 6]] math.identity(math.size(A)) // returns [[1, 0, 0], [0, 1, 0]] See also: diag, ones, zeros, size, range @param {...number | Matrix | Array} size The size for the matrix @param {string} [format] The Matrix storage format @return {Matrix | Array | number} A matrix with ones on the diagonal.
_identityVector
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _identity(rows, cols, format) { // BigNumber constructor with the right precision var Big = type.isBigNumber(rows) || type.isBigNumber(cols) ? type.BigNumber : null; if (type.isBigNumber(rows)) rows = rows.toNumber(); if (type.isBigNumber(cols)) cols = cols.toNumber(); if (!isInteger(rows) || rows < 1) { throw new Error('Parameters in function identity must be positive integers'); } if (!isInteger(cols) || cols < 1) { throw new Error('Parameters in function identity must be positive integers'); } var one = Big ? new type.BigNumber(1) : 1; var defaultValue = Big ? new Big(0) : 0; var size = [rows, cols]; // check we need to return a matrix if (format) { // get matrix storage constructor var F = type.Matrix.storage(format); // create diagonal matrix (use optimized implementation for storage format) return F.diagonal(size, one, 0, defaultValue); } // create and resize array var res = array.resize([], size, defaultValue); // fill in ones on the diagonal var minimum = rows < cols ? rows : cols; // fill diagonal for (var d = 0; d < minimum; d++) { res[d][d] = one; } return res; }
Create an identity matrix @param {number | BigNumber} rows @param {number | BigNumber} cols @param {string} [format] @returns {Matrix} @private
_identity
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function getPrecedence(_node, parenthesis) { var node = _node; if (parenthesis !== 'keep') { // ParenthesisNodes are only ignored when not in 'keep' mode node = _node.getContent(); } var identifier = node.getIdentifier(); for (var i = 0; i < properties.length; i++) { if (identifier in properties[i]) { return i; } } return null; }
Get the precedence of a Node. Higher number for higher precedence, starting with 0. Returns null if the precedence is undefined. @param {Node} @param {string} parenthesis @return {number|null}
getPrecedence
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function getAssociativity(_node, parenthesis) { var node = _node; if (parenthesis !== 'keep') { // ParenthesisNodes are only ignored when not in 'keep' mode node = _node.getContent(); } var identifier = node.getIdentifier(); var index = getPrecedence(node, parenthesis); if (index === null) { // node isn't in the list return null; } var property = properties[index][identifier]; if (property.hasOwnProperty('associativity')) { if (property.associativity === 'left') { return 'left'; } if (property.associativity === 'right') { return 'right'; } // associativity is invalid throw Error('\'' + identifier + '\' has the invalid associativity \'' + property.associativity + '\'.'); } // associativity is undefined return null; }
Get the associativity of an operator (left or right). Returns a string containing 'left' or 'right' or null if the associativity is not defined. @param {Node} @param {string} parenthesis @return {string|null} @throws {Error}
getAssociativity
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isAssociativeWith(nodeA, nodeB, parenthesis) { // ParenthesisNodes are only ignored when not in 'keep' mode var a = parenthesis !== 'keep' ? nodeA.getContent() : nodeA; var b = parenthesis !== 'keep' ? nodeA.getContent() : nodeB; var identifierA = a.getIdentifier(); var identifierB = b.getIdentifier(); var index = getPrecedence(a, parenthesis); if (index === null) { // node isn't in the list return null; } var property = properties[index][identifierA]; if (property.hasOwnProperty('associativeWith') && property.associativeWith instanceof Array) { for (var i = 0; i < property.associativeWith.length; i++) { if (property.associativeWith[i] === identifierB) { return true; } } return false; } // associativeWith is not defined return null; }
Check if an operator is associative with another operator. Returns either true or false or null if not defined. @param {Node} nodeA @param {Node} nodeB @param {string} parenthesis @return {bool|null}
isAssociativeWith
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isValuelessUnit(name) { return type.Unit ? type.Unit.isValuelessUnit(name) : false; }
Check whether some name is a valueless unit like "inch". @param {string} name @return {boolean}
isValuelessUnit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function SymbolNode(name) { if (!(this instanceof SymbolNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); this.name = name; }
@constructor SymbolNode @extends {Node} A symbol node can hold and resolve a symbol @param {string} name @extends {Node}
SymbolNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function undef(name) { throw new Error('Undefined symbol ' + name); }
Throws an error 'Undefined symbol {name}' @param {string} name
undef
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function ArgumentsError(fn, count, min, max) { if (!(this instanceof ArgumentsError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.fn = fn; this.count = count; this.min = min; this.max = max; this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + (max !== undefined && max !== null ? '-' + max : '') + ' expected)'; this.stack = new Error().stack; }
Create a syntax error with the message: 'Wrong number of arguments in function <fn> (<count> provided, <min>-<max> expected)' @param {string} fn Function name @param {number} count Actual argument count @param {number} min Minimum required argument count @param {number} [max] Maximum required argument count @extends Error
ArgumentsError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function ConstantNode(value) { if (!(this instanceof ConstantNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (arguments.length === 2) { // TODO: remove deprecation error some day (created 2018-01-23) throw new SyntaxError('new ConstantNode(valueStr, valueType) is not supported anymore since math v4.0.0. Use new ConstantNode(value) instead, where value is a non-stringified value.'); } this.value = value; }
A ConstantNode holds a constant value like a number or string. Usage: new ConstantNode(2.3) new ConstantNode('hello') @param {*} value Value can be any type (number, BigNumber, string, ...) @constructor ConstantNode @extends {Node}
ConstantNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function OperatorNode(op, fn, args, implicit) { if (!(this instanceof OperatorNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (typeof op !== 'string') { throw new TypeError('string expected for parameter "op"'); } if (typeof fn !== 'string') { throw new TypeError('string expected for parameter "fn"'); } if (!Array.isArray(args) || !args.every(type.isNode)) { throw new TypeError('Array containing Nodes expected for parameter "args"'); } this.implicit = implicit === true; this.op = op; this.fn = fn; this.args = args || []; }
@constructor OperatorNode @extends {Node} An operator with two arguments, like 2+3 @param {string} op Operator name, for example '+' @param {string} fn Function name, for example 'add' @param {Node[]} args Operator arguments @param {boolean} [implicit] Is this an implicit multiplication?
OperatorNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function calculateNecessaryParentheses(root, parenthesis, implicit, args, latex) { // precedence of the root OperatorNode var precedence = operators.getPrecedence(root, parenthesis); var associativity = operators.getAssociativity(root, parenthesis); if (parenthesis === 'all' || args.length > 2 && root.getIdentifier() !== 'OperatorNode:add' && root.getIdentifier() !== 'OperatorNode:multiply') { var parens = args.map(function (arg) { switch (arg.getContent().type) { // Nodes that don't need extra parentheses case 'ArrayNode': case 'ConstantNode': case 'SymbolNode': case 'ParenthesisNode': return false; default: return true; } }); return parens; } var result; switch (args.length) { case 0: result = []; break; case 1: // unary operators // precedence of the operand var operandPrecedence = operators.getPrecedence(args[0], parenthesis); // handle special cases for LaTeX, where some of the parentheses aren't needed if (latex && operandPrecedence !== null) { var operandIdentifier; var rootIdentifier; if (parenthesis === 'keep') { operandIdentifier = args[0].getIdentifier(); rootIdentifier = root.getIdentifier(); } else { // Ignore Parenthesis Nodes when not in 'keep' mode operandIdentifier = args[0].getContent().getIdentifier(); rootIdentifier = root.getContent().getIdentifier(); } if (operators.properties[precedence][rootIdentifier].latexLeftParens === false) { result = [false]; break; } if (operators.properties[operandPrecedence][operandIdentifier].latexParens === false) { result = [false]; break; } } if (operandPrecedence === null) { // if the operand has no defined precedence, no parens are needed result = [false]; break; } if (operandPrecedence <= precedence) { // if the operands precedence is lower, parens are needed result = [true]; break; } // otherwise, no parens needed result = [false]; break; case 2: // binary operators var lhsParens; // left hand side needs parenthesis? // precedence of the left hand side var lhsPrecedence = operators.getPrecedence(args[0], parenthesis); // is the root node associative with the left hand side var assocWithLhs = operators.isAssociativeWith(root, args[0], parenthesis); if (lhsPrecedence === null) { // if the left hand side has no defined precedence, no parens are needed // FunctionNode for example lhsParens = false; } else if (lhsPrecedence === precedence && associativity === 'right' && !assocWithLhs) { // In case of equal precedence, if the root node is left associative // parens are **never** necessary for the left hand side. // If it is right associative however, parens are necessary // if the root node isn't associative with the left hand side lhsParens = true; } else if (lhsPrecedence < precedence) { lhsParens = true; } else { lhsParens = false; } var rhsParens; // right hand side needs parenthesis? // precedence of the right hand side var rhsPrecedence = operators.getPrecedence(args[1], parenthesis); // is the root node associative with the right hand side? var assocWithRhs = operators.isAssociativeWith(root, args[1], parenthesis); if (rhsPrecedence === null) { // if the right hand side has no defined precedence, no parens are needed // FunctionNode for example rhsParens = false; } else if (rhsPrecedence === precedence && associativity === 'left' && !assocWithRhs) { // In case of equal precedence, if the root node is right associative // parens are **never** necessary for the right hand side. // If it is left associative however, parens are necessary // if the root node isn't associative with the right hand side rhsParens = true; } else if (rhsPrecedence < precedence) { rhsParens = true; } else { rhsParens = false; } // handle special cases for LaTeX, where some of the parentheses aren't needed if (latex) { var _rootIdentifier; var lhsIdentifier; var rhsIdentifier; if (parenthesis === 'keep') { _rootIdentifier = root.getIdentifier(); lhsIdentifier = root.args[0].getIdentifier(); rhsIdentifier = root.args[1].getIdentifier(); } else { // Ignore ParenthesisNodes when not in 'keep' mode _rootIdentifier = root.getContent().getIdentifier(); lhsIdentifier = root.args[0].getContent().getIdentifier(); rhsIdentifier = root.args[1].getContent().getIdentifier(); } if (lhsPrecedence !== null) { if (operators.properties[precedence][_rootIdentifier].latexLeftParens === false) { lhsParens = false; } if (operators.properties[lhsPrecedence][lhsIdentifier].latexParens === false) { lhsParens = false; } } if (rhsPrecedence !== null) { if (operators.properties[precedence][_rootIdentifier].latexRightParens === false) { rhsParens = false; } if (operators.properties[rhsPrecedence][rhsIdentifier].latexParens === false) { rhsParens = false; } } } result = [lhsParens, rhsParens]; break; default: if (root.getIdentifier() === 'OperatorNode:add' || root.getIdentifier() === 'OperatorNode:multiply') { result = args.map(function (arg) { var argPrecedence = operators.getPrecedence(arg, parenthesis); var assocWithArg = operators.isAssociativeWith(root, arg, parenthesis); var argAssociativity = operators.getAssociativity(arg, parenthesis); if (argPrecedence === null) { // if the argument has no defined precedence, no parens are needed return false; } else if (precedence === argPrecedence && associativity === argAssociativity && !assocWithArg) { return true; } else if (argPrecedence < precedence) { return true; } return false; }); } break; } // handles an edge case of 'auto' parentheses with implicit multiplication of ConstantNode // In that case print parentheses for ParenthesisNodes even though they normally wouldn't be // printed. if (args.length >= 2 && root.getIdentifier() === 'OperatorNode:multiply' && root.implicit && parenthesis === 'auto' && implicit === 'hide') { result = args.map(function (arg, index) { var isParenthesisNode = arg.getIdentifier() === 'ParenthesisNode'; if (result[index] || isParenthesisNode) { // put in parenthesis? return true; } return false; }); } return result; }
Calculate which parentheses are necessary. Gets an OperatorNode (which is the root of the tree) and an Array of Nodes (this.args) and returns an array where 'true' means that an argument has to be enclosed in parentheses whereas 'false' means the opposite. @param {OperatorNode} root @param {string} parenthesis @param {Node[]} args @param {boolean} latex @return {boolean[]} @private
calculateNecessaryParentheses
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
numeric = function numeric(value, outputType) { var inputType = getTypeOf(value); if (!(inputType in validInputTypes)) { throw new TypeError('Cannot convert ' + value + ' of type "' + inputType + '"; valid input types are ' + Object.keys(validInputTypes).join(', ')); } if (!(outputType in validOutputTypes)) { throw new TypeError('Cannot convert ' + value + ' to type "' + outputType + '"; valid output types are ' + Object.keys(validOutputTypes).join(', ')); } if (outputType === inputType) { return value; } else { return validOutputTypes[outputType](value); } }
Convert a numeric value to a specific type: number, BigNumber, or Fraction @param {string | number | BigNumber | Fraction } value @param {'number' | 'BigNumber' | 'Fraction'} outputType @return {number | BigNumber | Fraction} Returns an instance of the numeric in the requested type
numeric
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _round(value, decimals) { return parseFloat(toFixed(value, decimals)); }
round a number to the given number of decimals, or to zero if decimals is not provided @param {number} value @param {number} decimals number of decimals, between 0 and 15 (0 by default) @return {number} roundedValue @private
_round
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function ParenthesisNode(content) { if (!(this instanceof ParenthesisNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (!type.isNode(content)) { throw new TypeError('Node expected for parameter "content"'); } this.content = content; }
@constructor ParenthesisNode @extends {Node} A parenthesis node describes manual parenthesis from the user input @param {Node} content @extends {Node}
ParenthesisNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function FunctionNode(fn, args) { if (!(this instanceof FunctionNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof fn === 'string') { fn = new SymbolNode(fn); } // validate input if (!type.isNode(fn)) throw new TypeError('Node expected as parameter "fn"'); if (!Array.isArray(args) || !args.every(type.isNode)) { throw new TypeError('Array containing Nodes expected for parameter "args"'); } this.fn = fn; this.args = args || []; // readonly property name Object.defineProperty(this, 'name', { get: function () { return this.fn.name || ''; }.bind(this), set: function set() { throw new Error('Cannot assign a new name, name is read-only'); } }); // TODO: deprecated since v3, remove some day var deprecated = function deprecated() { throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead'); }; Object.defineProperty(this, 'object', { get: deprecated, set: deprecated }); }
@constructor FunctionNode @extends {./Node} invoke a list with arguments on a node @param {./Node | string} fn Node resolving with a function on which to invoke the arguments, typically a SymboNode or AccessorNode @param {./Node[]} args
FunctionNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
deprecated = function deprecated() { throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead'); }
@constructor FunctionNode @extends {./Node} invoke a list with arguments on a node @param {./Node | string} fn Node resolving with a function on which to invoke the arguments, typically a SymboNode or AccessorNode @param {./Node[]} args
deprecated
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function expandTemplate(template, node, options) { var latex = ''; // Match everything of the form ${identifier} or ${identifier[2]} or $$ // while submatching identifier and 2 (in the second case) var regex = new RegExp('\\$(?:\\{([a-z_][a-z_0-9]*)(?:\\[([0-9]+)\\])?\\}|\\$)', 'ig'); var inputPos = 0; // position in the input string var match; while ((match = regex.exec(template)) !== null) { // go through all matches // add everything in front of the match to the LaTeX string latex += template.substring(inputPos, match.index); inputPos = match.index; if (match[0] === '$$') { // escaped dollar sign latex += '$'; inputPos++; } else { // template parameter inputPos += match[0].length; var property = node[match[1]]; if (!property) { throw new ReferenceError('Template: Property ' + match[1] + ' does not exist.'); } if (match[2] === undefined) { // no square brackets switch (_typeof(property)) { case 'string': latex += property; break; case 'object': if (type.isNode(property)) { latex += property.toTex(options); } else if (Array.isArray(property)) { // make array of Nodes into comma separated list latex += property.map(function (arg, index) { if (type.isNode(arg)) { return arg.toTex(options); } throw new TypeError('Template: ' + match[1] + '[' + index + '] is not a Node.'); }).join(','); } else { throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes'); } break; default: throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes'); } } else { // with square brackets if (type.isNode(property[match[2]] && property[match[2]])) { latex += property[match[2]].toTex(options); } else { throw new TypeError('Template: ' + match[1] + '[' + match[2] + '] is not a Node.'); } } } } latex += template.slice(inputPos); // append rest of the template return latex; } // backup Node's toTex function
Get HTML representation @param {Object} options @return {string} str
expandTemplate
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _inv(mat, rows, cols) { var r, s, f, value, temp; if (rows === 1) { // this is a 1 x 1 matrix value = mat[0][0]; if (value === 0) { throw Error('Cannot calculate inverse, determinant is zero'); } return [[divideScalar(1, value)]]; } else if (rows === 2) { // this is a 2 x 2 matrix var d = det(mat); if (d === 0) { throw Error('Cannot calculate inverse, determinant is zero'); } return [[divideScalar(mat[1][1], d), divideScalar(unaryMinus(mat[0][1]), d)], [divideScalar(unaryMinus(mat[1][0]), d), divideScalar(mat[0][0], d)]]; } else { // this is a matrix of 3 x 3 or larger // calculate inverse using gauss-jordan elimination // https://en.wikipedia.org/wiki/Gaussian_elimination // http://mathworld.wolfram.com/MatrixInverse.html // http://math.uww.edu/~mcfarlat/inverse.htm // make a copy of the matrix (only the arrays, not of the elements) var A = mat.concat(); for (r = 0; r < rows; r++) { A[r] = A[r].concat(); } // create an identity matrix which in the end will contain the // matrix inverse var B = identity(rows).valueOf(); // loop over all columns, and perform row reductions for (var c = 0; c < cols; c++) { // Pivoting: Swap row c with row r, where row r contains the largest element A[r][c] var ABig = abs(A[c][c]); var rBig = c; r = c + 1; while (r < rows) { if (abs(A[r][c]) > ABig) { ABig = abs(A[r][c]); rBig = r; } r++; } if (ABig === 0) { throw Error('Cannot calculate inverse, determinant is zero'); } r = rBig; if (r !== c) { temp = A[c]; A[c] = A[r]; A[r] = temp; temp = B[c]; B[c] = B[r]; B[r] = temp; } // eliminate non-zero values on the other rows at column c var Ac = A[c]; var Bc = B[c]; for (r = 0; r < rows; r++) { var Ar = A[r]; var Br = B[r]; if (r !== c) { // eliminate value at column c and row r if (Ar[c] !== 0) { f = divideScalar(unaryMinus(Ar[c]), Ac[c]); // add (f * row c) to row r to eliminate the value // at column c for (s = c; s < cols; s++) { Ar[s] = addScalar(Ar[s], multiply(f, Ac[s])); } for (s = 0; s < cols; s++) { Br[s] = addScalar(Br[s], multiply(f, Bc[s])); } } } else { // normalize value at Acc to 1, // divide each value on row r with the value at Acc f = Ac[c]; for (s = c; s < cols; s++) { Ar[s] = divideScalar(Ar[s], f); } for (s = 0; s < cols; s++) { Br[s] = divideScalar(Br[s], f); } } } } return B; } }
Calculate the inverse of a square matrix @param {Array[]} mat A square matrix @param {number} rows Number of rows @param {number} cols Number of columns, must equal rows @return {Array[]} inv Inverse matrix @private
_inv
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _denseTranspose(m, rows, columns) { // matrix array var data = m._data; // transposed matrix data var transposed = []; var transposedRow; // loop columns for (var j = 0; j < columns; j++) { // initialize row transposedRow = transposed[j] = []; // loop rows for (var i = 0; i < rows; i++) { // set data transposedRow[i] = clone(data[i][j]); } } // return matrix return new DenseMatrix({ data: transposed, size: [columns, rows], datatype: m._datatype }); }
Transpose a matrix. All values of the matrix are reflected over its main diagonal. Only applicable to two dimensional matrices containing a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional vectors and scalars return the input unchanged. Syntax: math.transpose(x) Examples: const A = [[1, 2, 3], [4, 5, 6]] math.transpose(A) // returns [[1, 4], [2, 5], [3, 6]] See also: diag, inv, subset, squeeze @param {Array | Matrix} x Matrix to be transposed @return {Array | Matrix} The transposed matrix
_denseTranspose
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sparseTranspose(m, rows, columns) { // matrix arrays var values = m._values; var index = m._index; var ptr = m._ptr; // result matrices var cvalues = values ? [] : undefined; var cindex = []; var cptr = []; // row counts var w = []; for (var x = 0; x < rows; x++) { w[x] = 0; } // vars var p, l, j; // loop values in matrix for (p = 0, l = index.length; p < l; p++) { // number of values in row w[index[p]]++; } // cumulative sum var sum = 0; // initialize cptr with the cummulative sum of row counts for (var i = 0; i < rows; i++) { // update cptr cptr.push(sum); // update sum sum += w[i]; // update w w[i] = cptr[i]; } // update cptr cptr.push(sum); // loop columns for (j = 0; j < columns; j++) { // values & index in column for (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) { // C values & index var q = w[index[k]]++; // C[j, i] = A[i, j] cindex[q] = j; // check we need to process values (pattern matrix) if (values) { cvalues[q] = clone(values[k]); } } } // return matrix return new SparseMatrix({ values: cvalues, index: cindex, ptr: cptr, size: [columns, rows], datatype: m._datatype }); }
Transpose a matrix. All values of the matrix are reflected over its main diagonal. Only applicable to two dimensional matrices containing a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional vectors and scalars return the input unchanged. Syntax: math.transpose(x) Examples: const A = [[1, 2, 3], [4, 5, 6]] math.transpose(A) // returns [[1, 4], [2, 5], [3, 6]] See also: diag, inv, subset, squeeze @param {Array | Matrix} x Matrix to be transposed @return {Array | Matrix} The transposed matrix
_sparseTranspose
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isPositiveInteger(n) { return n.isInteger() && n.gte(0); }
Test whether BigNumber n is a positive integer @param {BigNumber} n @returns {boolean} isPositiveInteger
isPositiveInteger
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _out(arr) { return config.matrix === 'Array' ? arr : matrix(arr); }
Create an array from a range. By default, the range end is excluded. This can be customized by providing an extra parameter `includeEnd`. Syntax: math.range(str [, includeEnd]) // Create a range from a string, // where the string contains the // start, optional step, and end, // separated by a colon. math.range(start, end [, includeEnd]) // Create a range with start and // end and a step size of 1. math.range(start, end, step [, includeEnd]) // Create a range with start, step, // and end. Where: - `str: string` A string 'start:end' or 'start:step:end' - `start: {number | BigNumber}` Start of the range - `end: number | BigNumber` End of the range, excluded by default, included when parameter includeEnd=true - `step: number | BigNumber` Step size. Default value is 1. - `includeEnd: boolean` Option to specify whether to include the end or not. False by default. Examples: math.range(2, 6) // [2, 3, 4, 5] math.range(2, -3, -1) // [2, 1, 0, -1, -2] math.range('2:1:6') // [2, 3, 4, 5] math.range(2, 6, true) // [2, 3, 4, 5, 6] See also: ones, zeros, size, subset @param {*} args Parameters describing the ranges `start`, `end`, and optional `step`. @return {Array | Matrix} range
_out
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _strRange(str, includeEnd) { var r = _parse(str); if (!r) { throw new SyntaxError('String "' + str + '" is no valid range'); } var fn; if (config.number === 'BigNumber') { fn = includeEnd ? _bigRangeInc : _bigRangeEx; return _out(fn(new type.BigNumber(r.start), new type.BigNumber(r.end), new type.BigNumber(r.step))); } else { fn = includeEnd ? _rangeInc : _rangeEx; return _out(fn(r.start, r.end, r.step)); } }
Create an array from a range. By default, the range end is excluded. This can be customized by providing an extra parameter `includeEnd`. Syntax: math.range(str [, includeEnd]) // Create a range from a string, // where the string contains the // start, optional step, and end, // separated by a colon. math.range(start, end [, includeEnd]) // Create a range with start and // end and a step size of 1. math.range(start, end, step [, includeEnd]) // Create a range with start, step, // and end. Where: - `str: string` A string 'start:end' or 'start:step:end' - `start: {number | BigNumber}` Start of the range - `end: number | BigNumber` End of the range, excluded by default, included when parameter includeEnd=true - `step: number | BigNumber` Step size. Default value is 1. - `includeEnd: boolean` Option to specify whether to include the end or not. False by default. Examples: math.range(2, 6) // [2, 3, 4, 5] math.range(2, -3, -1) // [2, 1, 0, -1, -2] math.range('2:1:6') // [2, 3, 4, 5] math.range(2, 6, true) // [2, 3, 4, 5, 6] See also: ones, zeros, size, subset @param {*} args Parameters describing the ranges `start`, `end`, and optional `step`. @return {Array | Matrix} range
_strRange
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _rangeEx(start, end, step) { var array = []; var x = start; if (step > 0) { while (smaller(x, end)) { array.push(x); x += step; } } else if (step < 0) { while (larger(x, end)) { array.push(x); x += step; } } return array; }
Create a range with numbers. End is excluded @param {number} start @param {number} end @param {number} step @returns {Array} range @private
_rangeEx
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _rangeInc(start, end, step) { var array = []; var x = start; if (step > 0) { while (smallerEq(x, end)) { array.push(x); x += step; } } else if (step < 0) { while (largerEq(x, end)) { array.push(x); x += step; } } return array; }
Create a range with numbers. End is included @param {number} start @param {number} end @param {number} step @returns {Array} range @private
_rangeInc
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _bigRangeEx(start, end, step) { var array = []; var x = start; if (step.gt(ZERO)) { while (smaller(x, end)) { array.push(x); x = x.plus(step); } } else if (step.lt(ZERO)) { while (larger(x, end)) { array.push(x); x = x.plus(step); } } return array; }
Create a range with big numbers. End is excluded @param {BigNumber} start @param {BigNumber} end @param {BigNumber} step @returns {Array} range @private
_bigRangeEx
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _bigRangeInc(start, end, step) { var array = []; var x = start; if (step.gt(ZERO)) { while (smallerEq(x, end)) { array.push(x); x = x.plus(step); } } else if (step.lt(ZERO)) { while (largerEq(x, end)) { array.push(x); x = x.plus(step); } } return array; }
Create a range with big numbers. End is included @param {BigNumber} start @param {BigNumber} end @param {BigNumber} step @returns {Array} range @private
_bigRangeInc
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _parse(str) { var args = str.split(':'); // number var nums = args.map(function (arg) { // use Number and not parseFloat as Number returns NaN on invalid garbage in the string return Number(arg); }); var invalid = nums.some(function (num) { return isNaN(num); }); if (invalid) { return null; } switch (nums.length) { case 2: return { start: nums[0], end: nums[1], step: 1 }; case 3: return { start: nums[0], end: nums[2], step: nums[1] }; default: return null; } }
Parse a string into a range, The string contains the start, optional step, and end, separated by a colon. If the string does not contain a valid range, null is returned. For example str='0:2:11'. @param {string} str @return {{start: number, end: number, step: number} | null} range Object containing properties start, end, step @private
_parse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _concat(a, b, concatDim, dim) { if (dim < concatDim) { // recurse into next dimension if (a.length !== b.length) { throw new DimensionError(a.length, b.length); } var c = []; for (var i = 0; i < a.length; i++) { c[i] = _concat(a[i], b[i], concatDim, dim + 1); } return c; } else { // concatenate this dimension return a.concat(b); } }
Recursively concatenate two matrices. The contents of the matrices is not cloned. @param {Array} a Multi dimensional array @param {Array} b Multi dimensional array @param {number} concatDim The dimension on which to concatenate (zero-based) @param {number} dim The current dim (zero-based) @return {Array} c The concatenated matrix @private
_concat
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _reduce(mat, dim, callback) { var i, ret, val, tran; if (dim <= 0) { if (!Array.isArray(mat[0])) { val = mat[0]; for (i = 1; i < mat.length; i++) { val = callback(val, mat[i]); } return val; } else { tran = _switch(mat); ret = []; for (i = 0; i < tran.length; i++) { ret[i] = _reduce(tran[i], dim - 1, callback); } return ret; } } else { ret = []; for (i = 0; i < mat.length; i++) { ret[i] = _reduce(mat[i], dim - 1, callback); } return ret; } }
Recursively reduce a matrix @param {Array} mat @param {number} dim @param {Function} callback @returns {Array} ret @private
_reduce
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _switch(mat) { var I = mat.length; var J = mat[0].length; var i, j; var ret = []; for (j = 0; j < J; j++) { var tmp = []; for (i = 0; i < I; i++) { tmp.push(mat[i][j]); } ret.push(tmp); } return ret; }
Transpose a matrix @param {Array} mat @returns {Array} ret @private
_switch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Matrix() { if (!(this instanceof Matrix)) { throw new SyntaxError('Constructor must be called with the new operator'); } }
@constructor Matrix A Matrix is a wrapper around an Array. A matrix can hold a multi dimensional array. A matrix can be constructed as: let matrix = math.matrix(data) Matrix contains the functions to resize, get and set values, get the size, clone the matrix and to convert the matrix to a vector, array, or scalar. Furthermore, one can iterate over the matrix using map and forEach. The internal Array of the Matrix can be accessed using the function valueOf. Example usage: let matrix = math.matrix([[1, 2], [3, 4]]) matix.size() // [2, 2] matrix.resize([3, 2], 5) matrix.valueOf() // [[1, 2], [3, 4], [5, 5]] matrix.subset([1,2]) // 3 (indexes are zero-based)
Matrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function removeParens(node) { return node.transform(function (node, path, parent) { return type.isParenthesisNode(node) ? node.content : node; }); } // All constants that are allowed in rules
Simplify an expression tree. A list of rules are applied to an expression, repeating over the list until no further changes are made. It's possible to pass a custom set of rules to the function as second argument. A rule can be specified as an object, string, or function: const rules = [ { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' }, 'n1*n3 + n2*n3 -> (n1+n2)*n3', function (node) { // ... return a new node or return the node unchanged return node } ] String and object rules consist of a left and right pattern. The left is used to match against the expression and the right determines what matches are replaced with. The main difference between a pattern and a normal expression is that variables starting with the following characters are interpreted as wildcards: - 'n' - matches any Node - 'c' - matches any ConstantNode - 'v' - matches any Node that is not a ConstantNode The default list of rules is exposed on the function as `simplify.rules` and can be used as a basis to built a set of custom rules. For more details on the theory, see: - [Strategies for simplifying math expressions (Stackoverflow)](https://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions) - [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification) An optional `options` argument can be passed as last argument of `simplify`. There is currently one option available: `exactFractions`, a boolean which is `true` by default. Syntax: simplify(expr) simplify(expr, rules) simplify(expr, rules) simplify(expr, rules, scope) simplify(expr, rules, scope, options) simplify(expr, scope) simplify(expr, scope, options) Examples: math.simplify('2 * 1 * x ^ (2 - 1)') // Node "2 * x" math.simplify('2 * 3 * x', {x: 4}) // Node "24" const f = math.parse('2 * 1 * x ^ (2 - 1)') math.simplify(f) // Node "2 * x" math.simplify('0.4 * x', {}, {exactFractions: true}) // Node "x * 2 / 5" math.simplify('0.4 * x', {}, {exactFractions: false}) // Node "0.4 * x" See also: derivative, parse, eval, rationalize @param {Node | string} expr The expression to be simplified @param {Array<{l:string, r: string} | string | function>} [rules] Optional list with custom rules @return {Node} Returns the simplified form of `expr`
removeParens
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _buildRules(rules) { // Array of rules to be used to simplify expressions var ruleSet = []; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; var newRule = void 0; var ruleType = _typeof(rule); switch (ruleType) { case 'string': var lr = rule.split('->'); if (lr.length === 2) { rule = { l: lr[0], r: lr[1] }; } else { throw SyntaxError('Could not parse rule: ' + rule); } /* falls through */ case 'object': newRule = { l: removeParens(parse(rule.l)), r: removeParens(parse(rule.r)) }; if (rule.context) { newRule.evaluate = rule.context; } if (rule.evaluate) { newRule.evaluate = parse(rule.evaluate); } if (isAssociative(newRule.l)) { var makeNode = createMakeNodeFunction(newRule.l); var expandsym = _getExpandPlaceholderSymbol(); newRule.expanded = {}; newRule.expanded.l = makeNode([newRule.l.clone(), expandsym]); // Push the expandsym into the deepest possible branch. // This helps to match the newRule against nodes returned from getSplits() later on. flatten(newRule.expanded.l); unflattenr(newRule.expanded.l); newRule.expanded.r = makeNode([newRule.r, expandsym]); } break; case 'function': newRule = rule; break; default: throw TypeError('Unsupported type of rule: ' + ruleType); } // console.log('Adding rule: ' + rules[i]) // console.log(newRule) ruleSet.push(newRule); } return ruleSet; }
Parse the string array of rules into nodes Example syntax for rules: Position constants to the left in a product: { l: 'n1 * c1', r: 'c1 * n1' } n1 is any Node, and c1 is a ConstantNode. Apply difference of squares formula: { l: '(n1 - n2) * (n1 + n2)', r: 'n1^2 - n2^2' } n1, n2 mean any Node. Short hand notation: 'n1 * c1 -> c1 * n1'
_buildRules
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _getExpandPlaceholderSymbol() { return new SymbolNode('_p' + _lastsym++); }
Parse the string array of rules into nodes Example syntax for rules: Position constants to the left in a product: { l: 'n1 * c1', r: 'c1 * n1' } n1 is any Node, and c1 is a ConstantNode. Apply difference of squares formula: { l: '(n1 - n2) * (n1 + n2)', r: 'n1^2 - n2^2' } n1, n2 mean any Node. Short hand notation: 'n1 * c1 -> c1 * n1'
_getExpandPlaceholderSymbol
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_transform = function _transform(node) { if (node.isSymbolNode && matches.placeholders.hasOwnProperty(node.name)) { return matches.placeholders[node.name].clone(); } else { return node.map(_transform); } }
Returns a simplfied form of node, or the original node if no simplification was possible. @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The simplified form of `expr`, or the original node if no simplification was possible.
_transform
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function getSplits(node, context) { var res = []; var right, rightArgs; var makeNode = createMakeNodeFunction(node); if (isCommutative(node, context)) { for (var i = 0; i < node.args.length; i++) { rightArgs = node.args.slice(0); rightArgs.splice(i, 1); right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs); res.push(makeNode([node.args[i], right])); } } else { rightArgs = node.args.slice(1); right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs); res.push(makeNode([node.args[0], right])); } return res; }
Get (binary) combinations of a flattened binary node e.g. +(node1, node2, node3) -> [ +(node1, +(node2, node3)), +(node2, +(node1, node3)), +(node3, +(node1, node2))]
getSplits
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function mergeMatch(match1, match2) { var res = { placeholders: {} // Some matches may not have placeholders; this is OK }; if (!match1.placeholders && !match2.placeholders) { return res; } else if (!match1.placeholders) { return match2; } else if (!match2.placeholders) { return match1; } // Placeholders with the same key must match exactly for (var key in match1.placeholders) { res.placeholders[key] = match1.placeholders[key]; if (match2.placeholders.hasOwnProperty(key)) { if (!_exactMatch(match1.placeholders[key], match2.placeholders[key])) { return null; } } } for (var _key in match2.placeholders) { res.placeholders[_key] = match2.placeholders[_key]; } return res; }
Returns the set union of two match-placeholders or null if there is a conflict.
mergeMatch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function combineChildMatches(list1, list2) { var res = []; if (list1.length === 0 || list2.length === 0) { return res; } var merged; for (var i1 = 0; i1 < list1.length; i1++) { for (var i2 = 0; i2 < list2.length; i2++) { merged = mergeMatch(list1[i1], list2[i2]); if (merged) { res.push(merged); } } } return res; }
Combine two lists of matches by applying mergeMatch to the cartesian product of two lists of matches. Each list represents matches found in one child of a node.
combineChildMatches
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function mergeChildMatches(childMatches) { if (childMatches.length === 0) { return childMatches; } var sets = childMatches.reduce(combineChildMatches); var uniqueSets = []; var unique = {}; for (var i = 0; i < sets.length; i++) { var s = JSON.stringify(sets[i]); if (!unique[s]) { unique[s] = true; uniqueSets.push(sets[i]); } } return uniqueSets; }
Combine multiple lists of matches by applying mergeMatch to the cartesian product of two lists of matches. Each list represents matches found in one child of a node. Returns a list of unique matches.
mergeChildMatches
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _ruleMatch(rule, node, isSplit) { // console.log('Entering _ruleMatch(' + JSON.stringify(rule) + ', ' + JSON.stringify(node) + ')') // console.log('rule = ' + rule) // console.log('node = ' + node) // console.log('Entering _ruleMatch(' + rule.toString() + ', ' + node.toString() + ')') var res = [{ placeholders: {} }]; if (rule instanceof OperatorNode && node instanceof OperatorNode || rule instanceof FunctionNode && node instanceof FunctionNode) { // If the rule is an OperatorNode or a FunctionNode, then node must match exactly if (rule instanceof OperatorNode) { if (rule.op !== node.op || rule.fn !== node.fn) { return []; } } else if (rule instanceof FunctionNode) { if (rule.name !== node.name) { return []; } } // rule and node match. Search the children of rule and node. if (node.args.length === 1 && rule.args.length === 1 || !isAssociative(node) || isSplit) { // Expect non-associative operators to match exactly var childMatches = []; for (var i = 0; i < rule.args.length; i++) { var childMatch = _ruleMatch(rule.args[i], node.args[i]); if (childMatch.length === 0) { // Child did not match, so stop searching immediately return []; } // The child matched, so add the information returned from the child to our result childMatches.push(childMatch); } res = mergeChildMatches(childMatches); } else if (node.args.length >= 2 && rule.args.length === 2) { // node is flattened, rule is not // Associative operators/functions can be split in different ways so we check if the rule matches each // them and return their union. var splits = getSplits(node, rule.context); var splitMatches = []; for (var _i = 0; _i < splits.length; _i++) { var matchSet = _ruleMatch(rule, splits[_i], true); // recursing at the same tree depth here splitMatches = splitMatches.concat(matchSet); } return splitMatches; } else if (rule.args.length > 2) { throw Error('Unexpected non-binary associative function: ' + rule.toString()); } else { // Incorrect number of arguments in rule and node, so no match return []; } } else if (rule instanceof SymbolNode) { // If the rule is a SymbolNode, then it carries a special meaning // according to the first character of the symbol node name. // c.* matches a ConstantNode // n.* matches any node if (rule.name.length === 0) { throw new Error('Symbol in rule has 0 length...!?'); } if (math.hasOwnProperty(rule.name)) { if (!SUPPORTED_CONSTANTS[rule.name]) { throw new Error('Built in constant: ' + rule.name + ' is not supported by simplify.'); } // built-in constant must match exactly if (rule.name !== node.name) { return []; } } else if (rule.name[0] === 'n' || rule.name.substring(0, 2) === '_p') { // rule matches _anything_, so assign this node to the rule.name placeholder // Assign node to the rule.name placeholder. // Our parent will check for matches among placeholders. res[0].placeholders[rule.name] = node; } else if (rule.name[0] === 'v') { // rule matches any variable thing (not a ConstantNode) if (!type.isConstantNode(node)) { res[0].placeholders[rule.name] = node; } else { // Mis-match: rule was expecting something other than a ConstantNode return []; } } else if (rule.name[0] === 'c') { // rule matches any ConstantNode if (node instanceof ConstantNode) { res[0].placeholders[rule.name] = node; } else { // Mis-match: rule was expecting a ConstantNode return []; } } else { throw new Error('Invalid symbol in rule: ' + rule.name); } } else if (rule instanceof ConstantNode) { // Literal constant must match exactly if (!equal(rule.value, node.value)) { return []; } } else { // Some other node was encountered which we aren't prepared for, so no match return []; } // It's a match! // console.log('_ruleMatch(' + rule.toString() + ', ' + node.toString() + ') found a match') return res; }
Determines whether node matches rule. @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} rule @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node @return {Object} Information about the match, if it exists.
_ruleMatch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _exactMatch(p, q) { if (p instanceof ConstantNode && q instanceof ConstantNode) { if (!equal(p.value, q.value)) { return false; } } else if (p instanceof SymbolNode && q instanceof SymbolNode) { if (p.name !== q.name) { return false; } } else if (p instanceof OperatorNode && q instanceof OperatorNode || p instanceof FunctionNode && q instanceof FunctionNode) { if (p instanceof OperatorNode) { if (p.op !== q.op || p.fn !== q.fn) { return false; } } else if (p instanceof FunctionNode) { if (p.name !== q.name) { return false; } } if (p.args.length !== q.args.length) { return false; } for (var i = 0; i < p.args.length; i++) { if (!_exactMatch(p.args[i], q.args[i])) { return false; } } } else { return false; } return true; }
Determines whether p and q (and all their children nodes) are identical. @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} p @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} q @return {Object} Information about the match, if it exists.
_exactMatch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _denseLUP(m) { // rows & columns var rows = m._size[0]; var columns = m._size[1]; // minimum rows and columns var n = Math.min(rows, columns); // matrix array, clone original data var data = object.clone(m._data); // l matrix arrays var ldata = []; var lsize = [rows, n]; // u matrix arrays var udata = []; var usize = [n, columns]; // vars var i, j, k; // permutation vector var p = []; for (i = 0; i < rows; i++) { p[i] = i; } // loop columns for (j = 0; j < columns; j++) { // skip first column in upper triangular matrix if (j > 0) { // loop rows for (i = 0; i < rows; i++) { // min i,j var min = Math.min(i, j); // v[i, j] var s = 0; // loop up to min for (k = 0; k < min; k++) { // s = l[i, k] - data[k, j] s = addScalar(s, multiplyScalar(data[i][k], data[k][j])); } data[i][j] = subtract(data[i][j], s); } } // row with larger value in cvector, row >= j var pi = j; var pabsv = 0; var vjj = 0; // loop rows for (i = j; i < rows; i++) { // data @ i, j var v = data[i][j]; // absolute value var absv = abs(v); // value is greater than pivote value if (larger(absv, pabsv)) { // store row pi = i; // update max value pabsv = absv; // value @ [j, j] vjj = v; } } // swap rows (j <-> pi) if (j !== pi) { // swap values j <-> pi in p p[j] = [p[pi], p[pi] = p[j]][0]; // swap j <-> pi in data DenseMatrix._swapRows(j, pi, data); } // check column is in lower triangular matrix if (j < rows) { // loop rows (lower triangular matrix) for (i = j + 1; i < rows; i++) { // value @ i, j var vij = data[i][j]; if (!equalScalar(vij, 0)) { // update data data[i][j] = divideScalar(data[i][j], vjj); } } } } // loop columns for (j = 0; j < columns; j++) { // loop rows for (i = 0; i < rows; i++) { // initialize row in arrays if (j === 0) { // check row exists in upper triangular matrix if (i < columns) { // U udata[i] = []; } // L ldata[i] = []; } // check we are in the upper triangular matrix if (i < j) { // check row exists in upper triangular matrix if (i < columns) { // U udata[i][j] = data[i][j]; } // check column exists in lower triangular matrix if (j < rows) { // L ldata[i][j] = 0; } continue; } // diagonal value if (i === j) { // check row exists in upper triangular matrix if (i < columns) { // U udata[i][j] = data[i][j]; } // check column exists in lower triangular matrix if (j < rows) { // L ldata[i][j] = 1; } continue; } // check row exists in upper triangular matrix if (i < columns) { // U udata[i][j] = 0; } // check column exists in lower triangular matrix if (j < rows) { // L ldata[i][j] = data[i][j]; } } } // l matrix var l = new DenseMatrix({ data: ldata, size: lsize }); // u matrix var u = new DenseMatrix({ data: udata, size: usize }); // p vector var pv = []; for (i = 0, n = p.length; i < n; i++) { pv[p[i]] = i; } // return matrices return { L: l, U: u, p: pv, toString: function toString() { return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p; } }; }
Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a row permutation vector `p` where `A[p,:] = L * U` Syntax: math.lup(A) Example: const m = [[2, 1], [1, 4]] const r = math.lup(m) // r = { // L: [[1, 0], [0.5, 1]], // U: [[2, 1], [0, 3.5]], // P: [0, 1] // } See also: slu, lsolve, lusolve, usolve @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition. @return {{L: Array | Matrix, U: Array | Matrix, P: Array.<number>}} The lower triangular matrix, the upper triangular matrix and the permutation matrix.
_denseLUP
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sparseLUP(m) { // rows & columns var rows = m._size[0]; var columns = m._size[1]; // minimum rows and columns var n = Math.min(rows, columns); // matrix arrays (will not be modified, thanks to permutation vector) var values = m._values; var index = m._index; var ptr = m._ptr; // l matrix arrays var lvalues = []; var lindex = []; var lptr = []; var lsize = [rows, n]; // u matrix arrays var uvalues = []; var uindex = []; var uptr = []; var usize = [n, columns]; // vars var i, j, k; // permutation vectors, (current index -> original index) and (original index -> current index) var pvCo = []; var pvOc = []; for (i = 0; i < rows; i++) { pvCo[i] = i; pvOc[i] = i; } // swap indices in permutation vectors (condition x < y)! var swapIndeces = function swapIndeces(x, y) { // find pv indeces getting data from x and y var kx = pvOc[x]; var ky = pvOc[y]; // update permutation vector current -> original pvCo[kx] = y; pvCo[ky] = x; // update permutation vector original -> current pvOc[x] = ky; pvOc[y] = kx; }; // loop columns var _loop = function _loop() { // sparse accumulator var spa = new Spa(); // check lower triangular matrix has a value @ column j if (j < rows) { // update ptr lptr.push(lvalues.length); // first value in j column for lower triangular matrix lvalues.push(1); lindex.push(j); } // update ptr uptr.push(uvalues.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] var k0 = ptr[j]; var k1 = ptr[j + 1]; // copy column j into sparse accumulator for (k = k0; k < k1; k++) { // row i = index[k]; // copy column values into sparse accumulator (use permutation vector) spa.set(pvCo[i], values[k]); } // skip first column in upper triangular matrix if (j > 0) { // loop rows in column j (above diagonal) spa.forEach(0, j - 1, function (k, vkj) { // loop rows in column k (L) SparseMatrix._forEachRow(k, lvalues, lindex, lptr, function (i, vik) { // check row is below k if (i > k) { // update spa value spa.accumulate(i, unaryMinus(multiplyScalar(vik, vkj))); } }); }); } // row with larger value in spa, row >= j var pi = j; var vjj = spa.get(j); var pabsv = abs(vjj); // loop values in spa (order by row, below diagonal) spa.forEach(j + 1, rows - 1, function (x, v) { // absolute value var absv = abs(v); // value is greater than pivote value if (larger(absv, pabsv)) { // store row pi = x; // update max value pabsv = absv; // value @ [j, j] vjj = v; } }); // swap rows (j <-> pi) if (j !== pi) { // swap values j <-> pi in L SparseMatrix._swapRows(j, pi, lsize[1], lvalues, lindex, lptr); // swap values j <-> pi in U SparseMatrix._swapRows(j, pi, usize[1], uvalues, uindex, uptr); // swap values in spa spa.swap(j, pi); // update permutation vector (swap values @ j, pi) swapIndeces(j, pi); } // loop values in spa (order by row) spa.forEach(0, rows - 1, function (x, v) { // check we are above diagonal if (x <= j) { // update upper triangular matrix uvalues.push(v); uindex.push(x); } else { // update value v = divideScalar(v, vjj); // check value is non zero if (!equalScalar(v, 0)) { // update lower triangular matrix lvalues.push(v); lindex.push(x); } } }); }; for (j = 0; j < columns; j++) { _loop(); } // update ptrs uptr.push(uvalues.length); lptr.push(lvalues.length); // return matrices return { L: new SparseMatrix({ values: lvalues, index: lindex, ptr: lptr, size: lsize }), U: new SparseMatrix({ values: uvalues, index: uindex, ptr: uptr, size: usize }), p: pvCo, toString: function toString() { return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p; } }; }
Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a row permutation vector `p` where `A[p,:] = L * U` Syntax: math.lup(A) Example: const m = [[2, 1], [1, 4]] const r = math.lup(m) // r = { // L: [[1, 0], [0.5, 1]], // U: [[2, 1], [0, 3.5]], // P: [0, 1] // } See also: slu, lsolve, lusolve, usolve @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition. @return {{L: Array | Matrix, U: Array | Matrix, P: Array.<number>}} The lower triangular matrix, the upper triangular matrix and the permutation matrix.
_sparseLUP
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
swapIndeces = function swapIndeces(x, y) { // find pv indeces getting data from x and y var kx = pvOc[x]; var ky = pvOc[y]; // update permutation vector current -> original pvCo[kx] = y; pvCo[ky] = x; // update permutation vector original -> current pvOc[x] = ky; pvOc[y] = kx; }
Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a row permutation vector `p` where `A[p,:] = L * U` Syntax: math.lup(A) Example: const m = [[2, 1], [1, 4]] const r = math.lup(m) // r = { // L: [[1, 0], [0.5, 1]], // U: [[2, 1], [0, 3.5]], // P: [0, 1] // } See also: slu, lsolve, lusolve, usolve @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition. @return {{L: Array | Matrix, U: Array | Matrix, P: Array.<number>}} The lower triangular matrix, the upper triangular matrix and the permutation matrix.
swapIndeces
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_loop = function _loop() { // sparse accumulator var spa = new Spa(); // check lower triangular matrix has a value @ column j if (j < rows) { // update ptr lptr.push(lvalues.length); // first value in j column for lower triangular matrix lvalues.push(1); lindex.push(j); } // update ptr uptr.push(uvalues.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] var k0 = ptr[j]; var k1 = ptr[j + 1]; // copy column j into sparse accumulator for (k = k0; k < k1; k++) { // row i = index[k]; // copy column values into sparse accumulator (use permutation vector) spa.set(pvCo[i], values[k]); } // skip first column in upper triangular matrix if (j > 0) { // loop rows in column j (above diagonal) spa.forEach(0, j - 1, function (k, vkj) { // loop rows in column k (L) SparseMatrix._forEachRow(k, lvalues, lindex, lptr, function (i, vik) { // check row is below k if (i > k) { // update spa value spa.accumulate(i, unaryMinus(multiplyScalar(vik, vkj))); } }); }); } // row with larger value in spa, row >= j var pi = j; var vjj = spa.get(j); var pabsv = abs(vjj); // loop values in spa (order by row, below diagonal) spa.forEach(j + 1, rows - 1, function (x, v) { // absolute value var absv = abs(v); // value is greater than pivote value if (larger(absv, pabsv)) { // store row pi = x; // update max value pabsv = absv; // value @ [j, j] vjj = v; } }); // swap rows (j <-> pi) if (j !== pi) { // swap values j <-> pi in L SparseMatrix._swapRows(j, pi, lsize[1], lvalues, lindex, lptr); // swap values j <-> pi in U SparseMatrix._swapRows(j, pi, usize[1], uvalues, uindex, uptr); // swap values in spa spa.swap(j, pi); // update permutation vector (swap values @ j, pi) swapIndeces(j, pi); } // loop values in spa (order by row) spa.forEach(0, rows - 1, function (x, v) { // check we are above diagonal if (x <= j) { // update upper triangular matrix uvalues.push(v); uindex.push(x); } else { // update value v = divideScalar(v, vjj); // check value is non zero if (!equalScalar(v, 0)) { // update lower triangular matrix lvalues.push(v); lindex.push(x); } } }); }
Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a row permutation vector `p` where `A[p,:] = L * U` Syntax: math.lup(A) Example: const m = [[2, 1], [1, 4]] const r = math.lup(m) // r = { // L: [[1, 0], [0.5, 1]], // U: [[2, 1], [0, 3.5]], // P: [0, 1] // } See also: slu, lsolve, lusolve, usolve @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition. @return {{L: Array | Matrix, U: Array | Matrix, P: Array.<number>}} The lower triangular matrix, the upper triangular matrix and the permutation matrix.
_loop
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csFlip = function csFlip(i) { // flip the value return -i - 2; }
This function "flips" its input about the integer -1. @param {Number} i The value to flip Reference: http://faculty.cse.tamu.edu/davis/publications.html
csFlip
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
solveValidation = function solveValidation(m, b, copy) { // matrix size var size = m.size(); // validate matrix dimensions if (size.length !== 2) { throw new RangeError('Matrix must be two dimensional (size: ' + string.format(size) + ')'); } // rows & columns var rows = size[0]; var columns = size[1]; // validate rows & columns if (rows !== columns) { throw new RangeError('Matrix must be square (size: ' + string.format(size) + ')'); } // vars var data, i, bdata; // check b is matrix if (type.isMatrix(b)) { // matrix size var msize = b.size(); // vector if (msize.length === 1) { // check vector length if (msize[0] !== rows) { throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); } // create data array data = []; // matrix data (DenseMatrix) bdata = b._data; // loop b data for (i = 0; i < rows; i++) { // row array data[i] = [bdata[i]]; } // return Dense Matrix return new DenseMatrix({ data: data, size: [rows, 1], datatype: b._datatype }); } // two dimensions if (msize.length === 2) { // array must be a column vector if (msize[0] !== rows || msize[1] !== 1) { throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); } // check matrix type if (type.isDenseMatrix(b)) { // check a copy is needed if (copy) { // create data array data = []; // matrix data (DenseMatrix) bdata = b._data; // loop b data for (i = 0; i < rows; i++) { // row array data[i] = [bdata[i][0]]; } // return Dense Matrix return new DenseMatrix({ data: data, size: [rows, 1], datatype: b._datatype }); } // b is already a column vector return b; } // create data array data = []; for (i = 0; i < rows; i++) { data[i] = [0]; } // sparse matrix arrays var values = b._values; var index = b._index; var ptr = b._ptr; // loop values in column 0 for (var k1 = ptr[1], k = ptr[0]; k < k1; k++) { // row i = index[k]; // add to data data[i][0] = values[k]; } // return Dense Matrix return new DenseMatrix({ data: data, size: [rows, 1], datatype: b._datatype }); } // throw error throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); } // check b is array if (isArray(b)) { // size var asize = array.size(b); // check matrix dimensions, vector if (asize.length === 1) { // check vector length if (asize[0] !== rows) { throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); } // create data array data = []; // loop b for (i = 0; i < rows; i++) { // row array data[i] = [b[i]]; } // return Dense Matrix return new DenseMatrix({ data: data, size: [rows, 1] }); } if (asize.length === 2) { // array must be a column vector if (asize[0] !== rows || asize[1] !== 1) { throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); } // create data array data = []; // loop b data for (i = 0; i < rows; i++) { // row array data[i] = [b[i][0]]; } // return Dense Matrix return new DenseMatrix({ data: data, size: [rows, 1] }); } // throw error throw new RangeError('Dimension mismatch. Matrix columns must match vector length.'); } }
Validates matrix and column vector b for backward/forward substitution algorithms. @param {Matrix} m An N x N matrix @param {Array | Matrix} b A column vector @param {Boolean} copy Return a copy of vector b @return {DenseMatrix} Dense column vector b
solveValidation
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function decCoefficientToBinaryString(x) { // Convert to string var a = x.d; // array with digits var r = a[0] + ''; for (var i = 1; i < a.length; ++i) { var s = a[i] + ''; for (var z = 7 - s.length; z--;) { s = '0' + s; } r += s; } var j = r.length; while (r.charAt(j) === '0') { j--; } var xe = x.e; var str = r.slice(0, j + 1 || 1); var strL = str.length; if (xe > 0) { if (++xe > strL) { // Append zeros. xe -= strL; while (xe--) { str += '0'; } } else if (xe < strL) { str = str.slice(0, xe) + '.' + str.slice(xe); } } // Convert from base 10 (decimal) to base 2 var arr = [0]; for (var _i2 = 0; _i2 < str.length;) { var arrL = arr.length; while (arrL--) { arr[arrL] *= 10; } arr[0] += parseInt(str.charAt(_i2++)); // convert to int for (var _j = 0; _j < arr.length; ++_j) { if (arr[_j] > 1) { if (arr[_j + 1] === null || arr[_j + 1] === undefined) { arr[_j + 1] = 0; } arr[_j + 1] += arr[_j] >> 1; arr[_j] &= 1; } } } return arr.reverse(); }
Applies bitwise function to numbers @param {BigNumber} x @param {BigNumber} y @param {function (a, b)} func @return {BigNumber}
decCoefficientToBinaryString
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function product(i, n) { var half; if (n < i) { return 1; } if (n === i) { return n; } half = n + i >> 1; // divide (n + i) by 2 and truncate to integer return product(i, half) * product(half + 1, n); }
@param {integer} i @param {integer} n @returns : product of i to n
product
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _apply(mat, dim, callback) { var i, ret, tran; if (dim <= 0) { if (!Array.isArray(mat[0])) { return callback(mat); } else { tran = _switch(mat); ret = []; for (i = 0; i < tran.length; i++) { ret[i] = _apply(tran[i], dim - 1, callback); } return ret; } } else { ret = []; for (i = 0; i < mat.length; i++) { ret[i] = _apply(mat[i], dim - 1, callback); } return ret; } }
Recursively reduce a matrix @param {Array} mat @param {number} dim @param {Function} callback @returns {Array} ret @private
_apply
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _switch(mat) { var I = mat.length; var J = mat[0].length; var i, j; var ret = []; for (j = 0; j < J; j++) { var tmp = []; for (i = 0; i < I; i++) { tmp.push(mat[i][j]); } ret.push(tmp); } return ret; }
Transpose a matrix @param {Array} mat @returns {Array} ret @private
_switch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _partitionSelect(x, k, compare) { if (!isInteger(k) || k < 0) { throw new Error('k must be a non-negative integer'); } if (type.isMatrix(x)) { var size = x.size(); if (size.length > 1) { throw new Error('Only one dimensional matrices supported'); } return quickSelect(x.valueOf(), k, compare); } if (Array.isArray(x)) { return quickSelect(x, k, compare); } }
Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect. Syntax: math.partitionSelect(x, k) math.partitionSelect(x, k, compare) Examples: math.partitionSelect([5, 10, 1], 2) // returns 10 math.partitionSelect(['C', 'B', 'A', 'D'], 1) // returns 'B' function sortByLength (a, b) { return a.length - b.length } math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength) // returns 'Langdon' See also: sort @param {Matrix | Array} x A one dimensional matrix or array to sort @param {Number} k The kth smallest value to be retrieved zero-based index @param {Function | 'asc' | 'desc'} [compare='asc'] An optional comparator function. The function is called as `compare(a, b)`, and must return 1 when a > b, -1 when a < b, and 0 when a == b. @return {*} Returns the kth lowest value.
_partitionSelect
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function quickSelect(arr, k, compare) { if (k >= arr.length) { throw new Error('k out of bounds'); } // check for NaN values since these can cause an infinite while loop for (var i = 0; i < arr.length; i++) { if (isNumeric(arr[i]) && isNaN(arr[i])) { return arr[i]; // return NaN } } var from = 0; var to = arr.length - 1; // if from == to we reached the kth element while (from < to) { var r = from; var w = to; var pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from]; // stop if the reader and writer meets while (r < w) { // arr[r] >= pivot if (compare(arr[r], pivot) >= 0) { // put the large values at the end var tmp = arr[w]; arr[w] = arr[r]; arr[r] = tmp; --w; } else { // the value is smaller than the pivot, skip ++r; } } // if we stepped up (r++) we need to step one down (arr[r] > pivot) if (compare(arr[r], pivot) > 0) { --r; } // the r pointer is on the end of the first k elements if (k <= r) { to = r; } else { from = r + 1; } } return arr[k]; }
Quickselect algorithm. Code adapted from: https://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html @param {Array} arr @param {Number} k @param {Function} compare @private
quickSelect
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _largest(x, y) { try { return larger(x, y) ? x : y; } catch (err) { throw improveErrorMessage(err, 'max', y); } }
Return the largest of two values @param {*} x @param {*} y @returns {*} Returns x when x is largest, or y when y is largest @private
_largest
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _max(array) { var max; deepForEach(array, function (value) { try { if (isNaN(value) && typeof value === 'number') { max = NaN; } else if (max === undefined || larger(value, max)) { max = value; } } catch (err) { throw improveErrorMessage(err, 'max', value); } }); if (max === undefined) { throw new Error('Cannot calculate max of an empty array'); } return max; }
Recursively calculate the maximum value in an n-dimensional array @param {Array} array @return {number} max @private
_max
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sum(array) { var sum; deepForEach(array, function (value) { try { sum = sum === undefined ? value : add(sum, value); } catch (err) { throw improveErrorMessage(err, 'sum', value); } }); if (sum === undefined) { switch (config.number) { case 'number': return 0; case 'BigNumber': return new type.BigNumber(0); case 'Fraction': return new type.Fraction(0); default: return 0; } } return sum; }
Recursively calculate the sum of an n-dimensional array @param {Array} array @return {number} sum @private
_sum
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _nsumDim(array, dim) { try { var _sum2 = reduce(array, dim, add); return _sum2; } catch (err) { throw improveErrorMessage(err, 'sum'); } }
Recursively calculate the sum of an n-dimensional array @param {Array} array @return {number} sum @private
_nsumDim
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function distribution(name) { if (!distributions.hasOwnProperty(name)) { throw new Error('Unknown distribution ' + name); } var args = Array.prototype.slice.call(arguments, 1); var distribution = distributions[name].apply(this, args); return function (distribution) { // This is the public API for all distributions var randFunctions = { random: function random(arg1, arg2, arg3) { var size, min, max; if (arguments.length > 3) { throw new ArgumentsError('random', arguments.length, 0, 3); } else if (arguments.length === 1) { // `random(max)` or `random(size)` if (isCollection(arg1)) { size = arg1; } else { max = arg1; } } else if (arguments.length === 2) { // `random(min, max)` or `random(size, max)` if (isCollection(arg1)) { size = arg1; max = arg2; } else { min = arg1; max = arg2; } } else { // `random(size, min, max)` size = arg1; min = arg2; max = arg3; } // TODO: validate type of size if (min !== undefined && !isNumber(min) || max !== undefined && !isNumber(max)) { throw new TypeError('Invalid argument in function random'); } if (max === undefined) max = 1; if (min === undefined) min = 0; if (size !== undefined) { var res = _randomDataForMatrix(size.valueOf(), min, max, _random); return type.isMatrix(size) ? matrix(res) : res; } return _random(min, max); }, randomInt: typed({ 'number | Array': function numberArray(arg) { var min = 0; if (isCollection(arg)) { var size = arg; var max = 1; var res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt); return type.isMatrix(size) ? matrix(res) : res; } else { var _max = arg; return _randomInt(min, _max); } }, 'number | Array, number': function numberArrayNumber(arg1, arg2) { if (isCollection(arg1)) { var size = arg1; var max = arg2; var min = 0; var res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt); return type.isMatrix(size) ? matrix(res) : res; } else { var _min = arg1; var _max2 = arg2; return _randomInt(_min, _max2); } }, 'Array, number, number': function ArrayNumberNumber(size, min, max) { var res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt); return size && size.isMatrix === true ? matrix(res) : res; } }), pickRandom: typed({ 'Array': function Array(possibles) { return _pickRandom(possibles); }, 'Array, number | Array': function ArrayNumberArray(possibles, arg2) { var number, weights; if (Array.isArray(arg2)) { weights = arg2; } else if (isNumber(arg2)) { number = arg2; } else { throw new TypeError('Invalid argument in function pickRandom'); } return _pickRandom(possibles, number, weights); }, 'Array, number | Array, Array | number': function ArrayNumberArrayArrayNumber(possibles, arg2, arg3) { var number, weights; if (Array.isArray(arg2)) { weights = arg2; number = arg3; } else { weights = arg3; number = arg2; } if (!Array.isArray(weights) || !isNumber(number)) { throw new TypeError('Invalid argument in function pickRandom'); } return _pickRandom(possibles, number, weights); } }) }; function _pickRandom(possibles, number, weights) { var single = typeof number === 'undefined'; if (single) { number = 1; } if (type.isMatrix(possibles)) { possibles = possibles.valueOf(); // get Array } else if (!Array.isArray(possibles)) { throw new TypeError('Unsupported type of value in function pickRandom'); } if (array.size(possibles).length > 1) { throw new Error('Only one dimensional vectors supported'); } var totalWeights = 0; if (typeof weights !== 'undefined') { if (weights.length !== possibles.length) { throw new Error('Weights must have the same length as possibles'); } for (var i = 0, len = weights.length; i < len; i++) { if (!isNumber(weights[i]) || weights[i] < 0) { throw new Error('Weights must be an array of positive numbers'); } totalWeights += weights[i]; } } var length = possibles.length; if (length === 0) { return []; } else if (number >= length) { return number > 1 ? possibles : possibles[0]; } var result = []; var pick; while (result.length < number) { if (typeof weights === 'undefined') { pick = possibles[Math.floor(rng() * length)]; } else { var randKey = rng() * totalWeights; for (var _i = 0, _len = possibles.length; _i < _len; _i++) { randKey -= weights[_i]; if (randKey < 0) { pick = possibles[_i]; break; } } } if (result.indexOf(pick) === -1) { result.push(pick); } } return single ? result[0] : result; // TODO: add support for multi dimensional matrices } function _random(min, max) { return min + distribution() * (max - min); } function _randomInt(min, max) { return Math.floor(min + distribution() * (max - min)); } // This is a function for generating a random matrix recursively. function _randomDataForMatrix(size, min, max, randFunc) { var data = []; size = size.slice(0); if (size.length > 1) { for (var i = 0, length = size.shift(); i < length; i++) { data.push(_randomDataForMatrix(size, min, max, randFunc)); } } else { for (var _i2 = 0, _length = size.shift(); _i2 < _length; _i2++) { data.push(randFunc(min, max)); } } return data; } return randFunctions; }(distribution); } // Each distribution is a function that takes no argument and when called returns
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See also: random, randomInt, pickRandom @param {string} name Name of a distribution. Choose from 'uniform', 'normal'. @return {Object} Returns a distribution object containing functions: `random([size] [, min] [, max])`, `randomInt([min] [, max])`, `pickRandom(array)`
distribution
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _pickRandom(possibles, number, weights) { var single = typeof number === 'undefined'; if (single) { number = 1; } if (type.isMatrix(possibles)) { possibles = possibles.valueOf(); // get Array } else if (!Array.isArray(possibles)) { throw new TypeError('Unsupported type of value in function pickRandom'); } if (array.size(possibles).length > 1) { throw new Error('Only one dimensional vectors supported'); } var totalWeights = 0; if (typeof weights !== 'undefined') { if (weights.length !== possibles.length) { throw new Error('Weights must have the same length as possibles'); } for (var i = 0, len = weights.length; i < len; i++) { if (!isNumber(weights[i]) || weights[i] < 0) { throw new Error('Weights must be an array of positive numbers'); } totalWeights += weights[i]; } } var length = possibles.length; if (length === 0) { return []; } else if (number >= length) { return number > 1 ? possibles : possibles[0]; } var result = []; var pick; while (result.length < number) { if (typeof weights === 'undefined') { pick = possibles[Math.floor(rng() * length)]; } else { var randKey = rng() * totalWeights; for (var _i = 0, _len = possibles.length; _i < _len; _i++) { randKey -= weights[_i]; if (randKey < 0) { pick = possibles[_i]; break; } } } if (result.indexOf(pick) === -1) { result.push(pick); } } return single ? result[0] : result; // TODO: add support for multi dimensional matrices }
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See also: random, randomInt, pickRandom @param {string} name Name of a distribution. Choose from 'uniform', 'normal'. @return {Object} Returns a distribution object containing functions: `random([size] [, min] [, max])`, `randomInt([min] [, max])`, `pickRandom(array)`
_pickRandom
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _random(min, max) { return min + distribution() * (max - min); }
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See also: random, randomInt, pickRandom @param {string} name Name of a distribution. Choose from 'uniform', 'normal'. @return {Object} Returns a distribution object containing functions: `random([size] [, min] [, max])`, `randomInt([min] [, max])`, `pickRandom(array)`
_random
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _randomInt(min, max) { return Math.floor(min + distribution() * (max - min)); } // This is a function for generating a random matrix recursively.
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See also: random, randomInt, pickRandom @param {string} name Name of a distribution. Choose from 'uniform', 'normal'. @return {Object} Returns a distribution object containing functions: `random([size] [, min] [, max])`, `randomInt([min] [, max])`, `pickRandom(array)`
_randomInt
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _randomDataForMatrix(size, min, max, randFunc) { var data = []; size = size.slice(0); if (size.length > 1) { for (var i = 0, length = size.shift(); i < length; i++) { data.push(_randomDataForMatrix(size, min, max, randFunc)); } } else { for (var _i2 = 0, _length = size.shift(); _i2 < _length; _i2++) { data.push(randFunc(min, max)); } } return data; }
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See also: random, randomInt, pickRandom @param {string} name Name of a distribution. Choose from 'uniform', 'normal'. @return {Object} Returns a distribution object containing functions: `random([size] [, min] [, max])`, `randomInt([min] [, max])`, `pickRandom(array)`
_randomDataForMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _var(array, normalization) { var sum = 0; var num = 0; if (array.length === 0) { throw new SyntaxError('Function var requires one or more parameters (0 provided)'); } // calculate the mean and number of elements deepForEach(array, function (value) { try { sum = add(sum, value); num++; } catch (err) { throw improveErrorMessage(err, 'var', value); } }); if (num === 0) throw new Error('Cannot calculate var of an empty array'); var mean = divide(sum, num); // calculate the variance sum = 0; deepForEach(array, function (value) { var diff = subtract(value, mean); sum = add(sum, multiply(diff, diff)); }); if (isNaN(sum)) { return sum; } switch (normalization) { case 'uncorrected': return divide(sum, num); case 'biased': return divide(sum, num + 1); case 'unbiased': var zero = type.isBigNumber(sum) ? new type.BigNumber(0) : 0; return num === 1 ? zero : divide(sum, num - 1); default: throw new Error('Unknown normalization "' + normalization + '". ' + 'Choose "unbiased" (default), "uncorrected", or "biased".'); } }
Recursively calculate the variance of an n-dimensional array @param {Array} array @param {string} normalization Determines how to normalize the variance: - 'unbiased' The sum of squared errors is divided by (n - 1) - 'uncorrected' The sum of squared errors is divided by n - 'biased' The sum of squared errors is divided by (n + 1) @return {number | BigNumber} variance @private
_var
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _varDim(array, dim, normalization) { try { if (array.length === 0) { throw new SyntaxError('Function var requires one or more parameters (0 provided)'); } return apply(array, dim, function (x) { return _var(x, normalization); }); } catch (err) { throw improveErrorMessage(err, 'var'); } }
Recursively calculate the variance of an n-dimensional array @param {Array} array @param {string} normalization Determines how to normalize the variance: - 'unbiased' The sum of squared errors is divided by (n - 1) - 'uncorrected' The sum of squared errors is divided by n - 'biased' The sum of squared errors is divided by (n + 1) @return {number | BigNumber} variance @private
_varDim
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Range(start, end, step) { if (!(this instanceof Range)) { throw new SyntaxError('Constructor must be called with the new operator'); } var hasStart = start !== null && start !== undefined; var hasEnd = end !== null && end !== undefined; var hasStep = step !== null && step !== undefined; if (hasStart) { if (type.isBigNumber(start)) { start = start.toNumber(); } else if (typeof start !== 'number') { throw new TypeError('Parameter start must be a number'); } } if (hasEnd) { if (type.isBigNumber(end)) { end = end.toNumber(); } else if (typeof end !== 'number') { throw new TypeError('Parameter end must be a number'); } } if (hasStep) { if (type.isBigNumber(step)) { step = step.toNumber(); } else if (typeof step !== 'number') { throw new TypeError('Parameter step must be a number'); } } this.start = hasStart ? parseFloat(start) : 0; this.end = hasEnd ? parseFloat(end) : 0; this.step = hasStep ? parseFloat(step) : 1; }
Create a range. A range has a start, step, and end, and contains functions to iterate over the range. A range can be constructed as: const range = new Range(start, end) const range = new Range(start, end, step) To get the result of the range: range.forEach(function (x) { console.log(x) }) range.map(function (x) { return math.sin(x) }) range.toArray() Example usage: const c = new Range(2, 6) // 2:1:5 c.toArray() // [2, 3, 4, 5] const d = new Range(2, -3, -1) // 2:-1:-2 d.toArray() // [2, 1, 0, -1, -2] @class Range @constructor Range @param {number} start included lower bound @param {number} end excluded upper bound @param {number} [step] step size, default value is 1
Range
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function ResultSet(entries) { if (!(this instanceof ResultSet)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.entries = entries || []; }
A ResultSet contains a list or results @class ResultSet @param {Array} entries @constructor ResultSet
ResultSet
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT