if isinstance(a, VectorExpr): args[i].is_Vector = _compute_is_vector(args[i]) # the following is used to avoid infinite recursion if not isinstance(obj, (Add, Mul)): return obj.func(*args) obj = obj.func._from_args(args) if isinstance(obj, VectorExpr): obj.is_Vector = _compute_is_vector(obj) return obj if __name__ == "__main__": # a = VectorSymbol("a") # b = VectorSymbol("b") # x = Symbol("x") # # # b = VectorSymbol("b") # # # r = VecMul(a + b, 3) # # # print(r.func, r.is_Vector, r) # # # a.norm.doit().diff(x) # nabla = Nabla() # expr = VecMul(4, (x * a.div + 1)) # print(expr.is_Vector) # # expr = VecMul(3, a + b) # # print(expr.is_Vector) # wtf() a = VectorSymbol("a") x = Symbol("x") Add(x, x)
def test_series(): from sympy.abc import x i = Integral(cos(x)) e = i.lseries(x) assert i.nseries(x, n=8).removeO() == Add(*[e.next() for j in range(4)])
def test_cancellation(): assert NS(Add(pi, Rational(1, 10**1000), -pi, evaluate=False), 15, maxn=1200) == '1.00000000000000e-1000'
def test_nested_substitution(): # Substitution within a substitution. e = Add(Pow(w * x + y, 2), sqrt(w * x + y)) substs, reduced = cse([e]) assert substs == [(x0, w * x + y)] assert reduced == [sqrt(x0) + x0**2]
def variance_prop(expr, consts=(), include_covar=False): r"""Symbolically propagates variance (`\sigma^2`) for expressions. This is computed as as seen in [1]_. Parameters ========== expr : Expr A sympy expression to compute the variance for. consts : sequence of Symbols, optional Represents symbols that are known constants in the expr, and thus have zero variance. All symbols not in consts are assumed to be variant. include_covar : bool, optional Flag for whether or not to include covariances, default=False. Returns ======= var_expr : Expr An expression for the total variance of the expr. The variance for the original symbols (e.g. x) are represented via instance of the Variance symbol (e.g. Variance(x)). Examples ======== >>> from sympy import symbols, exp >>> from sympy.stats.error_prop import variance_prop >>> x, y = symbols('x y') >>> variance_prop(x + y) Variance(x) + Variance(y) >>> variance_prop(x * y) x**2*Variance(y) + y**2*Variance(x) >>> variance_prop(exp(2*x)) 4*exp(4*x)*Variance(x) References ========== .. [1] https://en.wikipedia.org/wiki/Propagation_of_uncertainty """ args = expr.args if len(args) == 0: if expr in consts: return S.Zero elif isinstance(expr, RandomSymbol): return Variance(expr).doit() elif isinstance(expr, Symbol): return Variance(RandomSymbol(expr)).doit() else: return S.Zero nargs = len(args) var_args = list(map(variance_prop, args, repeat(consts, nargs), repeat(include_covar, nargs))) if isinstance(expr, Add): var_expr = Add(*var_args) if include_covar: terms = [2 * Covariance(_arg0_or_var(x), _arg0_or_var(y)).expand() \ for x, y in combinations(var_args, 2)] var_expr += Add(*terms) elif isinstance(expr, Mul): terms = [v/a**2 for a, v in zip(args, var_args)] var_expr = simplify(expr**2 * Add(*terms)) if include_covar: terms = [2*Covariance(_arg0_or_var(x), _arg0_or_var(y)).expand()/(a*b) \ for (a, b), (x, y) in zip(combinations(args, 2), combinations(var_args, 2))] var_expr += Add(*terms) elif isinstance(expr, Pow): b = args[1] v = var_args[0] * (expr * b / args[0])**2 var_expr = simplify(v) elif isinstance(expr, exp): var_expr = simplify(var_args[0] * expr**2) else: # unknown how to proceed, return variance of whole expr. var_expr = Variance(expr) return var_expr
def test_doit(): a = OperationsOnlyMatrix([[Add(x,x, evaluate=False)]]) assert a[0] != 2*x assert a.doit() == Matrix([[2*x]])
def wigner_d_small(J, beta): u"""Return the small Wigner d matrix for angular momentum J. INPUT: - ``J`` - An integer, half-integer, or sympy symbol for the total angular momentum of the angular momentum space being rotated. - ``beta`` - A real number representing the Euler angle of rotation about the so-called line of nodes. See [Edmonds74]_. OUTPUT: A matrix representing the corresponding Euler angle rotation( in the basis of eigenvectors of `J_z`). .. math :: \\mathcal{d}_{\\beta} = \\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big) The components are calculated using the general form [Edmonds74]_, equation 4.1.15. Examples ======== >>> from sympy import Integer, symbols, pi, pprint >>> from sympy.physics.wigner import wigner_d_small >>> half = 1/Integer(2) >>> beta = symbols("beta", real=True) >>> pprint(wigner_d_small(half, beta), use_unicode=True) ⎡ ⎛β⎞ ⎛β⎞⎤ ⎢cos⎜─⎟ sin⎜─⎟⎥ ⎢ ⎝2⎠ ⎝2⎠⎥ ⎢ ⎥ ⎢ ⎛β⎞ ⎛β⎞⎥ ⎢-sin⎜─⎟ cos⎜─⎟⎥ ⎣ ⎝2⎠ ⎝2⎠⎦ >>> pprint(wigner_d_small(2*half, beta), use_unicode=True) ⎡ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎤ ⎢ cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟ sin ⎜─⎟ ⎥ ⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎥ ⎢ ⎥ ⎢ ⎛β⎞ ⎛β⎞ 2⎛β⎞ 2⎛β⎞ ⎛β⎞ ⎛β⎞⎥ ⎢-√2⋅sin⎜─⎟⋅cos⎜─⎟ - sin ⎜─⎟ + cos ⎜─⎟ √2⋅sin⎜─⎟⋅cos⎜─⎟⎥ ⎢ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠⎥ ⎢ ⎥ ⎢ 2⎛β⎞ ⎛β⎞ ⎛β⎞ 2⎛β⎞ ⎥ ⎢ sin ⎜─⎟ -√2⋅sin⎜─⎟⋅cos⎜─⎟ cos ⎜─⎟ ⎥ ⎣ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎝2⎠ ⎦ From table 4 in [Edmonds74]_ >>> pprint(wigner_d_small(half, beta).subs({beta:pi/2}), use_unicode=True) ⎡ √2 √2⎤ ⎢ ── ──⎥ ⎢ 2 2 ⎥ ⎢ ⎥ ⎢-√2 √2⎥ ⎢──── ──⎥ ⎣ 2 2 ⎦ >>> pprint(wigner_d_small(2*half, beta).subs({beta:pi/2}), ... use_unicode=True) ⎡ √2 ⎤ ⎢1/2 ── 1/2⎥ ⎢ 2 ⎥ ⎢ ⎥ ⎢-√2 √2 ⎥ ⎢──── 0 ── ⎥ ⎢ 2 2 ⎥ ⎢ ⎥ ⎢ -√2 ⎥ ⎢1/2 ──── 1/2⎥ ⎣ 2 ⎦ >>> pprint(wigner_d_small(3*half, beta).subs({beta:pi/2}), ... use_unicode=True) ⎡ √2 √6 √6 √2⎤ ⎢ ── ── ── ──⎥ ⎢ 4 4 4 4 ⎥ ⎢ ⎥ ⎢-√6 -√2 √2 √6⎥ ⎢──── ──── ── ──⎥ ⎢ 4 4 4 4 ⎥ ⎢ ⎥ ⎢ √6 -√2 -√2 √6⎥ ⎢ ── ──── ──── ──⎥ ⎢ 4 4 4 4 ⎥ ⎢ ⎥ ⎢-√2 √6 -√6 √2⎥ ⎢──── ── ──── ──⎥ ⎣ 4 4 4 4 ⎦ >>> pprint(wigner_d_small(4*half, beta).subs({beta:pi/2}), ... use_unicode=True) ⎡ √6 ⎤ ⎢1/4 1/2 ── 1/2 1/4⎥ ⎢ 4 ⎥ ⎢ ⎥ ⎢-1/2 -1/2 0 1/2 1/2⎥ ⎢ ⎥ ⎢ √6 √6 ⎥ ⎢ ── 0 -1/2 0 ── ⎥ ⎢ 4 4 ⎥ ⎢ ⎥ ⎢-1/2 1/2 0 -1/2 1/2⎥ ⎢ ⎥ ⎢ √6 ⎥ ⎢1/4 -1/2 ── -1/2 1/4⎥ ⎣ 4 ⎦ """ M = [J - i for i in range(2 * J + 1)] d = zeros(2 * J + 1) for i, Mi in enumerate(M): for j, Mj in enumerate(M): # We get the maximum and minimum value of sigma. sigmamax = max([-Mi - Mj, J - Mj]) sigmamin = min([0, J - Mi]) dij = sqrt( factorial(J + Mi) * factorial(J - Mi) / factorial(J + Mj) / factorial(J - Mj)) terms = [(-1)**(J - Mi - s) * binomial(J + Mj, J - Mi - s) * binomial(J - Mj, s) * cos(beta / 2)**(2 * s + Mi + Mj) * sin(beta / 2)**(2 * J - 2 * s - Mj - Mi) for s in range(sigmamin, sigmamax + 1)] d[i, j] = dij * Add(*terms) return ImmutableMatrix(d)
def convert_to_dual(model): dual_model = model.interface.Model() maximization = model.objective.direction == "max" if maximization: sign = 1 else: sign = -1 coefficients = {} dual_objective = {} # Add dual variables from primal constraints: for constraint in model.constraints: if constraint.expression == 0: continue if not constraint.is_Linear: raise NotImplementedError("Non-linear problems are currently not supported: " + str(constraint)) if constraint.lb is None and constraint.ub is None: continue if constraint.lb == constraint.ub: const_var = model.interface.Variable("dual_" + constraint.name + "_constraint", lb=-1000, ub=1000) dual_model._add_variable(const_var) if constraint.lb != 0: dual_objective[const_var] = sign * constraint.lb for variable, coef in constraint.expression.as_coefficients_dict().items(): coefficients.setdefault(variable.name, {})[const_var] = sign * coef else: if constraint.lb is not None: lb_var = model.interface.Variable("dual_" + constraint.name + "_constraint_lb", lb=0, ub=1000) dual_model._add_variable(lb_var) if constraint.lb != 0: dual_objective[lb_var] = -sign * constraint.lb if constraint.ub is not None: ub_var = model.interface.Variable("dual_" + constraint.name + "_constraint_ub", lb=0, ub=1000) dual_model._add_variable(ub_var) if constraint.ub != 0: dual_objective[ub_var] = sign * constraint.ub for variable, coef in constraint.expression.as_coefficients_dict().items(): if constraint.lb is not None: coefficients.setdefault(variable.name, {})[lb_var] = -sign * coef if constraint.ub is not None: coefficients.setdefault(variable.name, {})[ub_var] = sign * coef # Add dual variables from primal bounds for variable in model.variables: if variable.type != "continuous": raise NotImplementedError("Integer variables are currently not supported: " + str(variable)) if variable.lb is None or variable.lb < 0: raise ValueError("Problem is not in standard form (" + variable.name + " can be negative)") if variable.lb > 0: bound_var = model.interface.Variable("dual_" + variable.name + "_lb", lb=0, ub=1000) dual_model._add_variable(bound_var) coefficients.setdefault(variable.name, {})[bound_var] = -sign * 1 dual_objective[bound_var] = -sign * variable.lb if variable.ub is not None: bound_var = model.interface.Variable("dual_" + variable.name + "_ub", lb=0, ub=1000) dual_model._add_variable(bound_var) coefficients.setdefault(variable.name, {})[bound_var] = sign * 1 if variable.ub != 0: dual_objective[bound_var] = sign * variable.ub # Add dual constraints from primal objective primal_objective_dict = model.objective.expression.as_coefficients_dict() for variable in model.variables: expr = Add(*((coef * dual_var) for dual_var, coef in coefficients[variable.name].items())) obj_coef = primal_objective_dict[variable] if maximization: const = model.interface.Constraint(expr, lb=obj_coef, name="dual_" + variable.name) else: const = model.interface.Constraint(expr, ub=obj_coef) dual_model._add_constraint(const) # Make dual objective expr = Add(*((coef * dual_var) for dual_var, coef in dual_objective.items() if coef != 0)) if maximization: objective = model.interface.Objective(expr, direction="min") else: objective = model.interface.Objective(expr, direction="max") dual_model.objective = objective return dual_model
def test_dim_simplify_add(): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) assert dim_simplify(Add(L, L)) == L assert dim_simplify(L + L) == L
def ast(self): "Return the full abstract syntax tree of the model." return Add(*list(self.models.values()))
def test_cse_single(): # Simple substitution. e = Add(Pow(x + y, 2), sqrt(x + y)) substs, reduced = cse([e], optimizations=[]) assert substs == [(x0, x + y)] assert reduced == [sqrt(x0) + x0**2]
def atomic_ordering_energy(self, dbe, disordered_phase_name, ordered_phase_name): """ Return the atomic ordering contribution in symbolic form. Description follows Servant and Ansara, Calphad, 2001. """ disordered_model = self.__class__(dbe, self.components, disordered_phase_name) constituents = [sorted(set(c).intersection(self.components)) \ for c in dbe.phases[ordered_phase_name].constituents] # Fix variable names variable_rename_dict = {} for atom in disordered_model.energy.atoms(v.SiteFraction): # Replace disordered phase site fractions with mole fractions of # ordered phase site fractions. # Special case: Pure vacancy sublattices all_species_in_sublattice = \ dbe.phases[disordered_phase_name].constituents[ atom.sublattice_index] if atom.species == 'VA' and len(all_species_in_sublattice) == 1: # Assume: Pure vacancy sublattices are always last vacancy_subl_index = \ len(dbe.phases[ordered_phase_name].constituents)-1 variable_rename_dict[atom] = \ v.SiteFraction( ordered_phase_name, vacancy_subl_index, atom.species) else: # All other cases: replace site fraction with mole fraction variable_rename_dict[atom] = \ self.mole_fraction( atom.species, ordered_phase_name, constituents, dbe.phases[ordered_phase_name].sublattices ) # Save all of the ordered energy contributions # This step is why this routine must be called _last_ in build_phase ordered_energy = Add(*list(self.models.values())) self.models.clear() # Copy the disordered energy contributions into the correct bins for name, value in disordered_model.models.items(): self.models[name] = value.xreplace(variable_rename_dict) molefraction_dict = {} # Construct a dictionary that replaces every site fraction with its # corresponding mole fraction in the disordered state for sitefrac in ordered_energy.atoms(v.SiteFraction): all_species_in_sublattice = \ dbe.phases[ordered_phase_name].constituents[ sitefrac.sublattice_index] if sitefrac.species == 'VA' and len(all_species_in_sublattice) == 1: # pure-vacancy sublattices should not be replaced # this handles cases like AL,NI,VA:AL,NI,VA:VA and # ensures the VA's don't get mixed up continue molefraction_dict[sitefrac] = \ self.mole_fraction(sitefrac.species, ordered_phase_name, constituents, dbe.phases[ordered_phase_name].sublattices) return ordered_energy - ordered_energy.subs(molefraction_dict, simultaneous=True)
def redlich_kister_sum(self, phase, param_search, param_query): """ Construct parameter in Redlich-Kister polynomial basis, using the Muggianu ternary parameter extension. """ rk_terms = [] # search for desired parameters params = param_search(param_query) for param in params: # iterate over every sublattice mixing_term = S.One for subl_index, comps in enumerate(param['constituent_array']): comp_symbols = None # convert strings to symbols if comps[0] == '*': # Handle wildcards in constituent array comp_symbols = \ [ v.SiteFraction(phase.name, subl_index, comp) for comp in set(phase.constituents[subl_index])\ .intersection(self.components) ] mixing_term *= Add(*comp_symbols) else: comp_symbols = \ [ v.SiteFraction(phase.name, subl_index, comp) for comp in comps ] mixing_term *= Mul(*comp_symbols) # is this a higher-order interaction parameter? if len(comps) == 2 and param['parameter_order'] > 0: # interacting sublattice, add the interaction polynomial mixing_term *= Pow(comp_symbols[0] - \ comp_symbols[1], param['parameter_order']) if len(comps) == 3: # 'parameter_order' is an index to a variable when # we are in the ternary interaction parameter case # NOTE: The commercial software packages seem to have # a "feature" where, if only the zeroth # parameter_order term of a ternary parameter is specified, # the other two terms are automatically generated in order # to make the parameter symmetric. # In other words, specifying only this parameter: # PARAMETER G(FCC_A1,AL,CR,NI;0) 298.15 +30300; 6000 N ! # Actually implies: # PARAMETER G(FCC_A1,AL,CR,NI;0) 298.15 +30300; 6000 N ! # PARAMETER G(FCC_A1,AL,CR,NI;1) 298.15 +30300; 6000 N ! # PARAMETER G(FCC_A1,AL,CR,NI;2) 298.15 +30300; 6000 N ! # # If either 1 or 2 is specified, no implicit parameters are # generated. # We need to handle this case. if param['parameter_order'] == 0: # are _any_ of the other parameter_orders specified? ternary_param_query = ( (where('phase_name') == param['phase_name']) & \ (where('parameter_type') == \ param['parameter_type']) & \ (where('constituent_array') == \ param['constituent_array']) ) other_tern_params = param_search(ternary_param_query) if len(other_tern_params) == 1 and \ other_tern_params[0] == param: # only the current parameter is specified # We need to generate the other two parameters. order_one = copy.deepcopy(param) order_one['parameter_order'] = 1 order_two = copy.deepcopy(param) order_two['parameter_order'] = 2 # Add these parameters to our iteration. params.extend((order_one, order_two)) # Include variable indicated by parameter order index # Perform Muggianu adjustment to site fractions mixing_term *= comp_symbols[param['parameter_order']].subs( self._Muggianu_correction_dict(comp_symbols), simultaneous=True) rk_terms.append(mixing_term * param['parameter']) return Add(*rk_terms)
def _Add(a, b): return Add(a, b, evaluate=False)
def test_2127(): assert Add(evaluate=False) == 0 assert Mul(evaluate=False) == 1 assert Mul(x + y, evaluate=False).is_Add
def test_dim_simplify_rec(): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) assert dim_simplify(Mul(Add(L, L), T)) == L*T assert dim_simplify((L + L) * T) == L*T
def add_terms(terms, prec, target_prec): """ Helper for evalf_add. Adds a list of (mpfval, accuracy) terms. Returns ------- - None, None if there are no non-zero terms; - terms[0] if there is only 1 term; - scaled_zero if the sum of the terms produces a zero by cancellation e.g. mpfs representing 1 and -1 would produce a scaled zero which need special handling since they are not actually zero and they are purposely malformed to ensure that they can't be used in anything but accuracy calculations; - a tuple that is scaled to target_prec that corresponds to the sum of the terms. The returned mpf tuple will be normalized to target_prec; the input prec is used to define the working precision. XXX explain why this is needed and why one can't just loop using mpf_add """ terms = [t for t in terms if not iszero(t)] if not terms: return None, None elif len(terms) == 1: return terms[0] # see if any argument is NaN or oo and thus warrants a special return special = [] from sympy.core.numbers import Float for t in terms: arg = Float._new(t[0], 1) if arg is S.NaN or arg.is_infinite: special.append(arg) if special: from sympy.core.add import Add rv = evalf(Add(*special), prec + 4, {}) return rv[0], rv[2] working_prec = 2 * prec sum_man, sum_exp, absolute_error = 0, 0, MINUS_INF for x, accuracy in terms: sign, man, exp, bc = x if sign: man = -man absolute_error = max(absolute_error, bc + exp - accuracy) delta = exp - sum_exp if exp >= sum_exp: # x much larger than existing sum? # first: quick test if ((delta > working_prec) and ((not sum_man) or delta - bitcount(abs(sum_man)) > working_prec)): sum_man = man sum_exp = exp else: sum_man += (man << delta) else: delta = -delta # x much smaller than existing sum? if delta - bc > working_prec: if not sum_man: sum_man, sum_exp = man, exp else: sum_man = (sum_man << delta) + man sum_exp = exp if not sum_man: return scaled_zero(absolute_error) if sum_man < 0: sum_sign = 1 sum_man = -sum_man else: sum_sign = 0 sum_bc = bitcount(sum_man) sum_accuracy = sum_exp + sum_bc - absolute_error r = normalize(sum_sign, sum_man, sum_exp, sum_bc, target_prec, rnd), sum_accuracy return r
def test_ops(): k0 = Ket(0) k1 = Ket(1) k = 2*I*k0 - (x/sqrt(2))*k1 assert k == Add(Mul(2, I, k0), Mul(Rational(-1, 2), x, Pow(2, Rational(1, 2)), k1))
def run(self, product=None, max_predictions=float("inf"), min_production=.1, timeout=None, silent=False): """Run pathway prediction for a desired product. Parameters ---------- product : Metabolite, str Metabolite or id or name of metabolite to find production pathways for. max_predictions : int, optional The maximum number of predictions to compute. min_production : float The minimum acceptable production flux to product. timeout : int The time limit [seconds] per attempted prediction. Returns ------- list A list of pathways (list of reactions) """ product = self._find_product(product) pathways = list() with TimeMachine() as tm: tm(do=partial(setattr, self.model.solver.configuration, 'timeout', timeout), undo=partial(setattr, self.model.solver.configuration, 'timeout', self.model.solver.configuration.timeout)) try: demand_reaction = self.model.reactions.get_by_id('DM_' + product.id) except KeyError: demand_reaction = self.model.add_demand(product) tm(do=str, undo=partial(self.model.remove_reactions, [demand_reaction], delete=False)) demand_reaction.lower_bound = min_production counter = 1 while counter <= max_predictions: logger.info('Predicting pathway No. %d' % counter) try: solution = self.model.solve() except SolveError as e: logger.info( 'No pathway could be predicted. Terminating pathway predictions.' ) logger.error(e) break vars_to_cut = list() for i, y_var_id in enumerate(self._y_vars_ids): y_var = self.model.solver.variables[y_var_id] if y_var.primal == 1.0: vars_to_cut.append(y_var) logger.info(vars_to_cut) if len(vars_to_cut) == 0: # no pathway found: logger.info( "It seems %s is a native product in model %s. Let's see if we can find better heterologous pathways." % (product, self.model)) # knockout adapter with native product for adapter in self.adpater_reactions: if product in adapter.metabolites: logger.info( 'Knocking out adapter reaction %s containing native product.' % adapter) adapter.knock_out(time_machine=tm) continue pathway = [ self.model.reactions.get_by_id(y_var.name[2:]) for y_var in vars_to_cut ] logger.info('Pathway predicted: %s' % '\t'.join([ r.build_reaction_string(use_metabolite_names=True) for r in pathway ])) # Figure out adapter reactions to include adapters = [ adapter for adapter in self.adpater_reactions if abs(adapter.flux) != 0 ] # Figure out exchange reactions to include exchanges = [ exchange for exchange in self._exchanges if abs(exchange.flux) != 0 ] pathway = PathwayResult(pathway, exchanges, adapters, demand_reaction) if not silent: util.display_pathway(pathway, counter) pathways.append(pathway) integer_cut = self.model.solver.interface.Constraint( Add(*vars_to_cut), name="integer_cut_" + str(counter), ub=len(vars_to_cut) - 1) logger.info('Adding integer cut.') tm(do=partial(self.model.solver._add_constraint, integer_cut), undo=partial(self.model.solver._remove_constraint, integer_cut)) counter += 1 # self.model.solver.configuration.verbosity = 0 return PathwayPredictions(pathways)
def minimum_substrate_analysis(self, conditions, sheet, substrates, objective, objective_linspace, output=None, output_sheet=None, minimum_growth=0.1, **kwargs ): if not substrates: substrates = [] df = read_excel(os.path.join(self.conditions_directory, conditions), sheet) with self.model: self.apply_conditions(data_frame=df) _growth = self.maximize(is_pfba=True) if _growth < minimum_growth: raise ValueError(f'Wrong Environmental Conditions, as growth rate is {_growth}') qp_expression = [arg for substrate in substrates for arg in self.get_reaction(substrate).flux_expression.args] qp_expression = Add(*qp_expression) qp_objective = self.model.problem.Objective(qp_expression, direction='max') self.model.objective = qp_objective self.maximize(is_pfba=False, growth=False) data = [] for objective_rate in objective_linspace: objective_rate = round(objective_rate, 3) with self.model: self.get_reaction(objective).bounds = (objective_rate, objective_rate) qp_sol = self.maximize(is_pfba=False, growth=False) sol = self.summary_from_solution(solution=qp_sol, objectives=False, cols_to_drop=['reaction', 'metabolite', 'factor'] ) sol.columns = [f'{objective}_{objective_rate}'] sol.loc[self.biomass_reaction.id] = qp_sol.fluxes[self.biomass_reaction.id] sol.loc['objective_function'] = qp_sol.objective_value sol.loc['status'] = qp_sol.status data.append(sol) data = concat(data, axis=1, join='outer') return data
from typing import Any, Dict, List, Tuple, Type from sympy.integrals.meijerint import _create_lookup_table from sympy import latex, Eq, Add, Symbol t = {} # type: Dict[Tuple[Type, ...], List[Any]] _create_lookup_table(t) doc = "" for about, category in sorted(t.items()): if about == (): doc += 'Elementary functions:\n\n' else: doc += 'Functions involving ' + ', '.join( '`%s`' % latex(list(category[0][0].atoms(func))[0]) for func in about) + ':\n\n' for formula, gs, cond, hint in category: if not isinstance(gs, list): g = Symbol('\\text{generated}') else: g = Add(*[fac * f for (fac, f) in gs]) obj = Eq(formula, g) if cond is True: cond = "" else: cond = ',\\text{ if } %s' % latex(cond) doc += ".. math::\n %s%s\n\n" % (latex(obj), cond) __doc__ = doc
def _eval_expand_func(self, **hints): from sympy import exp, I, floor, Add, Poly, Dummy, exp_polar, unpolarify z, s, a = self.args if z == 1: return zeta(s, a) if s.is_Integer and s <= 0: t = Dummy('t') p = Poly((t + a)**(-s), t) start = 1 / (1 - t) res = S(0) for c in reversed(p.all_coeffs()): res += c * start start = t * start.diff(t) return res.subs(t, z) if a.is_Rational: # See section 18 of # Kelly B. Roach. Hypergeometric Function Representations. # In: Proceedings of the 1997 International Symposium on Symbolic and # Algebraic Computation, pages 205-211, New York, 1997. ACM. # TODO should something be polarified here? add = S(0) mul = S(1) # First reduce a to the interaval (0, 1] if a > 1: n = floor(a) if n == a: n -= 1 a -= n mul = z**(-n) add = Add(*[-z**(k - n) / (a + k)**s for k in range(n)]) elif a <= 0: n = floor(-a) + 1 a += n mul = z**n add = Add(*[z**(n - 1 - k) / (a - k - 1)**s for k in range(n)]) m, n = S([a.p, a.q]) zet = exp_polar(2 * pi * I / n) root = z**(1 / n) return add + mul * n**(s - 1) * Add(*[ polylog(s, zet**k * root)._eval_expand_func(**hints) / (unpolarify(zet)**k * root)**m for k in range(n) ]) # TODO use minpoly instead of ad-hoc methods when issue 5888 is fixed if isinstance(z, exp) and (z.args[0] / (pi * I)).is_Rational or z in [-1, I, -I]: # TODO reference? if z == -1: p, q = S([1, 2]) elif z == I: p, q = S([1, 4]) elif z == -I: p, q = S([-1, 4]) else: arg = z.args[0] / (2 * pi * I) p, q = S([arg.p, arg.q]) return Add(*[ exp(2 * pi * I * k * p / q) / q**s * zeta(s, (k + a) / q) for k in range(q) ]) return lerchphi(z, s, a)
def u(expr, x): from sympy import Add, exp, exp_polar r = _rewrite_single(expr, x) e = Add(*[res[0] * res[2] for res in r[0]]).replace(exp_polar, exp) # XXX Hack? assert verify_numerically(e, expr, x)
def test_performance_of_adding_order(): l = list(x**i for i in range(1000)) l.append(O(x**1001)) assert Add(*l).subs(x, 1) == O(1)
def run(expr): # Return semantic (rebuilt expression, factorization candidates) if expr.is_Number: return expr, {'coeffs': expr} elif expr.is_Function: return expr, {'funcs': expr} elif expr.is_Pow: return expr, {'pows': expr} elif expr.is_Symbol or expr.is_Indexed or expr.is_Atom: return expr, {} elif expr.is_Add: args, candidates = zip(*[run(arg) for arg in expr.args]) candidates = ReducerMap.fromdicts(*candidates) funcs = candidates.getall('funcs', []) pows = candidates.getall('pows', []) coeffs = candidates.getall('coeffs', []) # Functions/Pows are collected first, coefficients afterwards terms = [] w_funcs = [] w_pows = [] w_coeffs = [] for i in args: _args = i.args if any(j in funcs for j in _args): w_funcs.append(i) elif any(j in pows for j in _args): w_pows.append(i) elif any(j in coeffs for j in _args): w_coeffs.append(i) else: terms.append(i) # Collect common funcs w_funcs = Add(*w_funcs, evaluate=False) w_funcs = collect(w_funcs, funcs, evaluate=False) try: terms.extend([ Mul(k, collect_const(v), evaluate=False) for k, v in w_funcs.items() ]) except AttributeError: assert w_funcs == 0 # Collect common pows w_pows = Add(*w_pows, evaluate=False) w_pows = collect(w_pows, pows, evaluate=False) try: terms.extend([ Mul(k, collect_const(v), evaluate=False) for k, v in w_pows.items() ]) except AttributeError: assert w_pows == 0 # Collect common temporaries (r0, r1, ...) w_coeffs = Add(*w_coeffs, evaluate=False) symbols = retrieve_symbols(w_coeffs) if symbols: w_coeffs = collect(w_coeffs, symbols, evaluate=False) try: terms.extend([ Mul(k, collect_const(v), evaluate=False) for k, v in w_coeffs.items() ]) except AttributeError: assert w_coeffs == 0 else: terms.append(w_coeffs) # Collect common coefficients rebuilt = Add(*terms) rebuilt = collect_const(rebuilt) return rebuilt, {} elif expr.is_Mul: args, candidates = zip(*[run(arg) for arg in expr.args]) return Mul(*args), ReducerMap.fromdicts(*candidates) elif expr.is_Equality: args, candidates = zip(*[run(expr.lhs), run(expr.rhs)]) return expr.func(*args, evaluate=False), ReducerMap.fromdicts(*candidates) else: args, candidates = zip(*[run(arg) for arg in expr.args]) return expr.func(*args), ReducerMap.fromdicts(*candidates)
def _separate_sq(p): """ helper function for ``_minimal_polynomial_sq`` It selects a rational ``g`` such that the polynomial ``p`` consists of a sum of terms whose surds squared have gcd equal to ``g`` and a sum of terms with surds squared prime with ``g``; then it takes the field norm to eliminate ``sqrt(g)`` See simplify.simplify.split_surds and polytools.sqf_norm. Examples ======== >>> from sympy import sqrt >>> from sympy.abc import x >>> from sympy.polys.numberfields import _separate_sq >>> p= -x + sqrt(2) + sqrt(3) + sqrt(7) >>> p = _separate_sq(p); p -x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8 >>> p = _separate_sq(p); p -x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20 >>> p = _separate_sq(p); p -x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400 """ from sympy.simplify.simplify import _split_gcd, _mexpand from sympy.utilities.iterables import sift def is_sqrt(expr): return expr.is_Pow and expr.exp is S.Half # p = c1*sqrt(q1) + ... + cn*sqrt(qn) -> a = [(c1, q1), .., (cn, qn)] a = [] for y in p.args: if not y.is_Mul: if is_sqrt(y): a.append((S.One, y**2)) elif y.is_Atom: a.append((y, S.One)) elif y.is_Pow and y.exp.is_integer: a.append((y, S.One)) else: raise NotImplementedError continue sifted = sift(y.args, is_sqrt) a.append((Mul(*sifted[False]), Mul(*sifted[True])**2)) a.sort(key=lambda z: z[1]) if a[-1][1] is S.One: # there are no surds return p surds = [z for y, z in a] for i in range(len(surds)): if surds[i] != 1: break g, b1, b2 = _split_gcd(*surds[i:]) a1 = [] a2 = [] for y, z in a: if z in b1: a1.append(y * z**S.Half) else: a2.append(y * z**S.Half) p1 = Add(*a1) p2 = Add(*a2) p = _mexpand(p1**2) - _mexpand(p2**2) return p
def __radd__(self, other): if type(other) is tuple: other = ContentChange(*other) elif type(other) is int: other = ContentChange(other) return Add(self, other)
class TestAllGood(object): # These latex strings should parse to the corresponding SymPy expression GOOD_PAIRS = [ ("0", 0), ("1", 1), ("-3.14", -3.14), ("5-3", _Add(5, -3)), ("(-7.13)(1.5)", _Mul(Rational('-7.13'), Rational('1.5'))), ("\\left(-7.13\\right)\\left(1.5\\right)", _Mul(Rational('-7.13'), Rational('1.5'))), ("x", x), ("2x", 2 * x), ("x^2", x**2), ("x^{3 + 1}", x**_Add(3, 1)), ("x^{\\left\\{3 + 1\\right\\}}", x**_Add(3, 1)), ("-3y + 2x", _Add(_Mul(2, x), Mul(-1, 3, y, evaluate=False))), ("-c", -c), ("a \\cdot b", a * b), ("a / b", a / b), ("a \\div b", a / b), ("a + b", a + b), ("a + b - a", Add(a, b, _Mul(-1, a), evaluate=False)), ("a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)), ("a^2 + b^2 != 2c^2", Ne(a**2 + b**2, 2 * c**2)), ("a\\mod b", Mod(a, b)), ("\\sin \\theta", sin(theta)), ("\\sin(\\theta)", sin(theta)), ("\\sin\\left(\\theta\\right)", sin(theta)), ("\\sin^{-1} a", asin(a)), ("\\sin a \\cos b", _Mul(sin(a), cos(b))), ("\\sin \\cos \\theta", sin(cos(theta))), ("\\sin(\\cos \\theta)", sin(cos(theta))), ("\\arcsin(a)", asin(a)), ("\\arccos(a)", acos(a)), ("\\arctan(a)", atan(a)), ("\\sinh(a)", sinh(a)), ("\\cosh(a)", cosh(a)), ("\\tanh(a)", tanh(a)), ("\\sinh^{-1}(a)", asinh(a)), ("\\cosh^{-1}(a)", acosh(a)), ("\\tanh^{-1}(a)", atanh(a)), ("\\arcsinh(a)", asinh(a)), ("\\arccosh(a)", acosh(a)), ("\\arctanh(a)", atanh(a)), ("\\arsinh(a)", asinh(a)), ("\\arcosh(a)", acosh(a)), ("\\artanh(a)", atanh(a)), ("\\operatorname{arcsinh}(a)", asinh(a)), ("\\operatorname{arccosh}(a)", acosh(a)), ("\\operatorname{arctanh}(a)", atanh(a)), ("\\operatorname{arsinh}(a)", asinh(a)), ("\\operatorname{arcosh}(a)", acosh(a)), ("\\operatorname{artanh}(a)", atanh(a)), ("\\operatorname{gcd}(a, b)", UnevaluatedExpr(gcd(a, b))), ("\\operatorname{lcm}(a, b)", UnevaluatedExpr(lcm(a, b))), ("\\operatorname{gcd}(a,b)", UnevaluatedExpr(gcd(a, b))), ("\\operatorname{lcm}(a,b)", UnevaluatedExpr(lcm(a, b))), ("\\operatorname{floor}(a)", floor(a)), ("\\operatorname{ceil}(b)", ceiling(b)), ("\\cos^2(x)", cos(x)**2), ("\\cos(x)^2", cos(x)**2), ("\\gcd(a, b)", UnevaluatedExpr(gcd(a, b))), ("\\lcm(a, b)", UnevaluatedExpr(lcm(a, b))), ("\\gcd(a,b)", UnevaluatedExpr(gcd(a, b))), ("\\lcm(a,b)", UnevaluatedExpr(lcm(a, b))), ("\\floor(a)", floor(a)), ("\\ceil(b)", ceiling(b)), ("\\max(a, b)", Max(a, b)), ("\\min(a, b)", Min(a, b)), ("\\frac{a}{b}", a / b), ("\\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))), ("\\frac{7}{3}", _Mul(7, _Pow(3, -1))), ("(\\csc x)(\\sec y)", csc(x) * sec(y)), ("\\lim_{x \\to 3} a", Limit(a, x, 3)), ("\\lim_{x \\rightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\Rightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\longrightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\Longrightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\to 3^{+}} a", Limit(a, x, 3, dir='+')), ("\\lim_{x \\to 3^{-}} a", Limit(a, x, 3, dir='-')), ("\\infty", oo), ("\\infty\\%", oo), ("\\$\\infty", oo), ("-\\infty", -oo), ("-\\infty\\%", -oo), ("-\\$\\infty", -oo), ("\\lim_{x \\to \\infty} \\frac{1}{x}", Limit(_Mul(1, _Pow(x, -1)), x, oo)), ("\\frac{d}{dx} x", Derivative(x, x)), ("\\frac{d}{dt} x", Derivative(x, t)), # ("f(x)", f(x)), # ("f(x, y)", f(x, y)), # ("f(x, y, z)", f(x, y, z)), # ("\\frac{d f(x)}{dx}", Derivative(f(x), x)), # ("\\frac{d\\theta(x)}{dx}", Derivative(theta(x), x)), ("|x|", _Abs(x)), ("\\left|x\\right|", _Abs(x)), ("||x||", _Abs(Abs(x))), ("|x||y|", _Abs(x) * _Abs(y)), ("||x||y||", _Abs(_Abs(x) * _Abs(y))), ("\\lfloor x\\rfloor", floor(x)), ("\\lceil y\\rceil", ceiling(y)), ("\\pi^{|xy|}", pi**_Abs(x * y)), ("\\frac{\\pi}{3}", _Mul(pi, _Pow(3, -1))), ("\\sin{\\frac{\\pi}{2}}", sin(_Mul(pi, _Pow(2, -1)), evaluate=False)), ("a+bI", a + I * b), ("e^{I\\pi}", -1), ("\\int x dx", Integral(x, x)), ("\\int x d\\theta", Integral(x, theta)), ("\\int (x^2 - y)dx", Integral(x**2 - y, x)), ("\\int x + a dx", Integral(_Add(x, a), x)), ("\\int da", Integral(1, a)), ("\\int_0^7 dx", Integral(1, (x, 0, 7))), ("\\int_a^b x dx", Integral(x, (x, a, b))), ("\\int^b_a x dx", Integral(x, (x, a, b))), ("\\int_{a}^b x dx", Integral(x, (x, a, b))), ("\\int^{b}_a x dx", Integral(x, (x, a, b))), ("\\int_{a}^{b} x dx", Integral(x, (x, a, b))), ("\\int_{ }^{}x dx", Integral(x, x)), ("\\int^{ }_{ }x dx", Integral(x, x)), ("\\int^{b}_{a} x dx", Integral(x, (x, a, b))), # ("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))), ("\\int (x+a)", Integral(_Add(x, a), x)), ("\\int a + b + c dx", Integral(Add(a, b, c, evaluate=False), x)), ("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)), ("\\int \\frac{3 dz}{z}", Integral(3 * Pow(z, -1), z)), ("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)), ("\\int \\frac{1}{a} + \\frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)), ("\\int \\frac{3 \\cdot d\\theta}{\\theta}", Integral(3 * _Pow(theta, -1), theta)), ("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)), ("x_0", Symbol('x_0', real=True)), ("x_{1}", Symbol('x_1', real=True)), ("x_a", Symbol('x_a', real=True)), ("x_{b}", Symbol('x_b', real=True)), ("h_\\theta", Symbol('h_{\\theta}', real=True)), ("h_\\theta ", Symbol('h_{\\theta}', real=True)), ("h_{\\theta}", Symbol('h_{\\theta}', real=True)), # ("h_{\\theta}(x_0, x_1)", Symbol('h_{theta}', real=True)(Symbol('x_{0}', real=True), Symbol('x_{1}', real=True))), ("x!", _factorial(x)), ("100!", _factorial(100)), ("\\theta!", _factorial(theta)), ("(x + 1)!", _factorial(_Add(x, 1))), ("\\left(x + 1\\right)!", _factorial(_Add(x, 1))), ("(x!)!", _factorial(_factorial(x))), ("x!!!", _factorial(_factorial(_factorial(x)))), ("5!7!", _Mul(_factorial(5), _factorial(7))), ("\\sqrt{x}", sqrt(x)), ("\\sqrt{x + b}", sqrt(_Add(x, b))), ("\\sqrt[3]{\\sin x}", root(sin(x), 3)), ("\\sqrt[y]{\\sin x}", root(sin(x), y)), ("\\sqrt[\\theta]{\\sin x}", root(sin(x), theta)), ("x < y", StrictLessThan(x, y)), ("x \\leq y", LessThan(x, y)), ("x > y", StrictGreaterThan(x, y)), ("x \\geq y", GreaterThan(x, y)), ("\\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))), ("\\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))), ("\\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))), ("\\sum^3_{k = 1} c", Sum(c, (k, 1, 3))), ("\\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))), ("\\sum_{n = 0}^{\\infty} \\frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))), ("\\prod_{a = b}^{c} x", Product(x, (a, b, c))), ("\\prod_{a = b}^c x", Product(x, (a, b, c))), ("\\prod^{c}_{a = b} x", Product(x, (a, b, c))), ("\\prod^c_{a = b} x", Product(x, (a, b, c))), ("\\ln x", _log(x, E)), ("\\ln xy", _log(x * y, E)), ("\\log x", _log(x, 10)), ("\\log xy", _log(x * y, 10)), # ("\\log_2 x", _log(x, 2)), ("\\log_{2} x", _log(x, 2)), # ("\\log_a x", _log(x, a)), ("\\log_{a} x", _log(x, a)), ("\\log_{11} x", _log(x, 11)), ("\\log_{a^2} x", _log(x, _Pow(a, 2))), ("[x]", x), ("[a + b]", _Add(a, b)), ("\\frac{d}{dx} [ \\tan x ]", Derivative(tan(x), x)), ("2\\overline{x}", 2 * Symbol('xbar', real=True)), ("2\\overline{x}_n", 2 * Symbol('xbar_n', real=True)), ("\\frac{x}{\\overline{x}_n}", x / Symbol('xbar_n', real=True)), ("\\frac{\\sin(x)}{\\overline{x}_n}", sin(Symbol('x', real=True)) / Symbol('xbar_n', real=True)), ("2\\bar{x}", 2 * Symbol('xbar', real=True)), ("2\\bar{x}_n", 2 * Symbol('xbar_n', real=True)), ("\\sin\\left(\\theta\\right) \\cdot4", sin(theta) * 4), ("\\ln\\left(\\theta\\right)", _log(theta, E)), ("\\ln\\left(x-\\theta\\right)", _log(x - theta, E)), ("\\ln\\left(\\left(x-\\theta\\right)\\right)", _log(x - theta, E)), ("\\ln\\left(\\left[x-\\theta\\right]\\right)", _log(x - theta, E)), ("\\ln\\left(\\left\\{x-\\theta\\right\\}\\right)", _log(x - theta, E)), ("\\ln\\left(\\left|x-\\theta\\right|\\right)", _log(_Abs(x - theta), E)), ("\\frac{1}{2}xy(x+y)", Mul(_Pow(2, -1), x, y, (x + y), evaluate=False)), ("\\frac{1}{2}\\theta(x+y)", Mul(_Pow(2, -1), theta, (x + y), evaluate=False)), ("1-f(x)", 1 - f * x), ("\\begin{matrix}1&2\\\\3&4\\end{matrix}", Matrix([[1, 2], [3, 4]])), ("\\begin{matrix}x&x^2\\\\\\sqrt{x}&x\\end{matrix}", Matrix([[x, x**2], [_Pow(x, S.Half), x]])), ("\\begin{matrix}\\sqrt{x}\\\\\\sin(\\theta)\\end{matrix}", Matrix([_Pow(x, S.Half), sin(theta)])), ("\\begin{pmatrix}1&2\\\\3&4\\end{pmatrix}", Matrix([[1, 2], [3, 4]])), ("\\begin{bmatrix}1&2\\\\3&4\\end{bmatrix}", Matrix([[1, 2], [3, 4]])), # scientific notation ("2.5\\times 10^2", 250), ("1,500\\times 10^{-1}", 150), # e notation ("2.5E2", 250), ("1,500E-1", 150), # multiplication without cmd ("2x2y", Mul(2, x, 2, y, evaluate=False)), ("2x2", Mul(2, x, 2, evaluate=False)), ("x2", x * 2), # lin alg processing ("\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(theta, Matrix([[1, 2], [3, 4]]), evaluate=False)), ("\\theta\\begin{matrix}1\\\\3\\end{matrix} - \\begin{matrix}-1\\\\2\\end{matrix}", MatAdd(MatMul(theta, Matrix([[1], [3]]), evaluate=False), MatMul(-1, Matrix([[-1], [2]]), evaluate=False), evaluate=False)), ("\\theta\\begin{matrix}1&0\\\\0&1\\end{matrix}*\\begin{matrix}3\\\\-2\\end{matrix}", MatMul(theta, Matrix([[1, 0], [0, 1]]), Matrix([3, -2]), evaluate=False)), ("\\frac{1}{9}\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(Pow(9, -1, evaluate=False), theta, Matrix([[1, 2], [3, 4]]), evaluate=False)), ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]), ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix};\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]), ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]), ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix},\\begin{pmatrix}1\\\\1\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1]), Matrix([1, 1, 1])]), ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right\\}", Matrix([1, 2, 3])), ("\\left{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right}", Matrix([1, 2, 3])), ("{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}}", Matrix([1, 2, 3])), # us dollars ("\\$1,000.00", 1000), ("\\$543.21", 543.21), ("\\$0.009", 0.009), # percentages ("100\\%", 1), ("1.5\\%", 0.015), ("0.05\\%", 0.0005), # empty set ("\\emptyset", S.EmptySet) ] def test_good_pair(self, s, eq): assert_equal(s, eq)
def test_evaluate_false(): for no in [0, False]: assert Add(3, 2, evaluate=no).is_Add assert Mul(3, 2, evaluate=no).is_Mul assert Pow(3, 2, evaluate=no).is_Pow assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0
def pdf(self, *syms): alpha = self.alpha B = Mul.fromiter(map(gamma, alpha)) / gamma(Add(*alpha)) return Mul.fromiter([sym**(a_k - 1) for a_k, sym in zip(alpha, syms)]) / B