Takes a node that might represent a multiplication with a polynomial term and flattens it appropriately so the coefficient and symbol are grouped together. Returns a new list of operands from this node that should be multiplied together.
541528
function maybeFlattenPolynomialTerm(node) {
  // We recurse on the left side of the tree to find operands so far
  const operands = getOperands(node.args[0], '*');

  // If the last operand (so far) under * was a constant, then it's a
  // polynomial term.
  // e.g. 2*5*6x creates a tree where the top node is implicit multiplcation
  // and the left branch goes to the tree with 2*5*6, and the right operand
  // is the symbol x. We want to check that the last argument on the left (in
  // this example 6) is a constant.
  const lastOperand = operands.pop();

  // in the above example, node.args[1] would be the symbol x
  const nextOperand = flattenOperands(node.args[1]);

  // a coefficient can be constant or a fraction of constants
  if (Node.Type.isConstantOrConstantFraction(lastOperand)) {
    // we replace the constant (which we popped) with constant*symbol
    operands.push(
      Node.Creator.operator('*', [lastOperand, nextOperand], true));
  }
  // Now we know it isn't a polynomial term, it's just another seperate operand
  else {
    operands.push(lastOperand);
    operands.push(nextOperand);
  }
  return operands;
}
1003021
function(symbol1, symbol2) {
            var result, remainder, factored, den;
            factored = core.Algebra.Factor.factor(symbol1.clone());
            den = factored.getDenom();
            if(!den.isConstant('all')) {
                symbol1 = _.expand(Symbol.unwrapPARENS(_.multiply(factored, den.clone())));
            }
            else
                //reset the denominator since we're not dividing by it anymore
                den = new Symbol(1); 
            result = __.div(symbol1, symbol2);
            remainder = _.divide(result[1], symbol2);
            return _.divide(_.add(result[0], remainder), den);
        }
1095422
def _flatterm_iter(cls, expression: Expression) -> Iterator[TermAtom]:
        """"""
        if isinstance(expression, Operation):
            yield type(expression)
            for operand in op_iter(expression):
                yield from cls._flatterm_iter(operand)
            yield OPERATION_END
        elif isinstance(expression, SymbolWildcard):
            yield expression.symbol_type
        elif isinstance(expression, (Symbol, Wildcard)):
            yield expression
        else:
            assert False, "Unreachable unless a new unsupported expression type is added."
35204
def convert_squeeze(node, **kwargs):
    
    name, input_nodes, attrs = get_inputs(node, kwargs)

    axis = attrs.get("axis", None)
    if not axis:
        raise AttributeError("Squeeze: Missing axis attribute: ONNX currently requires axis to "
                             "be specified for squeeze operator")
    axis = convert_string_to_list(axis)

    node = onnx.helper.make_node(
        "Squeeze",
        input_nodes,
        [name],
        axes=axis,
        name=name,
    )
    return [node]
864864
function factorMultiplicands(node) {
  const newNode = clone(node);
  const radicandNode = getRadicandNode(node);

  let children = [];
  let factored = false;
  radicandNode.args.forEach(child => {
    if (Node.PolynomialTerm.isPolynomialTerm(child)) {
      const polyTerm = new Node.PolynomialTerm(child);
      const coeffNode = polyTerm.getCoeffNode();
      const polyTermNoCoeff = Node.Creator.polynomialTerm(
        polyTerm.getSymbolNode(), polyTerm.getExponentNode(), null);
      if (coeffNode) {
        const factorNodes = getFactorNodes(coeffNode);
        if (factorNodes.length > 1) {
          factored = true;
        }
        children = children.concat(factorNodes);
      }
      children.push(polyTermNoCoeff);
    }
    else {
      const factorNodes = getFactorNodes(child);
      if (factorNodes.length > 1) {
        factored = true;
      }
      children = children.concat(factorNodes);
    }
  });

  if (factored) {
    newNode.args[0] = Node.Creator.operator('*', children);
    return Node.Status.nodeChanged(
      ChangeTypes.FACTOR_INTO_PRIMES, node, newNode);
  }

  return Node.Status.noChange(node);
}
406537
final public void Multiplication() throws ParseException {
    Unary();
    label_13:
    while (true) {
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case MULT:
      case DIV0:
      case DIV1:
      case MOD0:
      case MOD1:
        ;
        break;
      default:
        jj_la1[27] = jj_gen;
        break label_13;
      }
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case MULT:
        jj_consume_token(MULT);
                  AstMult jjtn001 = new AstMult(JJTMULT);
                  boolean jjtc001 = true;
                  jjtree.openNodeScope(jjtn001);
        try {
          Unary();
        } catch (Throwable jjte001) {
                  if (jjtc001) {
                    jjtree.clearNodeScope(jjtn001);
                    jjtc001 = false;
                  } else {
                    jjtree.popNode();
                  }
                  if (jjte001 instanceof RuntimeException) {
                    {if (true) throw (RuntimeException)jjte001;}
                  }
                  if (jjte001 instanceof ParseException) {
                    {if (true) throw (ParseException)jjte001;}
                  }
                  {if (true) throw (Error)jjte001;}
        } finally {
                  if (jjtc001) {
                    jjtree.closeNodeScope(jjtn001,  2);
                  }
        }
        break;
      case DIV0:
      case DIV1:
        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
        case DIV0:
          jj_consume_token(DIV0);
          break;
        case DIV1:
          jj_consume_token(DIV1);
          break;
        default:
          jj_la1[28] = jj_gen;
          jj_consume_token(-1);
          throw new ParseException();
        }
                           AstDiv jjtn002 = new AstDiv(JJTDIV);
                           boolean jjtc002 = true;
                           jjtree.openNodeScope(jjtn002);
        try {
          Unary();
        } catch (Throwable jjte002) {
                           if (jjtc002) {
                             jjtree.clearNodeScope(jjtn002);
                             jjtc002 = false;
                           } else {
                             jjtree.popNode();
                           }
                           if (jjte002 instanceof RuntimeException) {
                             {if (true) throw (RuntimeException)jjte002;}
                           }
                           if (jjte002 instanceof ParseException) {
                             {if (true) throw (ParseException)jjte002;}
                           }
                           {if (true) throw (Error)jjte002;}
        } finally {
                           if (jjtc002) {
                             jjtree.closeNodeScope(jjtn002,  2);
                           }
        }
        break;
      case MOD0:
      case MOD1:
        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
        case MOD0:
          jj_consume_token(MOD0);
          break;
        case MOD1:
          jj_consume_token(MOD1);
          break;
        default:
          jj_la1[29] = jj_gen;
          jj_consume_token(-1);
          throw new ParseException();
        }
                           AstMod jjtn003 = new AstMod(JJTMOD);
                           boolean jjtc003 = true;
                           jjtree.openNodeScope(jjtn003);
        try {
          Unary();
        } catch (Throwable jjte003) {
                           if (jjtc003) {
                             jjtree.clearNodeScope(jjtn003);
                             jjtc003 = false;
                           } else {
                             jjtree.popNode();
                           }
                           if (jjte003 instanceof RuntimeException) {
                             {if (true) throw (RuntimeException)jjte003;}
                           }
                           if (jjte003 instanceof ParseException) {
                             {if (true) throw (ParseException)jjte003;}
                           }
                           {if (true) throw (Error)jjte003;}
        } finally {
                           if (jjtc003) {
                             jjtree.closeNodeScope(jjtn003,  2);
                           }
        }
        break;
      default:
        jj_la1[30] = jj_gen;
        jj_consume_token(-1);
        throw new ParseException();
      }
    }
  }
1181724
def simplify_polynomial(polynomial, monomial_substitutions):
    
    if isinstance(polynomial, (int, float, complex)):
        return polynomial
    polynomial = (1.0 * polynomial).expand(mul=True,
                                           multinomial=True)
    if is_number_type(polynomial):
        return polynomial
    if polynomial.is_Mul:
        elements = [polynomial]
    else:
        elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1]
    new_polynomial = 0
    # Identify its constituent monomials
    for element in elements:
        monomial, coeff = separate_scalar_factor(element)
        monomial = apply_substitutions(monomial, monomial_substitutions)
        new_polynomial += coeff * monomial
    return new_polynomial
705566
function isMultiplicationOfTerms(node) {
  if (Node.Type.isParenthesis(node)) {
    return isMultiplicationOfTerms(node.content);
  }
  return (Node.Type.isOperator(node, '*') &&
          !Node.PolynomialTerm.isPolynomialTerm(node));
}
530827
def _process_monomial(self, monomial, n_vars):
        
        coeff, monomial = monomial.as_coeff_Mul()
        k = 0
        # Have we seen this monomial before?
        conjugate = False
        try:
            # If yes, then we improve sparsity by reusing the
            # previous variable to denote this entry in the matrix
            k = self.monomial_index[monomial]
        except KeyError:
            # An extra round of substitutions is granted on the conjugate of
            # the monomial if all the variables are Hermitian
            daggered_monomial = \
                apply_substitutions(Dagger(monomial), self.substitutions,
                                    self.pure_substitution_rules)
            try:
                k = self.monomial_index[daggered_monomial]
                conjugate = True
            except KeyError:
                # Otherwise we define a new entry in the associated
                # array recording the monomials, and add an entry in
                # the moment matrix
                k = n_vars + 1
                self.monomial_index[monomial] = k
        if conjugate:
            k = -k
        return k, coeff
858716
def divide(x1, x2, output_shape=None, name=None):
  
  output_shape = convert_to_shape(output_shape)
  if not isinstance(x2, Tensor):
    return ScalarMultiplyOperation(x1, 1.0 / x2).outputs[0]
  with tf.name_scope(name, default_name="divide"):
    x1, x2 = binary_arguments_to_tensors(x1, x2)
    return multiply(x1, reciprocal(x2), output_shape=output_shape)
131744
function groupCoefficientsForAdding(node) {
  let newNode = clone(node);

  const polynomialTermList = newNode.args.map(n => new Node.PolynomialTerm(n));
  const coefficientList = polynomialTermList.map(p => p.getCoeffNode(true));
  const sumOfCoefficents = Node.Creator.parenthesis(
    Node.Creator.operator('+', coefficientList));
  // TODO: changegroups should also be on the before node, on all the
  // coefficients, but changegroups with polyTerm gets messy so let's tackle
  // that later.
  sumOfCoefficents.changeGroup = 1;

  // Polynomial terms that can be added together must share the same symbol
  // name and exponent. Get that name and exponent from the first term
  const firstTerm = polynomialTermList[0];
  const exponentNode = firstTerm.getExponentNode();
  const symbolNode = firstTerm.getSymbolNode();
  newNode = Node.Creator.polynomialTerm(
    symbolNode, exponentNode, sumOfCoefficents);

  return Node.Status.nodeChanged(
    ChangeTypes.GROUP_COEFFICIENTS, node, newNode);
}
1085243
def roots(cls, degree, domain, kind):
        """"""
        basis_coefs = cls._basis_monomial_coefs(degree)
        basis_poly = cls.functions_factory(basis_coefs, domain, kind)
        return basis_poly.roots()
1314205
def from_list(cls, terms_list, coefficient=1.0):
        
        if not all([isinstance(op, tuple) for op in terms_list]):
            raise TypeError("The type of terms_list should be a list of (name, index) "
                            "tuples suitable for PauliTerm().")

        pterm = PauliTerm("I", 0)
        assert all([op[0] in PAULI_OPS for op in terms_list])

        indices = [op[1] for op in terms_list]
        assert all(_valid_qubit(index) for index in indices)

        # this is because from_list doesn't call simplify in order to be more efficient.
        if len(set(indices)) != len(indices):
            raise ValueError("Elements of PauliTerm that are allocated using from_list must "
                             "be on disjoint qubits. Use PauliTerm multiplication to simplify "
                             "terms instead.")

        for op, index in terms_list:
            if op != "I":
                pterm._ops[index] = op
        if not isinstance(coefficient, Number):
            raise ValueError("coefficient of PauliTerm must be a Number.")
        pterm.coefficient = complex(coefficient)
        return pterm
336709
function canAddLikeTermPolynomialNodes(node) {
  if (!Node.Type.isOperator(node) || node.op !== '+') {
    return false;
  }
  const args = node.args;
  if (!args.every(n => Node.PolynomialTerm.isPolynomialTerm(n))) {
    return false;
  }
  if (args.length === 1) {
    return false;
  }

  const polynomialTermList = args.map(n => new Node.PolynomialTerm(n));

  // to add terms, they must have the same symbol name *and* exponent
  const firstTerm = polynomialTermList[0];
  const sharedSymbol = firstTerm.getSymbolName();
  const sharedExponentNode = firstTerm.getExponentNode(true);

  const restTerms = polynomialTermList.slice(1);
  return restTerms.every(term => {
    const haveSameSymbol = sharedSymbol === term.getSymbolName();
    const exponentNode = term.getExponentNode(true);
    const haveSameExponent = exponentNode.equals(sharedExponentNode);
    return haveSameSymbol && haveSameExponent;
  });
}
947517
def p_term_mult(self, tree):
        ''' '''
        tree.value = convertstr(tree[0].value) * convertstr(tree[2].value)
415304
def build_graph(formula):
    '''  '''
    graph = {}

    for clause in formula:
        for (lit, _) in clause:
            for neg in [False, True]:
                graph[(lit, neg)] = []

    for ((a_lit, a_neg), (b_lit, b_neg)) in formula:
        add_edge(graph, (a_lit, a_neg), (b_lit, not b_neg))
        add_edge(graph, (b_lit, b_neg), (a_lit, not a_neg))

    return graph
90828
def flatten_tree(test, enumerator, exp):
  
  return sum((flatten_tree(test, enumerator, subx) for subx in enumerator(exp)), []) if test(exp) else [exp]