def test(): """ We are considering electron muon scattering, following the feinmann diagram below. Assuming all particles have helicity one, and the CM-fram, motion in z-dir, meaning line 1 and 4 have spin up, line 3 and 4 have spin down. This gives the spinnors below. p2\ /p4 \ ^ \ / μ γ § § / \e ^ \. p1/ \p3 """ # This is to make sure sympy knows these are real numbers me, Ee, Em, mm = sp.symbols("me, Ee, mm, Em", positive=True) ap = sp.symbols("ap", positive=True) # sqrt(Ee + me) am = sp.symbols("am", positive=True) # sqrt(Ee - me) bp = sp.symbols("bp", positive=True) # sqrt(Em + mm) bm = sp.symbols("bm", positive=True) # sqrt(Em - mm) u1 = np.array([ap, 0, am, 0], dtype=type(I)) u2 = np.array([0, bp, 0, bm], dtype=type(I)) u3 = np.array([0, ap, 0, am], dtype=type(I)) u4 = np.array([bp, 0, bm, 0], dtype=type(I)) M = 0 for i in range(dim): M += g[i, i] * ((adj(u3) @ γ[i] @ u1) * (adj(u4) @ γ[i] @ u2)) M *= g ** 2 / (4 * am * bp * bm * ap) pprint(M)
def deriveMetricFromConnection(self, nameOfTargetCoordinateSystem): # check if the patch stores a coordsystem with the right name matches = [ cs for cs in self.coord_systems if cs.name == nameOfTargetCoordinateSystem ] if len(matches) < 1: raise "no coordinate system of the specified name found" elif len(matches) > 1: raise "more than one coord system with the specified name found" else: targetCoordinateSystem = matches[0] connections = targetCoordinateSystem.transforms #connections is a dictionary whose keys are CoordSystems # check if there is at least one metric representation in a connected coord system connectionsWithMetricRepresentation = { key: val for key, val in connections.items() if key in self.metricRepresentations } # in most cases there will be only one match (e.g. the cartesian cs) but it is possible to have more # so we chose the first that comes our way firstCoordSystem = list(connectionsWithMetricRepresentation.keys())[0] # now the question is to which of the metric representations of the patch it refers symbols, equations = connectionsWithMetricRepresentation[ firstCoordSystem] #compute the jacobian J = targetCoordinateSystem.jacobian(firstCoordSystem, symbols) pprint(J) # the first column of the jacobian contains the components of the # new base vectors in the old base # therefor the components of the new metric tensor # can be derived from the components of the old # by J.transposeLU()*g_old*J g_old = self.metricRepresentations[firstCoordSystem] oldBases = g_old.bases oB0 = oldBases[0] # first base print("oldBases") print(oldBases) if isinstance(oB0, VectorFieldBase): # the second base must be of the same type # in this case also newBase = VectorFieldBase("newBase", targetCoordinateSystem) newBase.connect(oB0, J) i, j = map(Idx, ['i', 'j']) g_new = TensorIndexSet("g_new") g_new[i, j] = g_old[i, j].rebase2([newBase, newBase]) return (g_new)
def _interactive_traversal(expr, stage): if stage > 0: print cprint("Current expression (stage ", BYELLOW, stage, END, "):") print BCYAN pprint(expr) print END if isinstance(expr, Basic): if expr.is_Add: args = expr.as_ordered_terms() elif expr.is_Mul: args = expr.as_ordered_factors() else: args = expr.args elif hasattr(expr, "__iter__"): args = list(expr) else: return expr n_args = len(args) if not n_args: return expr for i, arg in enumerate(args): cprint(GREEN, "[", BGREEN, i, GREEN, "] ", BLUE, type(arg), END) pprint(arg) print if n_args == 1: choices = '0' else: choices = '0-%d' % (n_args - 1) try: choice = raw_input("Your choice [%s,f,l,r,d,?]: " % choices) except EOFError: result = expr print else: if choice == '?': cprint( RED, "%s - select subexpression with the given index" % choices) cprint(RED, "f - select the first subexpression") cprint(RED, "l - select the last subexpression") cprint(RED, "r - select a random subexpression") cprint(RED, "d - done\n") result = _interactive_traversal(expr, stage) elif choice in ['d', '']: result = expr elif choice == 'f': result = _interactive_traversal(args[0], stage + 1) elif choice == 'l': result = _interactive_traversal(args[-1], stage + 1) elif choice == 'r': result = _interactive_traversal(random.choice(args), stage + 1) else: try: choice = int(choice) except ValueError: cprint(BRED, "Choice must be a number in %s range\n" % choices) result = _interactive_traversal(expr, stage) else: if choice < 0 or choice >= n_args: cprint(BRED, "Choice must be in %s range\n" % choices) result = _interactive_traversal(expr, stage) else: result = _interactive_traversal( args[choice], stage + 1) return result
def _interactive_traversal(expr, stage): if stage > 0: print cprint("Current expression (stage ", BYELLOW, stage, END, "):") print BCYAN pprint(expr) print END if isinstance(expr, Basic): if expr.is_Add: args = expr.as_ordered_terms() elif expr.is_Mul: args = expr.as_ordered_factors() else: args = expr.args elif hasattr(expr, "__iter__"): args = list(expr) else: return expr n_args = len(args) if not n_args: return expr for i, arg in enumerate(args): cprint(GREEN, "[", BGREEN, i, GREEN, "] ", BLUE, type(arg), END) pprint(arg) print if n_args == 1: choices = '0' else: choices = '0-%d' % (n_args-1) try: choice = raw_input("Your choice [%s,f,l,r,d,?]: " % choices) except EOFError: result = expr print else: if choice == '?': cprint(RED, "%s - select subexpression with the given index" % choices) cprint(RED, "f - select the first subexpression") cprint(RED, "l - select the last subexpression") cprint(RED, "r - select a random subexpression") cprint(RED, "d - done\n") result = _interactive_traversal(expr, stage) elif choice in ['d', '']: result = expr elif choice == 'f': result = _interactive_traversal(args[0], stage+1) elif choice == 'l': result = _interactive_traversal(args[-1], stage+1) elif choice == 'r': result = _interactive_traversal(random.choice(args), stage+1) else: try: choice = int(choice) except ValueError: cprint(BRED, "Choice must be a number in %s range\n" % choices) result = _interactive_traversal(expr, stage) else: if choice < 0 or choice >= n_args: cprint(BRED, "Choice must be in %s range\n" % choices) result = _interactive_traversal(expr, stage) else: result = _interactive_traversal(args[choice], stage+1) return result
The cnot performs the following transformation: |00> -> |00> |01> -> |01> |10> -> |11> |11> -> |10> """ theta = Symbol('theta') X = np.array([[0, 1j], [-1j, 0]]) CNOT = Matrix( np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) I = Matrix(np.eye(2)) sigmax = Matrix(1j * X * theta) sigmax_inv = Matrix(-1j * X * theta) R = simplify(exp(sigmax)) R_ = simplify(exp(sigmax_inv)) IX = simplify(TensorProduct(I, R)) IX_ = simplify(TensorProduct(I, R_)) U = IX_ * CNOT * IX M_ij = Matrix([[U[0, 0], U[0, 2]], [U[2, 0], U[2, 2]]]) pprint(simplify(M_ij))
Algumas funções são conhecidas: - exponenciação: use ** em vez de ^ - multiplicação: sempre escreva explicitamente 2*a, nunca 2a - algumas funções suportadas: cos(x), sin(x), ln(x), log(x), etc. exemplo: 2*(ρ - ρl)*g / (9*a) """) ok = False while not ok: print("escreva a fórmula:\n") try: form = parse(input()) print("\nSua expressão:") pprint(form) if input("\nParece OK? (s/n)\n") == 's': ok = True except SyntaxError: print("Há um problema com a fórmula... tente de novo") print() print(f"""Como você quer a formatação da incerteza? (r): relativa (padrão) - a resposta sai na forma '{simb} * raiz de alguma coisa' (a): absoluta - a resposta sai na forma 'raiz de alguma coisa'""") if input() == 'a': inc = incerteza_absoluta(form) else: inc = incerteza_relativa(form, simb) print()
#from LAPM.linear_autonomous_pool_model import LinearAutonomousPoolModel from sympy.printing import pprint from sympy import var var("lambda_1 lambda_2 t") M=Matrix([[lambda_1,0,0],[1,lambda_1,0],[0,0,lambda_2]]) pprint(M.eigenvects()) var("t") pprint(M.exp()) M.jordan_form() pprint((M*t).exp()) T=Matrix([[1,2,0],[2,1,0],[1,1,1]]) T**-1 A=T*M*T**-1
from sympy import sqrt,exp,log,Symbol,oo,Rational,sin,cos,limit,I,pi,Mul from sympy.core import basic from sympy.printing import print_pygame, pprint x=Symbol("x") y=Symbol("y") expressions = ( x**x, x+y+x, sin(x)**x, sin(x)**cos(x), sin(x)/(cos(x)**2 * x**x +(2*y)), sin(x**2+exp(x)), sqrt(exp(x)), #print (1/cos(x)).series(x,10) ) print "sympy print:" for expr in expressions: print expr print '' print "pygame print:" for expr in expressions: pprint(expr) print_pygame(expr)
# Parameters params.update(eq_params()) params.update({**vy(), **vq()}) # Forward operator forward = forward_op(config.misc['symbolic']) # Mapped backward operator factor_x, factor_y, factor = factors(config.misc['symbolic'], config.num['λ']) backward = eq.map_operator(forward, f, factor) forward, backward = evaluate([forward, backward]) factor_x, factor_y, factor = evaluate([factor_x, factor_y, factor]) if config.misc['verbose']: pprint(forward) pprint(backward) for key in params: params[key].value = params[key].eval() degree = config.num['degree'] n_points_num = config.num['n_points_num'] # }}} # DEFINE QUADRATURES {{{ vprint("Defining quadratures") def compute_quads(): μx = params['μx'].value
import numpy import sympy from sympy.printing import pprint from sympy import init_printing from matplotlib import pyplot init_printing(use_latex=True) x, nu, t = sympy.symbols( 'x nu t') # Setting symbols for x, nu, and t from symbol library. # An example equation to show the look of output. phi = (sympy.exp(-(x - 4 * t)**2 / (4 * nu * (t + 1))) + sympy.exp(-(x - 4 * t - 2 * numpy.pi)**2 / (4 * nu * (t + 1)))) pprint("Phi") # Labeling the following equation. pprint( phi) # Prints Phi using pretty print, outputs the result in equation form. pprint("Phi prime") # Labeling the following equation. phiprime = phi.diff(x) # Solves for the derivative of phi. pprint( phiprime ) # Prints Phi' using pretty print, outputs the result in equation form. from sympy.utilities.lambdify import lambdify u = -2 * nu * (phiprime / phi) + 4 pprint(u) ufunc = lambdify((t, x, nu), u) pprint(ufunc(1, 4, 3)) # Burger's Equation nx = 101 # Set number of grid points in x dir