def test_issue_9398(): from sympy import Number, cancel assert cancel(1e-14) != 0 assert cancel(1e-14 * I) != 0 assert simplify(1e-14) != 0 assert simplify(1e-14 * I) != 0 assert (I * Number(1.) * Number(10)**Number(-14)).simplify() != 0 assert cancel(1e-20) != 0 assert cancel(1e-20 * I) != 0 assert simplify(1e-20) != 0 assert simplify(1e-20 * I) != 0 assert cancel(1e-100) != 0 assert cancel(1e-100 * I) != 0 assert simplify(1e-100) != 0 assert simplify(1e-100 * I) != 0 f = Float("1e-1000") assert cancel(f) != 0 assert cancel(f * I) != 0 assert simplify(f) != 0 assert simplify(f * I) != 0
def a_gcd(a, b): x, y = Number(1) * a, Number(1) * b if Abs(x) > Abs(y): x, y = y, x if x == 0: print(y) return y if y == 0: print(x) return x print("a and b are ") print(str(a) + " and " + str(b)) c = conjugate(x) pseudo_quot = simplify((y * c) / (x * c)) print("The pseudo-quotient is ") print(str(pseudo_quot)) p1, q1 = re(pseudo_quot), im(pseudo_quot) print( "The fractional real and imaginary parts of the pseudo-quotient are ") print(str(p1) + " and " + str(q1)) quot = p1.round() + I * q1.round() print("The nearest-integers-quotient is ") print(str(quot)) rem = simplify(y - quot * x) print("The remainder is ") print(rem) print("---") a_gcd(x, rem)
def get_equation(self, lhs_func: Function, rhs_funcs: Tuple[Function, ...]) -> Eq: if self.min_points != (0, 0): raise NotImplementedError( "not implemented equation in the case of " "positive left or positive right" ) rhs_func = rhs_funcs[0] subs: Dict[str, Expr] = { child: reduce(mul, [var(k) for k in parent_vars], 1) for child, parent_vars in self.reversed_extra_parameters.items() } left_vars = reduce( mul, [ var(k) for k in self.left_sided_parameters if k not in self.parent_fusion_parameters ], 1, ) right_vars = reduce( mul, [ var(k) for k in self.right_sided_parameters if k not in self.parent_fusion_parameters ], 1, ) p, q = Number(1), Number(1) for parent_fuse_parameter, fuse_type in zip( self.parent_fusion_parameters, self.fusion_types ): if fuse_type in ("left", "both"): p *= var(parent_fuse_parameter) if fuse_type in ("right", "both"): q *= var(parent_fuse_parameter) if left_vars == 1 and right_vars == 1 and p == q: raise NotImplementedError( "Not handled case with no left and right vars, and new fuse " "parameter, or only parent fusion parameter covered entire region" ) subs1 = {**subs} subs1[self.fuse_parameter] = q / left_vars subs2 = {**subs} subs2[self.fuse_parameter] = p / right_vars return Eq( lhs_func, ( (q * right_vars * rhs_func.subs(subs1, simultaneous=True)) - (p * left_vars * rhs_func.subs(subs2, simultaneous=True)) ) / (q * right_vars - p * left_vars), )
def test_simplemulti(): f = Function("f") x = Symbol("x") y = Symbol("y") z = Symbol("z") a = Number(1) b = Number("1.1") c = Number(1)/4 res = [f(x),f(y),f(z)] assert f([x,y,z])==res assert f((x,y,z))==res assert f([x, [y, [a, 1], [b, z]], [[c]]])==[f(x), [f(y), [f(a), f(1)], [f(b), f(z)]], [[f(c)]]]
def __new__(cls, call, pointer, params=None, **kwargs): if isinstance(pointer, str): pointer = Symbol(pointer) if isinstance(call, str): call = Symbol(call) elif not isinstance(call, (CallFromPointer, DefFunction, sympy.Symbol)): # NOTE: we need `sympy.Symbol`, rather than just (devito) `Symbol` # because otherwise it breaks upon certain reconstructions on SymPy-1.8, # due to the way `bound_symbols` and `canonical_variables` interact raise ValueError("`call` must be CallFromPointer, DefFunction, or Symbol") _params = [] for p in as_tuple(params): if isinstance(p, str): _params.append(Symbol(p)) elif isinstance(p, Expr): _params.append(p) else: try: _params.append(Number(p)) except TypeError: raise ValueError("`params` must be Expr, numbers or str") params = Tuple(*_params) obj = sympy.Expr.__new__(cls, call, pointer, params) obj.call = call obj.pointer = pointer obj.params = params return obj
def test_surface_energy(self): # For a nonstoichiometric case, the cheimcal potentials do not # cancel out, they serve as a reservoir for any missing atoms for slab_entry in self.MgO_slab_entry_dict[(1, 1, 1)].keys(): se = slab_entry.surface_energy(self.MgO_ucell_entry, ref_entries=[self.Mg_ucell_entry]) self.assertEqual(tuple(se.as_coefficients_dict().keys()), (Number(1), Symbol("delu_Mg"))) # For the case of a clean, stoichiometric slab, the surface energy # should be constant (i.e. surface energy is a constant). all_se = [] ECu = self.Cu_ucell_entry.energy_per_atom for hkl in self.Cu_entry_dict.keys(): slab_entry = list(self.Cu_entry_dict[hkl].keys())[0] se = slab_entry.surface_energy(self.Cu_ucell_entry) all_se.append(se) # Manually calculate surface energy manual_se = (slab_entry.energy - ECu * len(slab_entry.structure)) / (2 * slab_entry.surface_area) self.assertArrayAlmostEqual(float(se), manual_se, 10) # The (111) facet should be the most stable clean111_entry = list(self.Cu_entry_dict[(1, 1, 1)].keys())[0] se_Cu111 = clean111_entry.surface_energy(self.Cu_ucell_entry) self.assertEqual(min(all_se), se_Cu111)
def pivot_on_pivot_item(table, rowIndex, columnIndex): pivot_row = rowMultiplication(table[rowIndex], Number('1') / table[rowIndex][columnIndex]) f = lambda r: rowAddition(r, pivot_row, -r[columnIndex]) return [ f(table[i]) if i != rowIndex else pivot_row for i in range(len(table)) ]
def get_equation(self, lhs_func: Function, rhs_funcs: Tuple[Function, ...]) -> Eq: rhs_func = rhs_funcs[0] subs: Dict[Symbol, Expr] = { var(child): var(parent) for parent, child in self.extra_parameters.items() } for k in self.new_parameters: subs[k] = Number(1) return Eq(lhs_func, rhs_func.subs(subs, simultaneous=True))
def initial_conditions(self, check: int = 6) -> List[Expr]: """ Returns a list with the initial conditions to size `check` of the CombinatorialClass. """ def monomial(parameters: Dict[str, int]) -> Expr: return reduce(mul, [var(k)**val for k, val in parameters.items()], Number(1)) return [ sum( sum(Number(1) for _ in self.objects_of_size(n, **parameters)) * monomial(parameters) for parameters in self.possible_parameters(n)) for n in range(check + 1) ]
def as_symbol(expr): """Cast composite SymPy objects to :class:`sympy.Symbol`.""" from devito.types import Dimension try: return Number(expr) except (TypeError, ValueError): pass if isinstance(expr, str): return Symbol(expr) elif isinstance(expr, Dimension): return Symbol(expr.name) elif expr.is_Symbol: return expr elif isinstance(expr, Indexed): return expr.base.label else: raise TypeError("Cannot extract symbol from type %s" % type(expr))
def as_symbol(expr): """ Extract the "main" symbol from a SymPy object. """ try: return Number(expr) except (TypeError, ValueError): pass if isinstance(expr, str): return Symbol(expr) elif isinstance(expr, Dimension): return Symbol(expr.name) elif expr.is_Symbol: return expr elif isinstance(expr, Indexed): return expr.base.label else: raise TypeError("Cannot extract symbol from type %s" % type(expr))
def __init__(self, name, param, arg, circuit=None): """Create a new instruction. name = instruction name string param = list of real parameters arg = list of pairs (Register, index) circuit = QuantumCircuit or CompositeGate containing this instruction """ for i in arg: if not isinstance(i[0], Register): raise QISKitError("argument not (Register, int) tuple") self.name = name self.param = [] for p in param: if not isinstance(p, Basic): # if item in param not symbolic, make it symbolic self.param.append(Number(p)) else: self.param.append(p) self.arg = arg self.control = None # tuple (ClassicalRegister, int) for "if" self.circuit = circuit
def as_symbol(expr): """Cast to sympy.Symbol.""" from devito.types import Dimension try: if expr.is_Symbol: return expr except AttributeError: pass try: return Number(expr) except (TypeError, ValueError): pass if isinstance(expr, str): return Symbol(expr) elif isinstance(expr, Dimension): return Symbol(expr.name) elif expr.is_Symbol: return expr elif isinstance(expr, Indexed): return expr.base.label else: raise TypeError("Cannot extract symbol from type %s" % type(expr))
def get_initial_conditions(self, check: int = 6) -> List[Expr]: """ Compute the initial conditions of the root class. It will use the `count_objects_of_size` method if implemented, else resort to the method on the `initial_conditions` method on `CombinatorialClass. """ logger.info("Computing initial conditions") try: return [ sum( Number(self.count_objects_of_size(n=n, **parameters)) * reduce(mul, [var(k) ** val for k, val in parameters.items()], 1) for parameters in self.root.possible_parameters(n) ) for n in range(check + 1) ] except NotImplementedError as e: logger.info( "Reverting to generating objects from root for initial " "conditions due to:\nNotImplementedError: %s", e, ) return self.root.initial_conditions(check)
def __init__(self, name, param, arg, circuit=None): """Create a new instruction. name = instruction name string param = list of real parameters arg = list of pairs (Register, index) circuit = QuantumCircuit or CompositeGate containing this instruction """ for i in arg: if not isinstance(i[0], Register): raise QISKitError("argument not (Register, int) tuple") self.name = name self.param = [] for single_param in param: if not isinstance(single_param, (Basic, complex)): # If the item in param is not symbolic and not complex (used # by InitializeGate), make it symbolic. self.param.append(Number(single_param)) else: self.param.append(single_param) self.arg = arg self.control = None # tuple (ClassicalRegister, int) for "if" self.circuit = circuit
def symbolic_size(self): """The symbolic size of this dimension.""" return Number(self.size)
def test_Number_new(): """" Test for Number constructor """ # Expected behavior on numbers and strings assert Number(1) is S.One assert Number(2).__class__ is Integer assert Number(-622).__class__ is Integer assert Number(5, 3).__class__ is Rational assert Number(5.3).__class__ is Float assert Number('1') is S.One assert Number('2').__class__ is Integer assert Number('-622').__class__ is Integer assert Number('5/3').__class__ is Rational assert Number('5.3').__class__ is Float raises(ValueError, lambda: Number('cos')) raises(TypeError, lambda: Number(cos)) a = Rational(3, 5) assert Number(a) is a # Check idempotence on Numbers
constructions.append((steps, c_i, r_i)) except struct.error as e: return constructions if __name__ == "__main__": if len(sys.argv) == 1: constructions = read_fd(sys.stdin.buffer) else: with open(sys.argv[1], "rb") as f: constructions = read_fd(f) for n, (steps, c_i, r_i) in enumerate(constructions[:], 0): base = ExactCons() #a = Symbol("a", positive=True) #b = Symbol("b", positive=True) #init_isosceles(base, a, b) init_scalene_normal(base, Number(3), Number(4), Number(5)) #print(base.points) #print(base.circles) #print(base.goal) #break try: base.apply_steps(steps) except TypeError as e: print("Couldn't resolve comparison") continue except ValueError as e: print("Wrong number of intersections at some step") continue x = simplify(base.goal[0] - base.points[c_i][0]) y = simplify(base.goal[1] - base.points[c_i][1]) r = simplify(base.goal[2] - hypot(base.points[r_i][0] - base.goal[0], base.points[r_i][1] - base.goal[1]))
def monomial(parameters: Dict[str, int]) -> Expr: return reduce(mul, [var(k)**val for k, val in parameters.items()], Number(1))
def divides(a,b): x = b/a print(re(x)) real = factor_list(re(x)*Number(1))[0] imaginary = factor_list(im(x)*Number(1))[0] return real.is_Integer and imaginary.is_Integer
def _mb_int(n): from sympy.core.numbers import ImaginaryUnit try: return Number(n) except TypeError: return n
def t_REAL(self, t): r'(([0-9]+|([0-9]+)?\.[0-9]+|[0-9]+\.)[eE][+-]?[0-9]+)|(([0-9]+)?\.[0-9]+|[0-9]+\.)' t.value = Number(t.value) # tad nasty, see mkfloat.py to see how this is derived from python spec return t
from sympy import Number, sqrt, I from numpy import eye as identity, mat, vectorize def _mb_int(n): from sympy.core.numbers import ImaginaryUnit try: return Number(n) except TypeError: return n mb_int = vectorize(_mb_int) asint = vectorize(lambda n: Number(n)) simp = vectorize(lambda x: x.simplify()) conj = vectorize(lambda n: n.conjugate()) def decomp_one(xs, col, row0, row1): """ Perform one round of decomposition on (row0, col) and (row1, col) of xs. """ j, k, m, n = (row0, col), (row0, row1), (row1, col), (row1, row1) a, b = xs[j], xs[m] denom = sqrt(a * a.conjugate() + b * b.conjugate()) rv = asint(mat(identity(len(xs), dtype=int))) rv[j] = (a.conjugate() / denom).simplify() rv[k] = (b.conjugate() / denom).simplify() rv[m] = (b / denom).simplify() rv[n] = -(a / denom).simplify() return rv
def symbolic_size(self): """The symbolic size of this dimension.""" try: return Number(self.size) except TypeError: return self.rtargs[0].as_symbol
def make_zero_list(length: int): return [Number('0') for _ in range(length)]
def to_symbols(x): if type(x) != type([]): return Number(str(x)) return list(map(to_symbols, x))
def list_to_symbols(l): return list(map(lambda x: Number(str(x)), l))