'use strict'; function factory (type, config, load, typed, math) { var parse = load(require('../../expression/parse')); var ConstantNode = load(require('../../expression/node/ConstantNode')); var FunctionNode = load(require('../../expression/node/FunctionNode')); var OperatorNode = load(require('../../expression/node/OperatorNode')); var ParenthesisNode = load(require('../../expression/node/ParenthesisNode')); var SymbolNode = load(require('../../expression/node/SymbolNode')); var Node = load(require('../../expression/node/Node')); var simplifyConstant = load(require('./simplify/simplifyConstant')); var util = load(require('./simplify/util')); var isCommutative = util.isCommutative; var isAssociative = util.isAssociative; var flatten = util.flatten; var unflattenr = util.unflattenr; var unflattenl = util.unflattenl; var createMakeNodeFunction = util.createMakeNodeFunction; /** * 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: * * var 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)](http://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions) * - [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification) * * Syntax: * * simplify(expr) * simplify(expr, rules) * * Examples: * * math.simplify('2 * 1 * x ^ (2 - 1)'); // Node {2 * x} * var f = math.parse('2 * 1 * x ^ (2 - 1)'); * math.simplify(f); // Node {2 * x} * * See also: * * derivative, parse, eval * * @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` */ var simplify = typed('simplify', { 'string': function (expr) { return simplify(parse(expr), simplify.rules); }, 'string, Array': function (expr, rules) { return simplify(parse(expr), rules); }, 'Node': function (expr) { return simplify(expr, simplify.rules); }, 'Node, Array': function (expr, rules) { rules = _buildRules(rules); var res = removeParens(expr); var visited = {}; var str = res.toString({parenthesis: 'all'}); while(!visited[str]) { visited[str] = true; _lastsym = 0; // counter for placeholder symbols for (var i=0; i c1 * n1' */ function _buildRules(rules) { // Array of rules to be used to simplify expressions var ruleSet = []; for(var i=0; i'); if (lr.length !== 2) { throw SyntaxError('Could not parse rule: ' + rule); } rule = {l: lr[0], r: lr[1]}; /* 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 (newRule.l.isOperatorNode && 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; } var _lastsym = 0; function _getExpandPlaceholderSymbol() { return new SymbolNode('_p' + _lastsym++); } /** * 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. */ var applyRule = typed('applyRule', { 'Node, Object': function (node, rule) { //console.log('Entering applyRule(' + node.toString() + ')'); // Do not clone node unless we find a match var res = node; // First replace our child nodes with their simplified versions // If a child could not be simplified, the assignments will have // no effect since the node is returned unchanged if (res instanceof OperatorNode || res instanceof FunctionNode) { if (res.args) { for(var i=0; i [ * +(node1, +(node2, node3)), * +(node2, +(node1, node3)), * +(node3, +(node1, node2))] * */ function getSplits(node, context) { var res = []; var right, rightArgs; var makeNode = createMakeNodeFunction(node); if (isCommutative(node, context)) { for (var i=0; i= 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(!node.isConstantNode) { 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(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 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. */ function _exactMatch(p, q) { if(p instanceof ConstantNode && q instanceof ConstantNode) { if(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