def contains(self, other): """ Is the other GeometryEntity contained within this Segment? Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 1), Point(3, 4) >>> s = Segment(p1, p2) >>> s2 = Segment(p2, p1) >>> s.contains(s2) True """ if isinstance(other, Segment): return other.p1 in self and other.p2 in self elif isinstance(other, Point): if Point.is_collinear(self.p1, self.p2, other): t = Dummy('t') x, y = self.arbitrary_point(t).args if self.p1.x != self.p2.x: ti = solve(x - other.x, t)[0] else: ti = solve(y - other.y, t)[0] if ti.is_number: return 0 <= ti <= 1 return None # No other known entity can be contained in a Ray return False
def solveEquations(equations, numberSlots, alignedNumbers): x0 = Symbol('x0') x1 = Symbol('x1') #sanitize equation sanitized = [] for eq in equations: g = eq.split('=') g[1] = g[1].replace('+', '$').replace('-', '+').replace('$', '-') eq = g[0] + '-' + g[1] #print eq for i in range(0, len(numberSlots)): eq = eq.replace(numberSlots[i], str(alignedNumbers[i])) sanitized.append(eq) #print sanitized if len(sanitized) == 1: result = solve((sanitized[0]), x0) #print sanitized #print result if(len(result)>=1): result = {x0: result[0]} elif len(sanitized) == 2: result = solve((sanitized[0], sanitized[1]), x0, x1) #print 'result: ', result return result
def parameter_value(self, other, u, v=None): """Return the parameter(s) corresponding to the given point. Examples ======== >>> from sympy import Plane, Point, pi >>> from sympy.abc import t, u, v >>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0)) By default, the parameter value returned defines a point that is a distance of 1 from the Plane's p1 value and in line with the given point: >>> on_circle = p.arbitrary_point(t).subs(t, pi/4) >>> on_circle.distance(p.p1) 1 >>> p.parameter_value(on_circle, t) {t: pi/4} Moving the point twice as far from p1 does not change the parameter value: >>> off_circle = p.p1 + (on_circle - p.p1)*2 >>> off_circle.distance(p.p1) 2 >>> p.parameter_value(off_circle, t) {t: pi/4} If the 2-value parameter is desired, supply the two parameter symbols and a replacement dictionary will be returned: >>> p.parameter_value(on_circle, u, v) {u: sqrt(10)/10, v: sqrt(10)/30} >>> p.parameter_value(off_circle, u, v) {u: sqrt(10)/5, v: sqrt(10)/15} """ from sympy.geometry.point import Point from sympy.core.symbol import Dummy from sympy.solvers.solvers import solve if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if not isinstance(other, Point): raise ValueError("other must be a point") if other == self.p1: return other if isinstance(u, Symbol) and v is None: delta = self.arbitrary_point(u) - self.p1 eq = delta - (other - self.p1).unit sol = solve(eq, u, dict=True) elif isinstance(u, Symbol) and isinstance(v, Symbol): pt = self.arbitrary_point(u, v) sol = solve(pt - other, (u, v), dict=True) else: raise ValueError('expecting 1 or 2 symbols') if not sol: raise ValueError("Given point is not on %s" % func_name(self)) return sol[0] # {t: tval} or {u: uval, v: vval}
def _contains(self, other): L = self.lamda if self._is_multivariate(): solns = solve([expr - val for val, expr in zip(other, L.expr)], L.variables) else: solns = solve(L.expr - other, L.variables[0]) for soln in solns: try: if soln in self.base_set: return True except TypeError: if soln.evalf() in self.base_set: return True return False
def g(yieldCurve, zeroRates,n, verbose): ''' generates recursively the zero curve expressions eval('(0.06/1.05)+(1.06/(1+x)**2)-1') solves these expressions to get the new rate for that period ''' if len(zeroRates) >= len(yieldCurve): print "\n\n\t+zero curve boot strapped [%d iterations]" % (n) return else: legn = '' for i in range(0,len(zeroRates),1): if i == 0: legn = '%2.6f/(1+%2.6f)**%d'%(yieldCurve[n], zeroRates[i],i+1) else: legn = legn + ' +%2.6f/(1+%2.6f)**%d'%(yieldCurve[n], zeroRates[i],i+1) legn = legn + '+ (1+%2.6f)/(1+x)**%d-1'%(yieldCurve[n], n+1) # solve the expression for this iteration if verbose: print "-[%d] %s" % (n, legn.strip()) rate1 = solve(eval(legn), x) # Abs here since some solutions can be complex rate1 = min([Real(abs(r)) for r in rate1]) if verbose: print "-[%d] solution %2.6f" % (n, float(rate1)) # stuff the new rate in the results, will be # used by the next iteration zeroRates.append(rate1) g(yieldCurve, zeroRates,n+1, verbose)
def get_minimum_distance(arguments): delta = arguments[0] total_time = arguments[1] point = arguments[2] T=delta*total_time X=point[0] Y=point[1] a=2; b=-2*X; c=2*T*Y; d=-2*T**2 x=Symbol("x",real=True) #print "================" #print "X={0} Y={1} T={2}".format(X,Y,T) #print "a={0} b={1} c={2} d={3}".format(a,b,c,d) solutions = solve(a*x**4 + b*x**3 + c*x + d, x) #print solutions #print "================" #if len(solutions) == 0: # exit(1) # Once we have de solutions we want to get the minimum distance min_distance = float("inf") min_solution = 0 for solution in solutions: distance = math.sqrt((solution-X)**2 + ((T/solution)-Y)**2) if distance < min_distance: min_distance = distance min_solution = [solution, T/solution] # return min_distance, min_solution return min_distance**2
def _eval_subs(self, old, new): if old in self.variables: newexpr = self.expr.subs(old, new) i = self.variables.index(old) newvars = list(self.variables) newpt = list(self.point) if new.is_Symbol: newvars[i] = new else: syms = new.free_symbols if len(syms) == 1 or old in syms: if old in syms: var = self.variables[i] else: var = syms.pop() # First, try to substitute self.point in the "new" # expr to see if this is a fixed point. # E.g. O(y).subs(y, sin(x)) point = new.subs(var, self.point[i]) if point != self.point[i]: from sympy.solvers import solve d = Dummy() res = solve(old - new.subs(var, d), d, dict=True) point = d.subs(res[0]).limit(old, self.point[i]) newvars[i] = var newpt[i] = point elif old not in syms: del newvars[i], newpt[i] if not syms and new == self.point[i]: newvars.extend(syms) newpt.extend([S.Zero]*len(syms)) else: return return Order(newexpr, *zip(newvars, newpt))
def calcularEquacio(self): if "x" in self.expresio: expr=sympify(self.expresio) for symbol in expr.atoms(Symbol): if str(symbol)=='x': return solve(expr, symbol) elif "y" in self.expresio: expr=sympify(self.expresio) for symbol in expr.atoms(Symbol): if str(symbol)=='y': return solve(expr, symbol) else: expr=sympify(self.expresio) for symbol in expr.atoms(Symbol): if str(symbol)=='z': return solve(expr, symbol)
def rewriteUsingEquation(self,var,varToRemove,equation): """ Rewrites the expression for var to not include varToRemove, by solving equation for varToRemove, then substituting that into the expression for var. """ if var in equation.getVars(): self.write("You can't rewrite an expression with the " "original equation.") return equat = equation.equation for var2 in self.equivalenciesOfVariable(varToRemove): equat = equat.subs(var2,varToRemove) exps = solve(equat,varToRemove) outexps = [] if var not in self.expressions: self.findExpression(var) for exp1 in self.expressions[var]: for exp2 in exps: outexps.append(exp1.subs(varToRemove,exp2)) if outexps: self.expressions[var] = [self.unifyVarsInExpression(x) for x in outexps] self.tidyExpressions(var)
def _contains(self, other): from sympy.solvers import solve L = self.lamda if self._is_multivariate(): solns = solve([expr - val for val, expr in zip(other, L.expr)], L.variables) else: solns = solve(L.expr - other, L.variables[0]) for soln in solns: try: if soln in self.base_set: return S.true except TypeError: return self.base_set.contains(soln.evalf()) return S.false
def singularities(expr, sym): """ Finds singularities for a function. Currently supported functions are: - univariate real rational functions Examples ======== >>> from sympy.calculus.singularities import singularities >>> from sympy import Symbol >>> x = Symbol('x', real=True) >>> singularities(x**2 + x + 1, x) () >>> singularities(1/(x + 1), x) (-1,) References ========== .. [1] http://en.wikipedia.org/wiki/Mathematical_singularity """ if not expr.is_rational_function(sym): raise NotImplementedError("Algorithms finding singularities for" " non rational functions are not yet" " implemented") else: return tuple(sorted(solve(simplify(1/expr), sym)))
def arbitrary_point(self, t=None): """ Returns an arbitrary point on the Plane; varying `t` from 0 to 2*pi will move the point in a circle of radius 1 about p1 of the Plane. Examples ======== >>> from sympy.geometry.plane import Plane >>> from sympy.abc import t >>> p = Plane((0, 0, 0), (0, 0, 1), (0, 1, 0)) >>> p.arbitrary_point(t) Point3D(0, cos(t), sin(t)) >>> _.distance(p.p1).simplify() 1 Returns ======= Point3D """ from sympy import cos, sin t = t or Dummy('t') x, y, z = self.normal_vector a, b, c = self.p1.args if x == y == 0: return Point3D(a + cos(t), b + sin(t), c) elif x == z == 0: return Point3D(a + cos(t), b, c + sin(t)) elif y == z == 0: return Point3D(a, b + cos(t), c + sin(t)) m = Dummy() p = self.projection(Point3D(self.p1.x + cos(t), self.p1.y + sin(t), 0)*m) return p.xreplace({m: solve(p.distance(self.p1) - 1, m)[0]})
def matrix_eigenvalues(m): """ Module B3, page 14 This is one example of something easier with just using the libaries! You could just do Matrix(m).eigen_values()! m should be a sympy Matrix, e.g. Matrix([[0, 1], [1, 0]]). """ k = symbols('k') # To make it clearer, lets assign out the matrix elements a, b, c, d = m[0, 0], m[0, 1], m[1, 0], m[1, 1] # See B3 page 19, equation 2.5 for this definition characteristic_equation = k ** 2 - (a + d) * k + (a * d - b * c) roots = solve(characteristic_equation) print "Characteristic equation:\n\n%s\n" % pp(characteristic_equation) if len(roots) == 1: # Make dupe of repeated root roots = roots * 2 if roots[0].is_real: print "Eigenvalues: %s\n" % pp(roots) return roots else: # Note that the statement 'no eigenvalues' is by definition print "Roots are complex, no eigenvalues" return None
def matrix_eigenlines(m): """ Module B3, page 21 """ eigenvalues = matrix_eigenvalues(m) # Now make sure we've got something to work with! assert(eigenvalues is not None) # Now to work out the eignlines we use the eigenvector equation # Ax = kx where A is our matrix m, k is a particular eigenvalue # and x represents the (x, y) vector x, y = symbols('x, y') x_vector = Matrix([x, y]) eigenlines = list() for eigenvalue in eigenvalues: # Now we evaluate Ax = kx, since we can't do a 'a = b' style expression # in sympy/python we subtract the right hand side so we are basically # skipping a small step and writing Ax - kx = 0 equations = m * x_vector - eigenvalue * x_vector print "Set of equations for eigenvalue %s:\n\n%s" % (eigenvalue, pp(equations)) # For a given eigenvalue the equations returned above both reduce # to the same expression, so we can pick the first one, simplify it # down to the lowest terms. Then we solve for y which basically # rearranged it into standard form. This is the eigenline equation. # As we're dealing with solve, we take the first (only) result eigenline = solve(simplify(equations[0]), y)[0] print "Eigenline equation for eigenvalue %s:\n\n%s\n" % (eigenvalue, pp(eigenline)) eigenlines.append(eigenline) return eigenlines
def _remove_multiple_delta(expr): """ Evaluate products of KroneckerDelta's. """ from sympy.solvers import solve if expr.is_Add: return expr.func(*map(_remove_multiple_delta, expr.args)) if not expr.is_Mul: return expr eqs = [] newargs = [] for arg in expr.args: if isinstance(arg, KroneckerDelta): eqs.append(arg.args[0] - arg.args[1]) else: newargs.append(arg) if not eqs: return expr solns = solve(eqs, dict=True) if len(solns) == 0: return S.Zero elif len(solns) == 1: for key in solns[0].keys(): newargs.append(KroneckerDelta(key, solns[0][key])) expr2 = expr.func(*newargs) if expr != expr2: return _remove_multiple_delta(expr2) return expr
def test_nfloat(): from sympy.core.basic import _aresame from sympy.polys.rootoftools import RootOf x = Symbol("x") eq = x**(S(4)/3) + 4*x**(S(1)/3)/3 assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(S(1)/3)) assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3)) eq = x**(S(4)/3) + 4*x**(x/3)/3 assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(x/3)) big = 12345678901234567890 Float_big = Float(big) assert _aresame(nfloat(x**big, exponent=True), x**Float_big) assert _aresame(nfloat(big), Float_big) assert nfloat({x: sqrt(2)}) == {x: nfloat(sqrt(2))} assert nfloat({sqrt(2): x}) == {sqrt(2): x} assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2))) # issue 6342 f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4') assert not any(a.free_symbols for a in solve(f.subs(x, -0.139))) # issue 6632 assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \ 9.99999999800000e-11 # issue 7122 eq = cos(3*x**4 + y)*RootOf(x**5 + 3*x**3 + 1, 0) assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)'
def resolve(equation): '''Resolve an equation with 1 unknown var''' #Find the symbol r = re.compile(r"([A-Za-z]{0,})") varList = r.findall(equation) symbol = '' for a in range(0, len(varList)): if len(varList[a]) > 0: symbol = varList[a] break x = Symbol(symbol) #replace 3x -> 3*x for example r2 = re.compile(r'([0-9])'+symbol) replaceList = r2.findall(equation) for a in range(0, len(replaceList)): if len(replaceList[a]) > 0: equation = re.sub(r''+replaceList[a]+symbol, r''+replaceList[a]+'*'+symbol, equation) #rewrite the eq to solve it r3 = re.compile(r"(.{0,})\=(.{0,})") results = r3.findall(equation) mGauche = results[0][0] mDroite = results[0][1] return solve(mGauche + '-(' + mDroite + ')', x)
def intersection_plane_line(pP,nP,pL,vL): """Computes the intersection of a plane and a line INPUT: pPlane: point on plane nPlane: normal vector of plane pLine: point on line vLine: vecotr on line OUTPUT: coordinates of intersectionPoint """ plane = lambda x1,x2,x3: (x1-pP[0])*nP[0]+(x2-pP[1])*nP[1]+(x3-pP[2])*nP[2] iP=Symbol('iP') #intersection iP=solve(plane(pL[0]+iP*vL[0],pL[1]+iP*vL[1],pL[2]+iP*vL[2]),iP) #Compute intersection point Point = lambda iP: [pL[0]+iP*vL[0],pL[1]+iP*vL[1],pL[2]+iP*vL[2]] if iP != []: coordsPoint = Point(iP[0]) else: coordsPoint = [] newCoordsPoint=[] for coords in coordsPoint: newCoordsPoint.append(np.float(coords)) return np.array(newCoordsPoint)
def balance(): Ls=list('abcdefghijklmnopqrstuvwxyz') eq=eq_enter.get() Ss,Os,Es,a,i=defaultdict(list),Ls[:],[],1,1 for p in eq.split('->'): for k in p.split('+'): c = [Ls.pop(0), 1] for e,m in re.findall('([A-Z][a-z]?)([0-9]*)',k): m=1 if m=='' else int(m) a*=m d=[c[0],c[1]*m*i] Ss[e][:0],Es[:0]=[d],[[e,d]] i=-1 Ys=dict((s,eval('Symbol("'+s+'")')) for s in Os if s not in Ls) Qs=[eval('+'.join('%d*%s'%(c[1],c[0]) for c in Ss[s]),{},Ys) for s in Ss]+[Ys['a']-a] k=solve(Qs,*Ys) if k: N=[k[Ys[s]] for s in sorted(Ys)] g=N[0] for a1, a2 in zip(N[0::2],N[1::2]):g=gcd(g,a2) N=[i/g for i in N] pM=lambda c: str(c) if c!=1 else '' ans = '->'.join('+'.join(pM(N.pop(0))+str(t) for t in p.split('+')) for p in eq.split('->')) else:ans = 'No Result!' eq_result.configure(text='%s' % ans)
def random_point(self, seed=None): """ Returns a random point on the Plane. Returns ======= Point3D """ x, y, z = symbols("x, y, z") a = self.equation(x, y, z) from sympy import Rational import random if seed is not None: rng = random.Random(seed) else: rng = random for i in range(10): c = 2*Rational(rng.random()) - 1 s = sqrt(1 - c**2) a = solve(a.subs([(y, c), (z, s)])) if a is []: d = Point3D(0, c, s) else: d = Point3D(a[0], c, s) if d in self: return d raise GeometryError( 'Having problems generating a point in the plane')
def solve_r(source,target): """ @param source decibel of source @param target decibel of target @return radius {@code r} in meters needed to achieve decidel {@param target} from {@param source} """ r = Symbol('r') return solve(source-target-20*log(r,10)-A_ATMOSPHERE*r-A_WEATHER*r-A_GROUND*r-A_BARRIER*r/DISTANCE_BUILDINGS,r)[0]
def fixed_point(channel): """Calculates the fixed point of a 1-qubit channel""" rho = final_dens_matrix(channel) final_point = [fun.re((Xsym*rho).trace().expand()), fun.re((Ysym*rho).trace().expand()), fun.re((Zsym*rho).trace().expand())] final_point[0] -= x final_point[1] -= y final_point[2] -= z return solve(final_point)
def solved(): canvas.three = 3 x = Symbol('x') canvas.solved = canvas.eq.get() equat = str(canvas.solved) canvas.solved = solve(str(canvas.solved), x) roots = Label(canvas, text = "x = " + str(canvas.solved), font = 20) roots.place(x = 450, y = 675)
def check(out,vin): vovn = vin - VTO vdsn = out vovp = 5-VTO vdsp = 5-out #nmos in triode if(vdsn < vovn): print "nmos" vout = Symbol('vout') out = solve((2*KN*((vin - VTO)*vout-((vout**2)/2))*(1+LAMBDA*(vout)))-(KP*((5-VTO)**2)*(1+LAMBDA*(5-vout))),vout) print out #pmos in triode if(vdsp < vovp): print "pmos" vout = Symbol('vout') out = solve((KN*((vin - VTO)**2)*(1+LAMBDA*(vout)))-(2*KP*(5-VTO*5-vout-(((5-vout)**2)/2))*(1+LAMBDA*(5-vout))),vout) print out
def solve_db(source,r): """ @param source decibel of source @param r radius in meters @return decibel of the location away by {@param r} meters from the source with {@param source} dBs """ t = Symbol('t') return solve(source-t-20*log10(r)-A_ATMOSPHERE*r-A_WEATHER*r-A_GROUND*r-A_BARRIER*r/DISTANCE_BUILDINGS,t)[0]
def deltaintegrate(f, x): """The idea for integration is the following: -If we are dealing with a DiracDelta expression, i.e.: DiracDelta(g(x)), we try to simplify it. If we could simplify it, then we integrate the resulting expression. We already know we can integrate a simplified expression, because only simple DiracDelta expressions are involved. If we couldn't simplify it, there are two cases: 1) The expression is a simple expression, then we return the integral Taking care if we are dealing with a Derivative or with a proper DiracDelta 2) The expression is not simple(i.e. DiracDelta(cos(x))), we can do nothing at all -If the node is a multiplication node having a DiracDelta term First we expand it. If the expansion did work, the we try to integrate the expansion If not, we try to extract a simple DiracDelta term, then we have two cases 1)We have a simple DiracDelta term, so we return the integral 2)We didn't have a simple term, but we do have an expression with simplified DiracDelta terms, so we integrate this expression """ if not f.has(DiracDelta): return None # g(x) = DiracDelta(h(x)) if f.func == DiracDelta: h = f.simplify(x) if h == f:#can't simplify the expression #FIXME: the second term tells whether is DeltaDirac or Derivative #For integrating derivatives of DiracDelta we need the chain rule if f.is_simple(x): if (len(f.args) <= 1 or f.args[1]==0): return Heaviside(f.args[0]) else: return (DiracDelta(f.args[0],f.args[1]-1)/ f.args[0].as_poly().LC()) else:#let's try to integrate the simplified expression fh = sympy.integrals.integrate(h, x) return fh elif f.is_Mul: #g(x)=a*b*c*f(DiracDelta(h(x)))*d*e g = f.expand() if f != g:#the expansion worked fh = sympy.integrals.integrate(g, x) if fh and not isinstance(fh, sympy.integrals.Integral): return fh else:#no expansion performed, try to extract a simple DiracDelta term dg, rest_mult = change_mul(f, x) if not dg: if rest_mult: fh = sympy.integrals.integrate(rest_mult, x) return fh else: dg = dg.simplify(x) if dg.is_Mul: # Take out any extracted factors dg, rest_mult_2 = change_mul(dg, x) rest_mult = rest_mult*rest_mult_2 point = solve(dg.args[0],x)[0] return (rest_mult.subs(x, point)*Heaviside(x - point)) return None
def get_next_point_and_line(line, line_slope, x_coord, y_coord): # Start with a line, slope and point # Get new intersection point # Get angle of intersection and new angle # Get new slope and line # Return a line, slope and point # find new x, since it is not the same as the previous x xs = solve(ellipse_top - line, x_var) + solve(ellipse_bottom - line, x_var) x = filter(lambda x: not eq(x, x_coord), xs)[0] y = line.evalf(subs={'x': x}) ellipse_slope = -4 * x / y new_slope = new_slope_from_two_slopes(ellipse_slope, line_slope) #print 'ellipse_slope', ellipse_slope, x_coord, y_coord, new_slope # find our new y based on the new x and the line new_line = point_slope(new_slope, x, y) return new_line, new_slope, x, y
def contains(self, o): """Return True if o is on this Line, or False otherwise.""" if isinstance(o, Point): x, y = Dummy(), Dummy() eq = self.equation(x, y) if not eq.has(y): return (solve(eq, x)[0] - o.x).equals(0) if not eq.has(x): return (solve(eq, y)[0] - o.y).equals(0) return (solve(eq.subs(x, o.x), y)[0] - o.y).equals(0) elif not isinstance(o, LinearEntity): return False elif isinstance(o, Line): return self.__eq__(o) elif not self.is_similar(o): return False else: return o.p1 in self and o.p2 in self
def contains(self, other): """Is the other GeometryEntity contained within this Ray?""" if isinstance(other, Segment): return other.p1 in self and other.p2 in self elif isinstance(other, Point): if Point.is_collinear(self.p1, self.p2, other): t = Dummy('t') x, y = self.arbitrary_point(t) if self.p1.x != self.p2.x: ti = solve(x - other.x, t)[0] else: ti = solve(y - other.y, t)[0] if ti.is_number: return 0 <= ti <= 1 return None # No other known entity can be contained in a Ray return False
def solve_x(): x = sympy.Symbol('x') u= sympy.Symbol('u') qTerm=sympy.Symbol('qTerm') L=sympy.Symbol('L') phi_prime=phi_diff() (a,b)=solve(phi_prime,x) eq1=a eq2=b return eq1,eq2 #should return two equations to gw_flow
from sympy import Symbol, Dummy, sympify, exp from sympy.abc import mu, x, y, w from sympy.stats import density, Normal from sympy.solvers import solve from sympy.holonomic.holonomic import expr_to_holonomic sigma = Symbol('sigma', positive=True) want_dens = w * density(Normal(Dummy(), mu, sigma))(y) have_dens = exp(-x**2 - y**2 + x * y) want_hol = expr_to_holonomic(want_dens, y) have_hol = expr_to_holonomic(have_dens, y) print(want_hol) print(have_hol) def annihilator_coeff(hol, i): return hol.annihilator.listofpoly[i] if i <= hol.annihilator.order else 0 equations = set(h - w for (h, w) in zip(have_hol.y0, want_hol.y0)) order = max(want_hol.annihilator.order, have_hol.annihilator.order) have_top_coeff = annihilator_coeff(have_hol, order) want_top_coeff = annihilator_coeff(want_hol, order) for i in range(0, order): equations.update( c.as_expr() if hasattr(c, 'as_expr') else sympify(c) for c in ( annihilator_coeff(have_hol, i) * want_top_coeff - annihilator_coeff(want_hol, i) * have_top_coeff).all_coeffs()) print(equations) print(solve(equations, [w, mu, sigma]))
# Initial lists O_l = (list(np.arange(-1, 3.125, 0.125))) * 33 O_m = [] a = 0 da = 0.125 for i in range(33): for k in range(33): O_m.append(a) a = a + da # Solving all roots for every point of the grid for i in range(len(O_l)): O_l1 = O_l[i] O_m1 = O_m[i] a = Symbol('a', real=True) sc = solve((O_m1 / a**3) + O_l1 + ((1 - (O_m1 + O_l1)) / a**2), a) # Eliminating all the un-physical results if len(sc) == 3: sc1 = sc[2] elif len(sc) == 2: sc1 = sc[1] elif len(sc) == 1: sc1 = sc[0] else: sc1 = sc # Plotting different fates in a different color if sc1 == []: plt.plot(O_m1, O_l1, 'ro', color='red') plt.axis([0, 2.7, -1, 3]) plt.title('Different fates of the universe')
def safe_solve(*args): try: return solve(*args) except Exception as e: print (str(e)) return None
def max_interval(A, B, C, D, y, eps, show=False): x = Symbol('x', real=True) fx = A * x**3 + B * x**2 + C * x + D intervals = solve(abs(fx - y) < eps) xranges = [] diffs = [] for interval in intervals.args if type(intervals) is Or else [intervals]: lhs, rhs = interval.args lb = lhs.lts ub = rhs.gts xranges.append((lb, ub)) diffs.append((ub - lb)) maxdiff = max(diffs) if show: min_x = min(b[0] for b in xranges) max_x = max(b[1] for b in xranges) adj = 0.1 * (max_x - min_x) min_x = min_x - adj max_x = max_x + adj dfx = diff(fx, x) extrema = solve(dfx) x_candidates = [min_x, max_x] + list( filter(lambda x: min_x < x < max_x, extrema)) y_candidates = list(map(lambdify(x, fx), x_candidates)) min_y = min(y_candidates) max_y = max(y_candidates) adj = 0.1 * (max_y - min_y) min_y = min_y - adj max_y = max_y + adj xlim = (min_x, max_x) ylim = (min_y, max_y) p = plot(fx, show=False, xlim=xlim, ylim=ylim, adaptive=False, nb_of_points=1000) p.append(plot(y, show=False, xlim=xlim, ylim=ylim, line_color='r')[0]) p.append( plot(y - eps, show=False, xlim=xlim, ylim=ylim, line_color='lightsalmon', markers=['.'])[0]) p.append( plot(y + eps, show=False, xlim=xlim, ylim=ylim, line_color='lightsalmon', markers=['.'])[0]) for d, (lb, ub) in zip(diffs, xranges): p.append( plot_implicit(Eq(x, lb), show=False, xlim=xlim, ylim=ylim)[0]) p.append( plot_implicit(Eq(x, ub), show=False, xlim=xlim, ylim=ylim)[0]) print(" ".join(str(x) for x in diffs)) p.show() return maxdiff
def calculate_foundation_load(self, foundation_load_input_data, foundation_load_output_data): """ Function to calculate foundation load. Parameters ------- Int Section height m Surface area sq (in m^2) Coeff drag (installed) Lever arm m (in m) Multplier drag rotor Multiplier tower drag Mass tonne Returns ------- Dead load [in N] -> F_dead_kN_per_turbine Lateral load [in N] -> F_horiz_kN_per_turbine Moment [N.m] -> M_tot_kN_m_per_turbine Foundation radius based on overturning moment [in m] -> Radius_o_m Foundation radius based on slipping [in m] -> Radius_s_m Foundation radius based on gapping [in m] -> Radius_g_m Foundation radius based on bearing pressure [in m] -> Radius_b_m Largest foundation radius based on all three foundation design criteria (moment, gapping, bearing [in m]) -> Radius_m Raises ------ ValueError Raises a value error if r_bearing is calculated to be a negative value. """ # set exposure constants a = 9.5 z_g = 274.32 # get section height z = foundation_load_input_data['Section height m'] # get cross-sectional area a_f = foundation_load_input_data['Surface area sq m'] # get coefficient of drag c_d = foundation_load_input_data['Coeff drag (installed)'] # get lever arm l = foundation_load_input_data['Lever arm m'] # get multipliers for tower and rotor multiplier_rotor = foundation_load_input_data['Multplier drag rotor'] multiplier_tower = foundation_load_input_data['Multiplier tower drag'] # calculate wind pressure k_z = 2.01 * (z / z_g)**(2 / a) # exposure factor k_d = 0.95 # wind directionality factor k_zt = 1 # topographic factor v = foundation_load_input_data['gust_velocity_m_per_s'] wind_pressure = 0.613 * k_z * k_zt * k_d * v**2 # calculate wind loads on each tower component g = 0.85 # gust factor c_f = 0.6 # coefficient of force f_t = (wind_pressure * g * c_f * a_f) * multiplier_tower # calculate drag rotor rho = 1.225 # air density in kg/m^3 f_r = (0.5 * rho * c_d * a_f * v**2) * multiplier_rotor f = (f_t + f_r) # calculate dead load in N g = 9.8 # m / s ^ 2 f_dead = sum( foundation_load_input_data['Mass tonne'] ) * g * self._kg_per_tonne / 1.15 # scaling factor to adjust dead load for uplift # calculate moment from each component at base of tower m_overturn = f * l # get total lateral load (N) and moment (N * m) f_lat = f.sum() # todo: add f_lat (drag force) to output csv m_overturn = m_overturn.sum() # compare to moment from rated thrust rated_thrust = foundation_load_input_data['rated_thrust_N'] m_thrust = rated_thrust * max(l) m_tot = max(m_thrust, m_overturn) # compare lateral load to rated thrust f_horiz = max(f_lat, rated_thrust) # calculate foundation radius based on overturning moment vol_fraction_fill = 0.55 vol_fraction_concrete = 1 - vol_fraction_fill safety_overturn = 1.5 unit_weight_fill = 17.3e3 # in N / m^3 unit_weight_concrete = 23.6e3 # in N / m^3 bearing_pressure = foundation_load_input_data['bearing_pressure_n_m2'] p = [(np.pi * foundation_load_input_data['depth'] * (vol_fraction_fill * unit_weight_fill + vol_fraction_concrete * unit_weight_concrete)), 0, f_dead, -(safety_overturn * (m_tot + f_horiz * foundation_load_input_data['depth']))] r_overturn = np.roots(p) r_overturn = np.real(r_overturn[np.isreal(r_overturn)])[0] # calculate foundation radius based on slipping safety_slipping = 1.5 friction_angle_soil = 25 tangent_slip_angle = math.tan((friction_angle_soil * math.pi) / 180) slipping_force_with_sf = (safety_slipping * f_lat) # first check if slipping is already satisfied by dead weight if slipping_force_with_sf < (f_dead * tangent_slip_angle): r_slipping = 0 else: # Calculate foundation radius based on slipping: r_slipping = (( (slipping_force_with_sf / tangent_slip_angle) - f_dead) / ((vol_fraction_fill * unit_weight_fill + vol_fraction_concrete * unit_weight_concrete) * math.pi * foundation_load_input_data['depth']))**0.5 r_test_gapping = max(r_overturn, r_slipping) # calculate foundation radius based on gapping # check if gapping constrain is already satisfied - r / 3 < e foundation_vol = np.pi * r_test_gapping**2 * foundation_load_input_data[ 'depth'] v_1 = (foundation_vol * (vol_fraction_fill * unit_weight_fill + vol_fraction_concrete * unit_weight_concrete) + f_dead) e = m_tot / v_1 if (r_test_gapping / 3) < e: r_gapping = 0 else: r_g = Symbol('r_g', real=True, positive=True) foundation_vol = np.pi * r_g**2 * foundation_load_input_data[ 'depth'] v_1 = (foundation_vol * (vol_fraction_fill * unit_weight_fill + vol_fraction_concrete * unit_weight_concrete) + f_dead) e = m_tot / v_1 r_gapping = solve(e * 3 - r_g, r_g) if len(r_gapping) > 0: r_gapping = max(r_gapping) else: r_gapping = 0 r_test_bearing = max(r_test_gapping, r_gapping) # calculate foundation radius based on bearing pressure # Restrict r_b to only real numbers. Positive solutions for r_b are # selected below r_b = Symbol('r_b', real=True) foundation_vol = np.pi * r_test_bearing**2 * foundation_load_input_data[ 'depth'] v_1 = (foundation_vol * (vol_fraction_fill * unit_weight_fill + vol_fraction_concrete * unit_weight_concrete) + f_dead) e = m_tot / v_1 a_eff = v_1 / bearing_pressure r_bearing = solve(2 * (r_b**2 - e * (r_b**2 - e**2)**0.5) - a_eff, r_b) # Select only positive solutions to r_b. This is selected by max(). If there are # not positive solutions to r_b, that means something is wrong with the foundation # parameters. In that case, generate a warning below. if len(r_bearing) > 0: r_bearing = max(r_bearing) else: r_bearing = 0 if r_bearing < 0: raise ValueError( f'Warning {self.project_name} calculate_foundation_load r_bearing is negative, r_bearing={r_bearing}' ) # pick the largest foundation radius based on all 4 foundation design criteria: moment, gapping, bearing, slipping r_choosen = max(r_bearing, r_overturn, r_slipping, r_gapping) foundation_load_output_data['F_dead_kN_per_turbine'] = f_dead / 1e3 foundation_load_output_data['F_horiz_kN_per_turbine'] = f_lat / 1e3 foundation_load_output_data['M_tot_kN_m_per_turbine'] = m_tot / 1e3 foundation_load_output_data['Radius_o_m'] = r_overturn foundation_load_output_data['Radius_s_m'] = r_slipping foundation_load_output_data['Radius_g_m'] = r_gapping foundation_load_output_data['Radius_b_m'] = r_bearing foundation_load_output_data['Radius_m'] = r_choosen return foundation_load_output_data
def eval_sum_symbolic(f, limits): from sympy.functions import harmonic, bernoulli f_orig = f (i, a, b) = limits if not f.has(i): return f * (b - a + 1) # Linearity if f.is_Mul: # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 1: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i * s if r is not S.NaN: return r else: # Try term by term L, R = f.as_two_terms() if not L.has(i): sR = eval_sum_symbolic(R, (i, a, b)) if sR: return L * sR if not R.has(i): sL = eval_sum_symbolic(L, (i, a, b)) if sL: return sL * R try: f = apart(f, i) # see if it becomes an Add except PolynomialError: pass if f.is_Add: L, R = f.as_two_terms() lrsum = telescopic(L, R, (i, a, b)) if lrsum: return lrsum # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 0: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i * (b - a + 1) + s if r is not S.NaN: return r else: # Try term by term lsum = eval_sum_symbolic(L, (i, a, b)) rsum = eval_sum_symbolic(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r # Polynomial terms with Faulhaber's formula n = Wild("n") result = f.match(i ** n) if result is not None: n = result[n] if n.is_Integer: if n >= 0: if (b is S.Infinity and not a is S.NegativeInfinity) or ( a is S.NegativeInfinity and not b is S.Infinity ): return S.Infinity return ( (bernoulli(n + 1, b + 1) - bernoulli(n + 1, a)) / (n + 1) ).expand() elif a.is_Integer and a >= 1: if n == -1: return harmonic(b) - harmonic(a - 1) else: return harmonic(b, abs(n)) - harmonic(a - 1, abs(n)) if not ( a.has(S.Infinity, S.NegativeInfinity) or b.has(S.Infinity, S.NegativeInfinity) ): # Geometric terms c1 = Wild("c1", exclude=[i]) c2 = Wild("c2", exclude=[i]) c3 = Wild("c3", exclude=[i]) wexp = Wild("wexp") # Here we first attempt powsimp on f for easier matching with the # exponential pattern, and attempt expansion on the exponent for easier # matching with the linear pattern. e = f.powsimp().match(c1 ** wexp) if e is not None: e_exp = e.pop(wexp).expand().match(c2 * i + c3) if e_exp is not None: e.update(e_exp) if e is not None: p = (c1 ** c3).subs(e) q = (c1 ** c2).subs(e) r = p * (q ** a - q ** (b + 1)) / (1 - q) l = p * (b - a + 1) return Piecewise((l, Eq(q, S.One)), (r, True)) r = gosper_sum(f, (i, a, b)) if isinstance(r, (Mul, Add)): from sympy import ordered, Tuple non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols den = denom(together(r)) den_sym = non_limit & den.free_symbols args = [] for v in ordered(den_sym): try: s = solve(den, v) m = Eq(v, s[0]) if s else S.false if m != False: args.append((Sum(f_orig.subs(*m.args), limits).doit(), m)) break except NotImplementedError: continue args.append((r, True)) return Piecewise(*args) if not r in (None, S.NaN): return r h = eval_sum_hyper(f_orig, (i, a, b)) if h is not None: return h factored = f_orig.factor() if factored != f_orig: return eval_sum_symbolic(factored, (i, a, b))
def intersection(self, o): """ The intersection with other geometrical entity. Parameters ========== Point, Point3D, LinearEntity, LinearEntity3D, Plane Returns ======= List Examples ======== >>> from sympy import Point, Point3D, Line, Line3D, Plane >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1)) >>> b = Point3D(1, 2, 3) >>> a.intersection(b) [Point3D(1, 2, 3)] >>> c = Line3D(Point3D(1, 4, 7), Point3D(2, 2, 2)) >>> a.intersection(c) [Point3D(2, 2, 2)] >>> d = Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3)) >>> e = Plane(Point3D(2, 0, 0), normal_vector=(3, 4, -3)) >>> d.intersection(e) [Line3D(Point3D(78/23, -24/23, 0), Point3D(147/23, 321/23, 23))] """ from sympy.geometry.line3d import LinearEntity3D from sympy.geometry.line import LinearEntity if isinstance(o, (Point, Point3D)): if o in self: return [Point3D(o)] else: return [] if isinstance(o, (LinearEntity, LinearEntity3D)): if o in self: p1, p2 = o.p1, o.p2 if isinstance(o, Segment): o = Segment3D(p1, p2) elif isinstance(o, Ray): o = Ray3D(p1, p2) elif isinstance(o, Line): o = Line3D(p1, p2) else: raise ValueError('unhandled linear entity: %s' % o.func) return [o] else: x, y, z = map(Dummy, 'xyz') t = Dummy() # unnamed else it may clash with a symbol in o a = Point3D(o.arbitrary_point(t)) b = self.equation(x, y, z) c = solve(b.subs(list(zip((x, y, z), a.args))), t) if not c: return [] else: p = a.subs(t, c[0]) if p not in self: return [] # e.g. a segment might not intersect a plane return [p] if isinstance(o, Plane): if o == self: return [self] if self.is_parallel(o): return [] else: x, y, z = map(Dummy, 'xyz') a, b = Matrix([self.normal_vector]), Matrix([o.normal_vector]) c = list(a.cross(b)) d = self.equation(x, y, z) e = o.equation(x, y, z) f = solve((d.subs(z, 0), e.subs(z, 0)), [x, y]) if len(f) == 2: return [Line3D(Point3D(f[x], f[y], 0), direction_ratio=c)] g = solve((d.subs(y, 0), e.subs(y, 0)), [x, z]) if len(g) == 2: return [Line3D(Point3D(g[x], 0, g[z]), direction_ratio=c)] h = solve((d.subs(x, 0), e.subs(x, 0)), [y, z]) if len(h) == 2: return [Line3D(Point3D(0, h[y], h[z]), direction_ratio=c)]
def deltaintegrate(f, x): """ deltaintegrate(f, x) Explanation =========== The idea for integration is the following: - If we are dealing with a DiracDelta expression, i.e. DiracDelta(g(x)), we try to simplify it. If we could simplify it, then we integrate the resulting expression. We already know we can integrate a simplified expression, because only simple DiracDelta expressions are involved. If we couldn't simplify it, there are two cases: 1) The expression is a simple expression: we return the integral, taking care if we are dealing with a Derivative or with a proper DiracDelta. 2) The expression is not simple (i.e. DiracDelta(cos(x))): we can do nothing at all. - If the node is a multiplication node having a DiracDelta term: First we expand it. If the expansion did work, then we try to integrate the expansion. If not, we try to extract a simple DiracDelta term, then we have two cases: 1) We have a simple DiracDelta term, so we return the integral. 2) We didn't have a simple term, but we do have an expression with simplified DiracDelta terms, so we integrate this expression. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.integrals.deltafunctions import deltaintegrate >>> from sympy import sin, cos, DiracDelta >>> deltaintegrate(x*sin(x)*cos(x)*DiracDelta(x - 1), x) sin(1)*cos(1)*Heaviside(x - 1) >>> deltaintegrate(y**2*DiracDelta(x - z)*DiracDelta(y - z), y) z**2*DiracDelta(x - z)*Heaviside(y - z) See Also ======== sympy.functions.special.delta_functions.DiracDelta sympy.integrals.integrals.Integral """ if not f.has(DiracDelta): return None # g(x) = DiracDelta(h(x)) if f.func == DiracDelta: h = f.expand(diracdelta=True, wrt=x) if h == f: # can't simplify the expression #FIXME: the second term tells whether is DeltaDirac or Derivative #For integrating derivatives of DiracDelta we need the chain rule if f.is_simple(x): if (len(f.args) <= 1 or f.args[1] == 0): return Heaviside(f.args[0]) else: return (DiracDelta(f.args[0], f.args[1] - 1) / f.args[0].as_poly().LC()) else: # let's try to integrate the simplified expression fh = integrate(h, x) return fh elif f.is_Mul or f.is_Pow: # g(x) = a*b*c*f(DiracDelta(h(x)))*d*e g = f.expand() if f != g: # the expansion worked fh = integrate(g, x) if fh is not None and not isinstance(fh, Integral): return fh else: # no expansion performed, try to extract a simple DiracDelta term deltaterm, rest_mult = change_mul(f, x) if not deltaterm: if rest_mult: fh = integrate(rest_mult, x) return fh else: deltaterm = deltaterm.expand(diracdelta=True, wrt=x) if deltaterm.is_Mul: # Take out any extracted factors deltaterm, rest_mult_2 = change_mul(deltaterm, x) rest_mult = rest_mult * rest_mult_2 point = solve(deltaterm.args[0], x)[0] # Return the largest hyperreal term left after # repeated integration by parts. For example, # # integrate(y*DiracDelta(x, 1),x) == y*DiracDelta(x,0), not 0 # # This is so Integral(y*DiracDelta(x).diff(x),x).doit() # will return y*DiracDelta(x) instead of 0 or DiracDelta(x), # both of which are correct everywhere the value is defined # but give wrong answers for nested integration. n = (0 if len(deltaterm.args) == 1 else deltaterm.args[1]) m = 0 while n >= 0: r = S.NegativeOne**n * rest_mult.diff(x, n).subs(x, point) if r.is_zero: n -= 1 m += 1 else: if m == 0: return r * Heaviside(x - point) else: return r * DiracDelta(x, m - 1) # In some very weak sense, x=0 is still a singularity, # but we hope will not be of any practical consequence. return S.Zero return None
def normal_lines(self, p, prec=None): """Normal lines between `p` and the ellipse. Parameters ========== p : Point Returns ======= normal_lines : list with 1, 2 or 4 Lines Examples ======== >>> from sympy import Line, Point, Ellipse >>> e = Ellipse((0, 0), 2, 3) >>> c = e.center >>> e.normal_lines(c + Point(1, 0)) [Line2D(Point2D(0, 0), Point2D(1, 0))] >>> e.normal_lines(c) [Line2D(Point2D(0, 0), Point2D(0, 1)), Line2D(Point2D(0, 0), Point2D(1, 0))] Off-axis points require the solution of a quartic equation. This often leads to very large expressions that may be of little practical use. An approximate solution of `prec` digits can be obtained by passing in the desired value: >>> e.normal_lines((3, 3), prec=2) [Line2D(Point2D(-0.81, -2.7), Point2D(0.19, -1.2)), Line2D(Point2D(1.5, -2.0), Point2D(2.5, -2.7))] Whereas the above solution has an operation count of 12, the exact solution has an operation count of 2020. """ p = Point(p, dim=2) # XXX change True to something like self.angle == 0 if the arbitrarily # rotated ellipse is introduced. # https://github.com/sympy/sympy/issues/2815) if True: rv = [] if p.x == self.center.x: rv.append(Line(self.center, slope=oo)) if p.y == self.center.y: rv.append(Line(self.center, slope=0)) if rv: # at these special orientations of p either 1 or 2 normals # exist and we are done return rv # find the 4 normal points and construct lines through them with # the corresponding slope x, y = Dummy('x', real=True), Dummy('y', real=True) eq = self.equation(x, y) dydx = idiff(eq, y, x) norm = -1 / dydx slope = Line(p, (x, y)).slope seq = slope - norm # TODO: Replace solve with solveset, when this line is tested yis = solve(seq, y)[0] xeq = eq.subs(y, yis).as_numer_denom()[0].expand() if len(xeq.free_symbols) == 1: try: # this is so much faster, it's worth a try xsol = Poly(xeq, x).real_roots() except (DomainError, PolynomialError, NotImplementedError): # TODO: Replace solve with solveset, when these lines are tested xsol = _nsort(solve(xeq, x), separated=True)[0] points = [Point(i, solve(eq.subs(x, i), y)[0]) for i in xsol] else: raise NotImplementedError( 'intersections for the general ellipse are not supported') slopes = [norm.subs(zip((x, y), pt.args)) for pt in points] if prec is not None: points = [pt.n(prec) for pt in points] slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes] return [Line(pt, slope=s) for pt, s in zip(points, slopes)]
def temps(name, position): #vi=voltage pt100 / vcc=voltage source(3.3V) / R= rtc resistance vi1 = chan01.voltage vcc1 = chan11.voltage vi2 = chan02.voltage vcc2 = chan12.voltage vi3 = chan03.voltage vcc3 = chan13.voltage vi4 = chan04.voltage vcc4 = chan14.voltage R1 = 3300 / (vcc1 / vi1 - 1) R2 = 3300 / (vcc2 / vi2 - 1) R3 = 3300 / (vcc3 / vi3 - 1) R4 = 3300 / (vcc4 / vi4 - 1) #Finding temperature through resistance (rtc curve) x = Symbol("x") if R1 > 100: T1 = solve(R1 - 100 * (1 + a * x + b * x**2), x) else: T1 = solve(R1 - 100 * (1 + a * x + b * x**2 + c * (x - 100) * x**3), x) if R2 > 100: T2 = solve(R2 - 100 * (1 + a * x + b * x**2), x) else: T2 = solve(R2 - 100 * (1 + a * x + b * x**2 + c * (x - 100) * x**3), x) if R3 > 100: T3 = solve(R3 - 100 * (1 + a * x + b * x**2), x) else: T3 = solve(R3 - 100 * (1 + a * x + b * x**2 + c * (x - 100) * x**3), x) if R4 > 100: T4 = solve(R4 - 100 * (1 + a * x + b * x**2), x) else: T4 = solve(R4 - 100 * (1 + a * x + b * x**2 + c * (x - 100) * x**3), x) #keeping only the value within the reasonable range of temperatures temp = [] for z in range(0, len(T1)): if T1[z] >= -200 and T1[z] <= 300: T1[z] = float("{:.2f}".format(T1[z])) temp.append(T1[z]) z = z + 1 for z in range(0, len(T2)): if T2[z] >= -200 and T2[z] <= 300: T2[z] = float("{:.2f}".format(T2[z])) temp.append(T2[z]) z = z + 1 for z in range(0, len(T3)): if T3[z] >= -200 and T3[z] <= 300: T3[z] = float("{:.2f}".format(T3[z])) temp.append(T3[z]) z = z + 1 for z in range(0, len(T4)): if T4[z] >= -200 and T4[z] <= 300: T4[z] = float("{:.2f}".format(T4[z])) temp.append(T4[z]) z = z + 1 dict = {"name": "{}_PT100[*C]".format(name), "value": temp[position]} return dict
def deviation_calc(self, pos): y = Symbol( 'y' ) # A1*x + B*y + C*z - D = 0 y = solve( self.a1 * pos[0] + self.b * y + self.c * pos[2] - self.d, y ) # print('y-value is ', y) return y[0]
show(normalplot(Sub4iteratecount)) show(normalplot(Sub6iteratecount)) print("I found the above graphs (with regular axes) made it easier to see how much faster the") print("sequence of q_n's converges.") # TASK 3 print() print("TASK 3") # solve for z (x3 in the task) using sympy x = Symbol('x') #x1 y = Symbol('y') #x2 z = Symbol('z') #x3 print("solution via SymPy:", solvers.solve(2*x**2 - y**2 + 2*z**2 - 10*x*y - 4*x*z + 10*y*z - 1, z)) # the function obtained above via SymPy f1 = lambda x, y: x - 5*y/2 - sqrt(27*y**2 + 2)/2 f2 = lambda x, y: x - 5*y/2 + sqrt(27*y**2 + 2)/2 # calculate a sample of values for the plot within x, y in [-1, 1] x, y = np.meshgrid(np.linspace(-1, 1), np.linspace(-1, 1)) z1 = f1(x, y) z2 = f2(x, y) # plot them as surfaces (slow) or as contours (fast) plt.figure(figsize=(6, 8)) ax = plt.axes(projection='3d') ax.set_xlabel('x') ax.set_ylabel('y')
def match_template(template, program): """Match a template against a Blackbird program, returning template parameter values. For example, consider the following template and program: .. code-block:: python template = blackbird.loads(\"\"\"\\ name prog version 1.0 Dgate(-{r}, 0.45) | 1 Vac | 2 Sgate({r}, 2*{phi}-1) | 0 \"\"\") program = blackbird.loads(\"\"\"\\ name prog version 1.0 Sgate(0.543, -1.432*pi) | 0 Dgate(-0.543, 0.45) | 1 Vac | 2 \"\"\") By applying the ``match_template`` function, we can match the template parameters: >>> res = match_template(template, program) >>> print(res) {'r': 0.543, 'phi': -1.74938033997029} Verifying this is correct: >>> print((-1.432*np.pi+1)/2) -1.7493803399702919 .. note:: The template and the Blackbird program to match must have the *same* version number and target, otherwise an :class:`TemplateError` will be raised. Args: template (blackbird.Program): the Blackbird template program (blackbird.Program): a Blackbird program to match against the template Returns: dict[str, Number]: mapping from the template parameter name to a numerical value. """ # check template if not template.is_template(): raise TemplateError("Argument 1 is not a template.") if program.is_template(): raise TemplateError("Argument 2 cannot be a template.") if template.version != program.version: raise TemplateError("Mismatching Blackbird version between template and program") if template.target['name'] != program.target['name']: raise TemplateError("Mismatching target between template and program") G1 = to_DiGraph(template) G2 = to_DiGraph(program) def node_match(n1, n2): """Returns True if both nodes have the same name""" return n1['name'] == n2['name'] and n1['modes'] == n2['modes'] GM = isomorphism.DiGraphMatcher(G1, G2, node_match) # check if topology matches if not GM.is_isomorphic(): raise TemplateError("Not the same program.") G1nodes = G1.nodes().data() G2nodes = G2.nodes().data() argmatch = {} key = "" for n1, n2 in GM.mapping.items(): for x, y in zip(G1nodes[n1]['args'], G2nodes[n2]['args']): if np.all(x != y): if isinstance(x, sym.Symbol): key = str(x) val = y elif isinstance(x, sym.Expr): # need to symbolically solve for the symbol var = x.free_symbols if len(var) > 1: raise TemplateError("Matching template parameters only supports " "one template parameter per gate argument.") res = solve(x-y, var) key = str(var)[1:-1] val = float(res[-1]) if key in argmatch: if argmatch[key] != val: raise TemplateError("Template parameter {} matches inconsistent values: " "{} and {}".format(key, val, argmatch[key])) if key != "": argmatch[key] = val p_params = { k: program.variables[str(v)] for k, v in argmatch.items() if str(v) in program.variables } argmatch.update(p_params) return argmatch
dydt = k3_val * (1 - x_num - y_num)**2 - k3_inv_val * y_num**2 dvdt = [dxdt, dydt] return dvdt x = Symbol('x') y = Symbol('y') k1 = Symbol('k1') k1_inv = Symbol('k1_inv') k2 = Symbol('k2') k3 = Symbol('k3') k3_inv = Symbol('k3_inv') f1 = k1 * (1 - x - y) - k1_inv * x - k2 * x * (1 - x - y)**2 f2 = k3 * (1 - x - y)**2 - k3_inv * y**2 y_expr = solve(f2, y)[1] f1_tmp = f1.subs({y: y_expr}) k_expr = solve(f1_tmp, k2)[0] print(k_expr) # print(y_expr) a11 = sym.diff(f1, x) a12 = sym.diff(f1, y) a21 = sym.diff(f2, x) a22 = sym.diff(f2, y) detA = a11 * a22 - a12 * a21 trA = a11 + a22 k1_inv_expr_fold = solve(((a11 + a22).subs({k2: k_expr})).subs({y: y_expr}),
eqB17 = μ_Ba * (B_B - Ba) eqB18 = μ_Bb * (B_B - Bb) # market clearing conditions eqC1 = B_B + Bh + M - .5 * B eqC2 = Ba + Bb + B_ha + B_hb eqC3 = Ma + Mb - 2 * R_M * M eqC4 = I - (λb * A * R_W - R_M * M - Bb * P_B) # redundant variables eqR1 = P_B1 - P_B s_HH = solve( (eq1, eq2, eq3, eq4, eq5, eq6, eq7, eq8, eq9, eq10, eq11, eq12, eq13), R_E1, R_D1, μ_D1, μ_E1, μ_Bh, R_B, P_B, R_E, R_D, μ_λa_, μ_λb_, μ_λa, μ_λb, B_ha) s_HH = solve( (eq1, eq2, eq3, eq4, eq5, eq6, eq7, eq8, eq9, eq10, eq11, eq12, eq13), R_E1, R_D1, μ_E1, μ_Bh, R_B, P_B, R_E, R_D, μ_λa_, μ_λb_, μ_λa,
def _eval_imageset(self, f): from sympy.functions.elementary.miscellaneous import Min, Max from sympy.solvers import solve from sympy.core.function import diff from sympy.series import limit from sympy.calculus.singularities import singularities # TODO: handle piecewise defined functions # TODO: handle functions with infinitely many solutions (eg, sin, tan) # TODO: handle multivariate functions expr = f.expr if len(expr.free_symbols) > 1 or len(f.variables) != 1: return var = f.variables[0] if not self.start.is_comparable or not self.end.is_comparable: return try: sing = [x for x in singularities(expr, var) if x.is_real and x in self] except NotImplementedError: return if self.left_open: _start = limit(expr, var, self.start, dir="+") elif self.start not in sing: _start = f(self.start) if self.right_open: _end = limit(expr, var, self.end, dir="-") elif self.end not in sing: _end = f(self.end) if len(sing) == 0: solns = solve(diff(expr, var), var) extr = [_start, _end] + [f(x) for x in solns if x.is_real and x in self] start, end = Min(*extr), Max(*extr) left_open, right_open = False, False if _start <= _end: # the minimum or maximum value can occur simultaneously # on both the edge of the interval and in some interior # point if start == _start and start not in solns: left_open = self.left_open if end == _end and end not in solns: right_open = self.right_open else: if start == _end and start not in solns: left_open = self.right_open if end == _start and end not in solns: right_open = self.left_open return Interval(start, end, left_open, right_open) else: return imageset(f, Interval(self.start, sing[0], self.left_open, True)) + \ Union(*[imageset(f, Interval(sing[i], sing[i + 1]), True, True) for i in range(1, len(sing) - 1)]) + \ imageset(f, Interval(sing[-1], self.end, True, self.right_open))
def __get_eigenvalues_for_matrix_2x2(data: np.array) -> np.array: x = Symbol('x') return solve( (data[0][0] - x) * (data[1][1] - x) - data[0][1] * data[1][0], x)
def step(self, action, return_price=False): if self.current_portfolio_value == None: raise Exception("Please call reset first") execute_action = False execute_sell = False current_stock_price = self.index_feature_dataframe.iloc[ self.current_time_index][0] value_in_stock = self.quantity * current_stock_price current_percent_value_in_stock = value_in_stock / self.current_portfolio_value if current_percent_value_in_stock < action: need_to_buy = True need_to_sell = False else: need_to_buy = False need_to_sell = True if need_to_buy: x = Symbol('x') r = solve((value_in_stock + x) / (value_in_stock + x + self.cash - x) - action, x) r = float(r[0]) if r > self.min_transaction_value: if r > self.cash: r = self.cash self.cash -= r bought_quantity = r / current_stock_price self.quantity += bought_quantity execute_action = True if need_to_sell: x = Symbol('x') r = solve((value_in_stock - x) / (value_in_stock - x + self.cash + x) - action, x) # if len(r)==0 and self.cash < 1: # #sell everything # x = Symbol('x') # temp_cash = 0.01 # r = solve((value_in_stock-x)/(value_in_stock-x+temp_cash+x) - action,x) r = float(r[0]) if r > self.min_transaction_value: sold_quantity = r / current_stock_price if sold_quantity > self.quantity: sold_quantity = self.quantity self.quantity -= sold_quantity self.cash += sold_quantity * current_stock_price execute_action = True execute_sell = True # #we also need to update the naive hold quantity # self.buy_and_hold_stock_quantity -= sold_quantity # if return_price: # print('sold at least once') self.current_time_index += 1 current_stock_price = self.index_feature_dataframe.iloc[ self.current_time_index][0] value_in_stock = self.quantity * current_stock_price self.current_portfolio_value = self.cash + value_in_stock current_percent_value_in_stock = value_in_stock / self.current_portfolio_value observation = self.index_feature_dataframe.iloc[ self.current_time_index][2:].to_numpy() observation = observation.reshape((-1, 1)) observation = np.concatenate( (observation, [[current_percent_value_in_stock]]), axis=0) #observation = observation.astype('float64') reward = (self.current_portfolio_value / current_stock_price) - self.buy_and_hold_stock_quantity reward = 0 if return_price: return current_stock_price, observation, execute_action, need_to_buy, need_to_sell, self.current_portfolio_value, r return observation, reward, execute_sell
def deltaintegrate(f, x): """ deltaintegrate(f, x) The idea for integration is the following: - If we are dealing with a DiracDelta expression, i.e. DiracDelta(g(x)), we try to simplify it. If we could simplify it, then we integrate the resulting expression. We already know we can integrate a simplified expression, because only simple DiracDelta expressions are involved. If we couldn't simplify it, there are two cases: 1) The expression is a simple expression: we return the integral, taking care if we are dealing with a Derivative or with a proper DiracDelta. 2) The expression is not simple (i.e. DiracDelta(cos(x))): we can do nothing at all. - If the node is a multiplication node having a DiracDelta term: First we expand it. If the expansion did work, the we try to integrate the expansion. If not, we try to extract a simple DiracDelta term, then we have two cases: 1) We have a simple DiracDelta term, so we return the integral. 2) We didn't have a simple term, but we do have an expression with simplified DiracDelta terms, so we integrate this expression. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.integrals.deltafunctions import deltaintegrate >>> from sympy import sin, cos, DiracDelta, Heaviside >>> deltaintegrate(x*sin(x)*cos(x)*DiracDelta(x - 1), x) sin(1)*cos(1)*Heaviside(x - 1) >>> deltaintegrate(y**2*DiracDelta(x - z)*DiracDelta(y - z), y) z**2*DiracDelta(x - z)*Heaviside(y - z) See Also ======== sympy.functions.special.delta_functions.DiracDelta sympy.integrals.integrals.Integral """ if not f.has(DiracDelta): return None # g(x) = DiracDelta(h(x)) if f.func == DiracDelta: h = f.simplify(x) if h == f:#can't simplify the expression #FIXME: the second term tells whether is DeltaDirac or Derivative #For integrating derivatives of DiracDelta we need the chain rule if f.is_simple(x): if (len(f.args) <= 1 or f.args[1]==0): return Heaviside(f.args[0]) else: return (DiracDelta(f.args[0],f.args[1]-1)/ f.args[0].as_poly().LC()) else:#let's try to integrate the simplified expression fh = sympy.integrals.integrate(h, x) return fh elif f.is_Mul: #g(x)=a*b*c*f(DiracDelta(h(x)))*d*e g = f.expand() if f != g:#the expansion worked fh = sympy.integrals.integrate(g, x) if fh and not isinstance(fh, sympy.integrals.Integral): return fh else:#no expansion performed, try to extract a simple DiracDelta term dg, rest_mult = change_mul(f, x) if not dg: if rest_mult: fh = sympy.integrals.integrate(rest_mult, x) return fh else: dg = dg.simplify(x) if dg.is_Mul: # Take out any extracted factors dg, rest_mult_2 = change_mul(dg, x) rest_mult = rest_mult*rest_mult_2 point = solve(dg.args[0],x)[0] return (rest_mult.subs(x, point)*Heaviside(x - point)) return None
def __init__(self): super().__init__() # This is a tuning parameter self._rho = 0.5 nx_bar, ny_bar, nz_bar = Symbol('nx_bar', real=True), Symbol( 'ny_bar', real=True), Symbol('nz_bar', real=True) p_bar, q_bar, r_bar = Symbol('p_bar', real=True), Symbol( 'q_bar', real=True), Symbol('r_bar', real=True) eps = Symbol('eps', real=True) omega1_bar, omega2_bar, omega3_bar, omega4_bar = Symbol( 'omega1_bar', real=True), Symbol('omega2_bar', real=True), Symbol( 'omega3_bar', real=True), Symbol('omega4_bar', real=True) variables = [omega1_bar, r_bar, q_bar] eq1 = self.kappa_f * self.l* self.l* self._rho * omega1_bar**2 - \ (self.IzzT - self.IxxT) * q_bar * r_bar - self.IzzP * (2 + np.sqrt(self._rho)) * omega1_bar * q_bar eq2 = -self.gamma * r_bar + self.kappa_tau * \ self.kappa_f * (2 - self._rho) * omega1_bar**2 eq3 = (r_bar * self.kappa_f * (2 + self._rho) * omega1_bar**2) / ( q_bar**2 + r_bar**2)**(1 / 2) - 9.8 * self.mass equation = [eq1, eq2, eq3] sol = solve(equation, variables) variables = [ nx_bar, ny_bar, nz_bar, p_bar, q_bar, r_bar, eps, omega1_bar, omega2_bar, omega3_bar, omega4_bar ] eq1 = self.kappa_f * (omega2_bar**2 - omega4_bar**2) * self.l - (self.IzzT - self.IxxT) * \ q_bar * r_bar - self.IzzP * q_bar * (omega1_bar + omega2_bar + omega3_bar + omega4_bar) eq2 = self.kappa_f * (omega3_bar ** 2 - omega1_bar ** 2) * self.l + (self.IzzT - self.IxxT) * \ p_bar * r_bar + self.IzzP * p_bar * (omega1_bar + omega2_bar + omega3_bar + omega4_bar) eq3 = -self.gamma * r_bar + self.kappa_tau * self.kappa_f * \ (omega1_bar**2 - omega2_bar**2 + omega3_bar ** 2 - omega4_bar**2) eq4 = nx_bar - eps * p_bar eq5 = ny_bar - eps * q_bar eq6 = nz_bar - eps * r_bar eq7 = eps**2 * (p_bar**2 + q_bar**2 + r_bar**2) - 1 eq8 = self.mass * 9.8 - nz_bar * self.kappa_f * \ (omega1_bar**2 + omega2_bar**2 + omega3_bar**2 + omega4_bar**2) eq9 = omega2_bar**2 - self.rho * omega1_bar**2 eq10 = omega1_bar - omega3_bar eq11 = omega4_bar eq12 = p_bar equations = [ eq1, eq2, eq3, eq4, eq5, eq6, eq7, eq8, eq9, eq10, eq11, eq12 ] sol = solve(equations, variables) self._p_bar = 0 # in general p_bar can be obtained using this # factor = self.r_bar * (self.IzzT - self.IxxT) + self.IzzP * ( # self.omega1_bar + self.omega2_bar + self.omega3_bar + self.omega4_bar) #self._p_bar = -self.kappa_f * (self.omega3_bar ** 2 - self.omega1_bar ** 2) * self.l / factor factor = self.r_bar * (self.IzzT - self.IxxT) + self.IzzP * ( self.omega1_bar + self.omega2_bar + self.omega3_bar + self.omega4_bar) self._q_bar = self.kappa_f * \ (self.omega2_bar ** 2 - self.omega4_bar ** 2) * self.l / factor
def find_ck(self, amin, amax, smin, smax, Cmin, pexp, Rexp): '''Finds ck metric Args: amin (float): minimum semi-major axis value in AU amax (float): maximum semi-major axis value in AU smin (ndarray): 1D array of minimum separation values in AU smax (ndarray): 1D array of maximum separation values in AU Cmin (float): minimum contrast value pexp (float): expected value of geometric albedo Rexp (float): expected value of planetary radius in AU Returns: ck (ndarray): 1D array of ck metric ''' an = 1.0 / np.log(amax / amin) cg = an * (np.sqrt(1.0 - (smax / amax)**2) - np.sqrt(1.0 - (smin / amax)**2) + np.log(smax / (np.sqrt(1.0 - (smax / amax)**2) + 1.0)) - np.log(smin / (np.sqrt(1.0 - (smin / amax)**2) + 1.0))) # calculate ck anp = an / cg # intermediate values k1 = np.cos(0.5 * (np.pi - np.arcsin(smin / amax)))**4 / amax**2 k2 = np.cos(0.5 * (np.pi - np.arcsin(smax / amax)))**4 / amax**2 k3 = np.cos(0.5 * np.arcsin(smax / amax))**4 / amax**2 k4 = 27.0 / 64.0 * smax**(-2) k5 = np.cos(0.5 * np.arcsin(smin / amax))**4 / amax**2 k6 = 27.0 / 64.0 * smin**(-2) # set up z = sympy.Symbol('z', positive=True) k = sympy.Symbol('k', positive=True) b = sympy.Symbol('b', positive=True) # solve sol = solve(z**4 - z**3 / sympy.sqrt(k) + b**2 / (4 * k), z) # third and fourth roots give valid roots # lambdify these roots sol3 = sympy.lambdify((k, b), sol[2], "numpy") sol4 = sympy.lambdify((k, b), sol[3], "numpy") # find ck ck = np.zeros(smin.shape) kmin = Cmin / (pexp * Rexp**2) for i in xrange(len(ck)): if smin[i] == smax[i]: ck[i] = 0.0 else: # equations to integrate al1 = lambda k: sol3(k, smin[i]) au1 = lambda k: sol4(k, smin[i]) au2 = lambda k: sol3(k, smax[i]) al2 = lambda k: sol4(k, smax[i]) f12 = lambda k: anp[i] / (2.0 * np.sqrt(k)) * (amax - al1(k)) f23 = lambda k: anp[i] / (2.0 * np.sqrt(k)) * (au2(k) - al1(k)) f34 = lambda k: anp[i] / (2.0 * np.sqrt(k)) * (amax - al2(k) + au2(k) - al1(k)) f45 = lambda k: anp[i] / (2.0 * np.sqrt(k)) * (amax - al1(k)) f56 = lambda k: anp[i] / (2.0 * np.sqrt(k)) * (au1(k) - al1(k)) f35 = lambda k: anp[i] / (2.0 * np.sqrt(k)) * (amax - al2(k) + au2(k) - al1(k)) f54 = lambda k: anp[i] / (2.0 * np.sqrt(k)) * (au1(k) - al2( k) + au2(k) - al1(k)) f46 = lambda k: anp[i] / (2.0 * np.sqrt(k)) * (au1(k) - al1(k)) if k4[i] < k5[i]: if kmin < k1[i]: ck[i] = integrate.quad(f12, k1[i], k2[i], limit=50, epsabs=0, epsrel=1e-4)[0] if k2[i] != k3[i]: ck[i] += integrate.quad(f23, k2[i], k3[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f34, k3[i], k4[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f45, k4[i], k5[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f56, k5[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin > k1[i]) and (kmin < k2[i]): ck[i] = integrate.quad(f12, kmin, k2[i], limit=50, epsabs=0, epsrel=1e-4)[0] if k2[i] != k3[i]: ck[i] += integrate.quad(f23, k2[i], k3[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f34, k3[i], k4[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f45, k4[i], k5[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f56, k5[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin > k2[i]) and (kmin < k3[i]): ck[i] = integrate.quad(f23, kmin, k3[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f34, k3[i], k4[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f45, k4[i], k5[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f56, k5[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin > k3[i]) and (kmin < k4[i]): ck[i] = integrate.quad(f34, kmin, k4[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f45, k4[i], k5[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f56, k5[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin > k4[i]) and (kmin < k5[i]): ck[i] = integrate.quad(f45, kmin, k5[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f56, k5[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin < k6[i]): ck[i] = integrate.quad(f56, kmin, k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] else: ck[i] = 0.0 else: if kmin < k1[i]: ck[i] = integrate.quad(f12, k1[i], k2[i], limit=50, epsabs=0, epsrel=1e-4)[0] if k2[i] != k3[i]: ck[i] += integrate.quad(f23, k2[i], k3[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f35, k3[i], k5[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f54, k5[i], k4[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f46, k4[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin > k1[i]) and (kmin < k2[i]): ck[i] = integrate.quad(f12, kmin, k2[i], limit=50, epsabs=0, epsrel=1e-4)[0] if k2[i] != k3[i]: ck[i] += integrate.quad(f23, k2[i], k3[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f35, k3[i], k5[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f54, k5[i], k4[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f46, k4[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin > k2[i]) and (kmin < k3[i]): ck[i] = integrate.quad(f23, kmin, k3[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f35, k3[i], k5[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f54, k5[i], k4[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f46, k4[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin > k3[i]) and (kmin < k5[i]): ck[i] = integrate.quad(f35, kmin, k5[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f54, k5[i], k4[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f46, k4[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin > k5[i]) and (kmin < k4[i]): ck[i] = integrate.quad(f54, kmin, k4[i], limit=50, epsabs=0, epsrel=1e-4)[0] ck[i] += integrate.quad(f46, k4[i], k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] elif (kmin < k6[i]): ck[i] = integrate.quad(f46, kmin, k6[i], limit=50, epsabs=0, epsrel=1e-4)[0] else: ck[i] = 0.0 return ck
def l_max(theta, R, d): # R : size of the galaxy x = Symbol("x") solution = solve((x * x + d * d - R * R) / (2 * x * d) - np.cos(theta), x) return np.float(max(solution))
def intersection(self, o): """The intersection of this ellipse and another geometrical entity `o`. Parameters ========== o : GeometryEntity Returns ======= intersection : list of GeometryEntity objects Notes ----- Currently supports intersections with Point, Line, Segment, Ray, Circle and Ellipse types. See Also ======== sympy.geometry.entity.GeometryEntity Examples ======== >>> from sympy import Ellipse, Point, Line, sqrt >>> e = Ellipse(Point(0, 0), 5, 7) >>> e.intersection(Point(0, 0)) [] >>> e.intersection(Point(5, 0)) [Point2D(5, 0)] >>> e.intersection(Line(Point(0,0), Point(0, 1))) [Point2D(0, -7), Point2D(0, 7)] >>> e.intersection(Line(Point(5,0), Point(5, 1))) [Point2D(5, 0)] >>> e.intersection(Line(Point(6,0), Point(6, 1))) [] >>> e = Ellipse(Point(-1, 0), 4, 3) >>> e.intersection(Ellipse(Point(1, 0), 4, 3)) [Point2D(0, -3*sqrt(15)/4), Point2D(0, 3*sqrt(15)/4)] >>> e.intersection(Ellipse(Point(5, 0), 4, 3)) [Point2D(2, -3*sqrt(7)/4), Point2D(2, 3*sqrt(7)/4)] >>> e.intersection(Ellipse(Point(100500, 0), 4, 3)) [] >>> e.intersection(Ellipse(Point(0, 0), 3, 4)) [Point2D(3, 0), Point2D(-363/175, -48*sqrt(111)/175), Point2D(-363/175, 48*sqrt(111)/175)] >>> e.intersection(Ellipse(Point(-1, 0), 3, 4)) [Point2D(-17/5, -12/5), Point2D(-17/5, 12/5), Point2D(7/5, -12/5), Point2D(7/5, 12/5)] """ # TODO: Replace solve with nonlinsolve, when nonlinsolve will be able to solve in real domain x = Dummy('x', real=True) y = Dummy('y', real=True) if isinstance(o, Point): if o in self: return [o] else: return [] elif isinstance(o, (Segment2D, Ray2D)): ellipse_equation = self.equation(x, y) result = solve([ ellipse_equation, Line(o.points[0], o.points[1]).equation(x, y) ], [x, y]) return list(ordered([Point(i) for i in result if i in o])) elif isinstance(o, (Ellipse, Line2D)): if o == self: return self else: ellipse_equation = self.equation(x, y) return list( ordered([ Point(i) for i in solve([ellipse_equation, o.equation(x, y)], [x, y]) ])) elif isinstance(o, LinearEntity3D): raise TypeError( 'Entity must be two dimensional, not three dimensional') else: raise TypeError('Wrong type of argument were put')
def calculate_s_q(t, A_residual, peaks, final_params, tp): t0, tE, u0, fs, xe,xp, b1,b2, a, n, w, c, s = final_params[0], final_params[1], final_params[2], final_params[3],\ final_params[4], final_params[5], final_params[6], final_params[7],\ final_params[8], final_params[9], final_params[10], final_params[11],\ final_params[12] model = Double_horn(xe, xp, b1, b2, a, n, w, c, s, t) if np.mean(model[model != 0.0]) > 0: min_model = 0.0001 else: min_model = -0.0001 cc = 'None' if (c != 0): if (min_model > 0): max1 = t[(model[t > (np.median(t[model > min_model]))]).idxmax] max2 = t[(model[t < (np.median(t[model > min_model]))]).idxmax] tEp = (max(t[model > min_model]) - min(t[model > min_model])) / 2 cc = 'Major' tp_dd = max1 + (max2 - max1) / 2 t_new = t[(t > tp - tEp - 5) & (t < tp + tEp + 5)] model_new = Double_horn(xe, xp, b1, b2, a, n, w, c, s, t_new - t0) residual_new = A_residual[(t > tp - tEp - 5) & (t < tp + tEp + 5)] double_check = np.abs( np.sum( (residual_new - model_new)[(residual_new - model_new) < 0]) / np.sum((residual_new - model_new)[(residual_new - model_new) > 0])) else: max1 = t[(model[t > (np.median(t[model < min_model]))]).idxmin] max2 = t[(model[t < (np.median(t[model < min_model]))]).idxmin] tEp = (max(t[model < min_model]) - min(t[model < min_model])) / 2 cc = 'Minor' t1 = max1 t2 = max2 u1 = np.sqrt(((t1 - t0) / tE)**2 + (u0)**2) u2 = np.sqrt(((t2 - t0) / tE)**2 + (u0)**2) s0s1 = np.sqrt((u1)**2 - (u0)**2) s0s2 = np.sqrt((u2)**2 - (u0)**2) s1s2 = s0s1 - s0s2 if cc == 'Major': xs1 = (s1s2 * s0s1) / u1 Lx = u1 - xs1 s0 = Symbol('s0') s_final = (solve(s0 - (1 / s0) - Lx, s0))[1] if (xs1 > u1): q_final = ((max2 - max1) / tE)**2 else: q_final = (xs1 * float(s_final) * np.sqrt(float(s_final**2 - 1)) / 2.)**2 q_final2 = (tEp / tE)**2 q_final = (q_final2 + q_final) / 2 if double_check > 1: cc = 'Minor' if cc == 'Minor': xs1 = s1s2 / 2. xs0 = s0s2 + xs1 Lx = np.sqrt((xs0**2) + (u0**2)) s0 = Symbol('s0') s_final = (solve((1 / s0) - s0 - Lx, s0))[1] q_final = (16 * (s1s2**2)) / ((256. / s_final**2) + 27 * s_final**6) if np.abs(max1 - max2) < 0.2: c = 0 else: if (min_model > 0): tp = t[model.idxmax] - t0 cc = 'Major' tEp = (max(t[model > min_model]) - min(t[model > min_model])) / 2 t_new = t[(t > tp - 10) & (t < tp + 10)] residual_new = A_residual[(t > tp - 10) & (t < tp + 10)] model_new = Double_horn(xe, xp, b1, b2, a, n, w, c, s, t_new - t0) double_check = np.abs( np.sum( (residual_new - model_new)[(residual_new - model_new) < 0]) / np.sum((residual_new - model_new)[(residual_new - model_new) > 0])) if double_check > 1: tp = t[(model).idxmin] - t0 cc = 'Minor' else: tp = t[(model).idxmin] - t0 cc = 'Minor' tEp = (max(t[model < min_model]) - min(t[model < min_model])) / 2 u = np.sqrt(((tp) / tE)**2 + (u0)**2) s0 = Symbol('s0') s_final = (solve(s0 - (1 / s0) - u, s0))[1] if cc == 'Minor': s_final = 1. / s_final q_final = (tEp / tE)**2 return s_final, q_final, tEp
params.add('b', value = 0.01) params.add('c', value = -150) l_minner = Minimizer(residual, params, fcn_args=(left_data_x, left_data_y)) l_result = l_minner.minimize() report_fit(l_result) ###extract left parameters from model left_a = l_result.params['a'].value left_b = l_result.params['b'].value left_c = l_result.params['c'].value ###solve for left SOAs x = Symbol('x') ASOA50 = solve(left_a / (1 + 2.71828 ** (-left_b * (x - left_c))) - 0.5, x, rational = False)[0] #unclear why np.exp() doesn't work ASOA95 = solve(left_a / (1 + 2.71828 ** (-left_b * (x - left_c))) - 0.05, x, rational = False)[0] ###generate left sigmoid line data x_l_fun = np.linspace(-300, 0, 500) y_l_fun = left_a / (1 + np.exp(-left_b * (x_l_fun - left_c))) #fit right curve right_data_x = df_rate.SOA[df_rate.SOA >= 0] right_data_y = df_rate.sync_rate[df_rate.SOA >= 0] params = Parameters() params.add('a', value = 1) params.add('b', value = -0.01) params.add('c', value = 150)
def tangent_lines(self, p): """Tangent lines between `p` and the ellipse. If `p` is on the ellipse, returns the tangent line through point `p`. Otherwise, returns the tangent line(s) from `p` to the ellipse, or None if no tangent line is possible (e.g., `p` inside ellipse). Parameters ========== p : Point Returns ======= tangent_lines : list with 1 or 2 Lines Raises ====== NotImplementedError Can only find tangent lines for a point, `p`, on the ellipse. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Line Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.tangent_lines(Point(3, 0)) [Line2D(Point2D(3, 0), Point2D(3, -12))] >>> # This will plot an ellipse together with a tangent line. >>> from sympy.plotting.pygletplot import PygletPlot as Plot >>> from sympy import Point, Ellipse >>> e = Ellipse(Point(0,0), 3, 2) >>> t = e.tangent_lines(e.random_point()) >>> p = Plot() >>> p[0] = e # doctest: +SKIP >>> p[1] = t # doctest: +SKIP """ p = Point(p, dim=2) if self.encloses_point(p): return [] if p in self: delta = self.center - p rise = (self.vradius**2) * delta.x run = -(self.hradius**2) * delta.y p2 = Point(simplify(p.x + run), simplify(p.y + rise)) return [Line(p, p2)] else: if len(self.foci) == 2: f1, f2 = self.foci maj = self.hradius test = (2 * maj - Point.distance(f1, p) - Point.distance(f2, p)) else: test = self.radius - Point.distance(self.center, p) if test.is_number and test.is_positive: return [] # else p is outside the ellipse or we can't tell. In case of the # latter, the solutions returned will only be valid if # the point is not inside the ellipse; if it is, nan will result. x, y = Dummy('x'), Dummy('y') eq = self.equation(x, y) dydx = idiff(eq, y, x) slope = Line(p, Point(x, y)).slope # TODO: Replace solve with solveset, when this line is tested tangent_points = solve([slope - dydx, eq], [x, y]) # handle horizontal and vertical tangent lines if len(tangent_points) == 1: assert tangent_points[0][0] == p.x or tangent_points[0][ 1] == p.y return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))] # others return [Line(p, tangent_points[0]), Line(p, tangent_points[1])]
delim_whitespace=True, skipinitialspace=True); ai = 62/180*np.pi; aph = 60/180*np.pi; R =1; D = 0.2e-7; z = np.polyfit(neff["Wavelength(microns)"]*1e-6, neff["Effective_Index"], 1); dneffdivdwl = z[0]; ngdivneff = 1.9838; resolution = 0.125 FSR = 20e-9; m = Symbol('m') sol = solve(wavelength_center/m*pow(1-(m+1)/m*(1-ngdivneff),-1)-FSR,m); lambda_0 =np.linspace(wavelength_start, wavelength_stop, round((wavelength_stop-wavelength_start)*1e9/resolution)) neff_0 = z[0]*lambda_0+z[1]; d=32*wavelength_center/(neff_0[400]*(np.sin(ai)+np.sin(aph))) #diffraction equation output T =[] for i in range(len(lambda_0)): k = 2*np.pi*neff_0[i]/lambda_0[i]; def f(y): return np.exp(1j*k*y*np.sin(ai))*(np.exp(-1j*k*198e-6)/np.sqrt(198e-6))*(np.cos(ai)+np.cos(aph))/2 v,err =integrate.quad(f,-0.5*d,0.5*d) eout= R*np.sqrt(neff_0[i]/lambda_0[i])*1*v t= np.absolute(eout)**2
def deltasummation(f, limit, no_piecewise=False): """ Handle summations containing a KroneckerDelta. The idea for summation is the following: - If we are dealing with a KroneckerDelta expression, i.e. KroneckerDelta(g(x), j), we try to simplify it. If we could simplify it, then we sum the resulting expression. We already know we can sum a simplified expression, because only simple KroneckerDelta expressions are involved. If we couldn't simplify it, there are two cases: 1) The expression is a simple expression: we return the summation, taking care if we are dealing with a Derivative or with a proper KroneckerDelta. 2) The expression is not simple (i.e. KroneckerDelta(cos(x))): we can do nothing at all. - If the expr is a multiplication expr having a KroneckerDelta term: First we expand it. If the expansion did work, then we try to sum the expansion. If not, we try to extract a simple KroneckerDelta term, then we have two cases: 1) We have a simple KroneckerDelta term, so we return the summation. 2) We didn't have a simple term, but we do have an expression with simplified KroneckerDelta terms, so we sum this expression. Examples ======== >>> from sympy import oo, symbols >>> from sympy.abc import k >>> i, j = symbols('i, j', integer=True, finite=True) >>> from sympy.concrete.delta import deltasummation >>> from sympy import KroneckerDelta, Piecewise >>> deltasummation(KroneckerDelta(i, k), (k, -oo, oo)) 1 >>> deltasummation(KroneckerDelta(i, k), (k, 0, oo)) Piecewise((1, i >= 0), (0, True)) >>> deltasummation(KroneckerDelta(i, k), (k, 1, 3)) Piecewise((1, (i >= 1) & (i <= 3)), (0, True)) >>> deltasummation(k*KroneckerDelta(i, j)*KroneckerDelta(j, k), (k, -oo, oo)) j*KroneckerDelta(i, j) >>> deltasummation(j*KroneckerDelta(i, j), (j, -oo, oo)) i >>> deltasummation(i*KroneckerDelta(i, j), (i, -oo, oo)) j See Also ======== deltaproduct sympy.functions.special.tensor_functions.KroneckerDelta sympy.concrete.sums.summation """ from sympy.concrete.summations import summation from sympy.solvers import solve x, a, b = limit b -= 1 if ((b - a) < 0) == True: return S.Zero if not f.has(KroneckerDelta): return summation(f, limit) g = _expand_delta(f, x) if g.is_Add: return piecewise_fold( g.func(*[deltasummation(h, limit, no_piecewise) for h in g.args])) # try to extract a simple KroneckerDelta term delta, expr = _extract_delta(g, x) if not delta: return summation(f, limit) solns = solve(delta.args[0] - delta.args[1], x) if len(solns) == 0: return S.Zero elif len(solns) != 1: from sympy.concrete.summations import Sum return Sum(f, limit) value = solns[0] if no_piecewise: return expr.subs(x, value) return Piecewise( (expr.subs(x, value), Interval(a, b).as_relational(value)), (S.Zero, True))
def parametric_log_deriv_heu(fa, fd, wa, wd, DE, c1=None): """ Parametric logarithmic derivative heuristic. Given a derivation D on k[t], f in k(t), and a hyperexponential monomial theta over k(t), raises either NotImplementedError, in which case the heuristic failed, or returns None, in which case it has proven that no solution exists, or returns a solution (n, m, v) of the equation n*f == Dv/v + m*Dtheta/theta, with v in k(t)* and n, m in ZZ with n != 0. If this heuristic fails, the structure theorem approach will need to be used. The argument w == Dtheta/theta """ # TODO: finish writing this and write tests c1 = c1 or Dummy('c1') p, a = fa.div(fd) q, b = wa.div(wd) B = max(0, derivation(DE.t, DE).degree(DE.t) - 1) C = max(p.degree(DE.t), q.degree(DE.t)) if q.degree(DE.t) > B: eqs = [p.nth(i) - c1*q.nth(i) for i in range(B + 1, C + 1)] s = solve(eqs, c1) if not s or not s[c1].is_Rational: # deg(q) > B, no solution for c. return None N, M = s[c1].as_numer_denom() # N and M are integers N, M = Poly(N, DE.t), Poly(M, DE.t) nfmwa = N*fa*wd - M*wa*fd nfmwd = fd*wd Qv = is_log_deriv_k_t_radical_in_field(N*fa*wd - M*wa*fd, fd*wd, DE, 'auto') if Qv is None: # (N*f - M*w) is not the logarithmic derivative of a k(t)-radical. return None Q, e, v = Qv if e != 1: return None if Q.is_zero or v.is_zero: return None return (Q*N, Q*M, v) if p.degree(DE.t) > B: return None c = lcm(fd.as_poly(DE.t).LC(), wd.as_poly(DE.t).LC()) l = fd.monic().lcm(wd.monic())*Poly(c, DE.t) ln, ls = splitfactor(l, DE) z = ls*ln.gcd(ln.diff(DE.t)) if not z.has(DE.t): # TODO: We treat this as 'no solution', until the structure # theorem version of parametric_log_deriv is implemented. return None u1, r1 = (fa*l.quo(fd)).div(z) # (l*f).div(z) u2, r2 = (wa*l.quo(wd)).div(z) # (l*w).div(z) eqs = [r1.nth(i) - c1*r2.nth(i) for i in range(z.degree(DE.t))] s = solve(eqs, c1) if not s or not s[c1].is_Rational: # deg(q) <= B, no solution for c. return None M, N = s[c1].as_numer_denom() nfmwa = N.as_poly(DE.t)*fa*wd - M.as_poly(DE.t)*wa*fd nfmwd = fd*wd Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE) if Qv is None: # (N*f - M*w) is not the logarithmic derivative of a k(t)-radical. return None Q, v = Qv if Q.is_zero or v.is_zero: return None return (Q*N, Q*M, v)
#print(first_OBJ) Get[:0] = [[e, d]] #print(Get) i = -1 prop = dict( (s, eval('Symbol("' + s + '")')) for s in second_OBJ if s not in Ls) prop2 = [ eval('+'.join('%d*%s' % (int(c[1]), c[0]) for c in first_OBJ[s]), {}, prop) for s in first_OBJ ] + [prop['a'] - a] k = solve(prop2, *prop) #print(k) if k: N = [k[prop[s]] for s in sorted(prop)] g = N[0] for a1, a2 in zip(N[0::2], N[1::2]): g = gcd(g, a2) N = [i / g for i in N] #print(c) if c[1] != 1: c[1] = c if c[1] == 1: