def regular_point(self): """ Returns a point on the implicit region. Examples ======== >>> from sympy.abc import x, y >>> from sympy.vector import ImplicitRegion >>> circle = ImplicitRegion((x, y), (x + 2)**2 + (y - 3)**2 - 16) >>> circle.regular_point() (-6, 3) """ # TODO: implement the algorithm to find regular point on a Conic. # Now it iterates over a range and tries to find a point on the region. equation = self.equation if len(self.variables) == 1: return (list(solveset(equation, self.variables[0], domain=S.Reals))[0], ) elif len(self.variables) == 2: x, y = self.variables for x_reg in range(-100, 100): if not solveset(equation.subs(x, x_reg), self.variables[1], domain=S.Reals).is_empty: return (x_reg, list( solveset(equation.subs(x, x_reg), domain=S.Reals))[0]) elif len(self.variables) == 3: x, y, z = self.variables for x_reg in range(-10, 10): for y_reg in range(-10, 10): if not solveset(equation.subs({ x: x_reg, y: y_reg }), self.variables[2], domain=S.Reals).is_empty: return (x_reg, y_reg, list( solveset( equation.subs({ x: x_reg, y: y_reg })))[0]) if len(self.singular_points()) != 0: return list[self.singular_points()][0] raise NotImplementedError()
def regular_point(self): """ Returns a point on the implicit region. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.vector import ImplicitRegion >>> circle = ImplicitRegion((x, y), (x + 2)**2 + (y - 3)**2 - 16) >>> circle.regular_point() (-2, -1) >>> parabola = ImplicitRegion((x, y), x**2 - 4*y) >>> parabola.regular_point() (0, 0) >>> r = ImplicitRegion((x, y, z), (x + y + z)**4) >>> r.regular_point() (-10, -10, 20) References ========== - Erik Hillgarter, "Rational Points on Conics", Diploma Thesis, RISC-Linz, J. Kepler Universitat Linz, 1996. Availaible: https://www3.risc.jku.at/publications/download/risc_1355/Rational%20Points%20on%20Conics.pdf """ equation = self.equation if len(self.variables) == 1: return (list(solveset(equation, self.variables[0], domain=S.Reals))[0],) elif len(self.variables) == 2: if self.degree == 2: coeffs = a, b, c, d, e, f = conic_coeff(self.variables, equation) if b**2 == 4*a*c: x_reg, y_reg = self._regular_point_parabola(*coeffs) else: x_reg, y_reg = self._regular_point_ellipse(*coeffs) return x_reg, y_reg if len(self.variables) == 3: x, y, z = self.variables for x_reg in range(-10, 10): for y_reg in range(-10, 10): if not solveset(equation.subs({x: x_reg, y: y_reg}), self.variables[2], domain=S.Reals).is_empty: return (x_reg, y_reg, list(solveset(equation.subs({x: x_reg, y: y_reg})))[0]) if len(self.singular_points()) != 0: return list[self.singular_points()][0] raise NotImplementedError()
def get_zero_point(self, e): abs_expr = e.body.getAbs() zero_point = [] for a in abs_expr: arg = a.args[0] zeros = solveset(expr.sympy_style(arg), expr.sympy_style(e.var), Interval(sympy_style(e.lower), sympy_style(e.upper), left_open = True, right_open = True)) zero_point += zeros return holpy_style(zero_point[0])
def atten_coeff(disp, solve_mode=0): k = Symbol('k') if solve_mode == 0: # Solve mode for transverse dispersion relation ksol = list(solveset(disp, k))[0] else: # Solve mode for longitudinal dispersion relation ksol = list(nroots(disp, maxsteps=100))[2] alpha = abs(im(ksol)) return alpha
def check_zero_point(self, e): integrals = e.separate_integral() if not integrals: return False abs_info = [] for i, j in integrals: abs_expr = i.getAbs() abs_info += [(a, i) for a in abs_expr] zero_point = [] for a, i in abs_info: arg = a.args[0] zeros = solveset(expr.sympy_style(arg), expr.sympy_style(i.var), Interval(sympy_style(i.lower), sympy_style(i.upper), left_open = True, right_open = True)) zero_point += zeros return len(zero_point) > 0
def K_C(coeff, min_b): #Kong&Cox extension of asymptotic p-value x = Symbol('x', real=True) try: delta = list( solveset(likelihood_diff(x, tuple(coeff)), x, Interval(0, min_b))) except: #use numerical analysis to approach root if there's convergence problem by sympy delta_f = fsolve(likelihood_diff, 0, args=tuple(coeff)) delta = [ tmp_delta for tmp_delta in list(delta_f) if tmp_delta >= 0 and tmp_delta <= min_b ] max_l = None #print "delta:"+repr(delta) if len(delta) == 0: #if there is no zero for likelihood_diff #note likelihood_diff(0,tuple(coeff)) equals to original Z-score and should always be positive here. try: d2 = likelihood_diff(min_b, tuple(coeff)) likelihood(tuple(coeff), min_b) except: drift = 0.01 * min_b min_b = min_b - drift d2 = likelihood_diff(min_b, tuple(coeff)) while d2 < -0.1: min_b = 0.99 * min_b d2 = likelihood_diff(min_b, tuple(coeff)) max_l = likelihood(tuple(coeff), min_b) else: if len(delta) > 1: l_candidates = [] for tmp_delta in delta: try: tmp_l = likelihood(tuple(coeff), tmp_delta) except: tmp_l = likelihood(tuple(coeff), 0.99 * tmp_delta) l_candidates.append(tmp_l) max_l = max(l_candidates) else: try: max_l = likelihood(tuple(coeff), delta[0]) except: max_l = likelihood(tuple(coeff), 0.99 * delta[0]) #print max_l,likelihood(tuple(coeff),0) lrt = max_l - likelihood(tuple(coeff), 0) if lrt < 0: lrt = 0 lrt_stat = math.sqrt(2 * lrt) return lrt_stat, stats.norm.sf(lrt_stat)
def generate_valid_combos(self, prepped_equation, var_ranges, input_array): """Generate a list of variable combinations for all valid problems.""" valid_combos = [] # Generate the set of valid answer values as a FiniteSet. The # FiniteSet is necessary because sympy returns a FiniteSet when # it solves equations. solution_set = FiniteSet(*var_ranges[str(self.x)]) # For every variable combination, substitute the values for each # input variable into the final_equation so sympy can solve for the # remaining variable. for var_values in input_array: final_equation = prepped_equation for i, var in enumerate(self.variables): if i < len(self.variables) - 1: final_equation = final_equation.subs( var['variable'], var_values[i]) # Solve for self.x. answer = solveset(final_equation, self.x) #### Currently, this is just rigged to capture when we have a single integer solution if self.dict['positive_only'] == True: answer = answer.intersection(ConditionSet(x, x > 0)) # Add valid combinations to valid_combos list, with each valid combo as a dict if answer.issubset(solution_set) and answer != set(): valid_combo = {} valid_combo['values'] = {} # Add variable values to dict for i, var in enumerate(self.variables): if i < len(self.variables) - 1: valid_combo['values'][var['variable']] = int( var_values[i] ) ### Forces int, which needs to be updated # Add answer value(s) to dict valid_combo['values'][self.x] = [int(i) for i in answer] valid_combos.append(valid_combo) return valid_combos
def fixedPoints(self): """The fixed points of the 1D system Examples ======== >>> from dynamical1D import DynamicalSystem1D >>> xDot = DynamicalSystem1D((x**2) - 1, x) >>> xDot.fixedPoints [-1, 1] >>> yDot = DynamicalSystem1D(y**2, y) >>> yDot.fixedPoints [0] >>> zDot = DynamicalSystem1D((z+1)*(z-1)*(z**2), z) >>> zDot.fixedPoints [-1, 0, 1] """ fixedPoints = solveset(self.system, self.parameter, domain=S.Reals) (list(fixedPoints)).sort() return list(fixedPoints)
def rational_parametrization(self, parameters=('t', 's'), reg_point=None): """ Returns the rational parametrization of implict region. Examples ======== >>> from sympy import Eq >>> from sympy.abc import x, y, z, s, t >>> from sympy.vector import ImplicitRegion >>> parabola = ImplicitRegion((x, y), y**2 - 4*x) >>> parabola.rational_parametrization() (4/t**2, 4/t) >>> circle = ImplicitRegion((x, y), Eq(x**2 + y**2, 4)) >>> circle.rational_parametrization() (4*t/(t**2 + 1), 4*t**2/(t**2 + 1) - 2) >>> I = ImplicitRegion((x, y), x**3 + x**2 - y**2) >>> I.rational_parametrization() (t**2 - 1, t*(t**2 - 1)) >>> cubic_curve = ImplicitRegion((x, y), x**3 + x**2 - y**2) >>> cubic_curve.rational_parametrization(parameters=(t)) (t**2 - 1, t*(t**2 - 1)) >>> sphere = ImplicitRegion((x, y, z), x**2 + y**2 + z**2 - 4) >>> sphere.rational_parametrization(parameters=(t, s)) (-2 + 4/(s**2 + t**2 + 1), 4*s/(s**2 + t**2 + 1), 4*t/(s**2 + t**2 + 1)) For some conics, regular_points() is unable to find a point on curve. To calulcate the parametric representation in such cases, user need to determine a point on the region and pass it using reg_point. >>> c = ImplicitRegion((x, y), (x - 1/2)**2 + (y)**2 - (1/4)**2) >>> c.rational_parametrization(reg_point=(3/4, 0)) (0.75 - 0.5/(t**2 + 1), -0.5*t/(t**2 + 1)) References ========== - Christoph M. Hoffmann, "Conversion Methods between Parametric and Implicit Curves and Surfaces", Purdue e-Pubs, 1990. Available: https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1827&context=cstech """ equation = self.equation degree = self.degree if degree == 1: if len(self.variables) == 1: return (equation, ) elif len(self.variables) == 2: x, y = self.variables y_par = list(solveset(equation, y))[0] return x, y_par else: raise NotImplementedError() point = () # Finding the (n - 1) fold point of the monoid of degree if degree == 2: # For degree 2 curves, either a regular point or a singular point can be used. if reg_point is not None: # Using point provided by the user as regular point point = reg_point else: if len(self.singular_points()) != 0: point = list(self.singular_points())[0] else: point = self.regular_point() if len(self.singular_points()) != 0: singular_points = self.singular_points() for spoint in singular_points: syms = Tuple(*spoint).free_symbols rep = {s: 2 for s in syms} if len(syms) != 0: spoint = tuple(s.subs(rep) for s in spoint) if self.multiplicity(spoint) == degree - 1: point = spoint break if len(point) == 0: # The region in not a monoid raise NotImplementedError() modified_eq = equation # Shifting the region such that fold point moves to origin for i, var in enumerate(self.variables): modified_eq = modified_eq.subs(var, var + point[i]) modified_eq = expand(modified_eq) hn = hn_1 = 0 for term in modified_eq.args: if total_degree(term) == degree: hn += term else: hn_1 += term hn_1 = -1 * hn_1 if not isinstance(parameters, tuple): parameters = (parameters, ) if len(self.variables) == 2: parameter1 = parameters[0] if parameter1 == 's': # To avoid name conflict between parameters s = _symbol('s_', real=True) else: s = _symbol('s', real=True) t = _symbol(parameter1, real=True) hn = hn.subs({self.variables[0]: s, self.variables[1]: t}) hn_1 = hn_1.subs({self.variables[0]: s, self.variables[1]: t}) x_par = (s * (hn_1 / hn)).subs(s, 1) + point[0] y_par = (t * (hn_1 / hn)).subs(s, 1) + point[1] return x_par, y_par elif len(self.variables) == 3: parameter1, parameter2 = parameters if parameter1 == 'r' or parameter2 == 'r': # To avoid name conflict between parameters r = _symbol('r_', real=True) else: r = _symbol('r', real=True) s = _symbol(parameter2, real=True) t = _symbol(parameter1, real=True) hn = hn.subs({ self.variables[0]: r, self.variables[1]: s, self.variables[2]: t }) hn_1 = hn_1.subs({ self.variables[0]: r, self.variables[1]: s, self.variables[2]: t }) x_par = (r * (hn_1 / hn)).subs(r, 1) + point[0] y_par = (s * (hn_1 / hn)).subs(r, 1) + point[1] z_par = (t * (hn_1 / hn)).subs(r, 1) + point[2] return x_par, y_par, z_par raise NotImplementedError()
def _regular_point_ellipse(self, a, b, c, d, e, f): D = 4 * a * c - b**2 ok = D if not ok: raise ValueError("Rational Point on the conic does not exist") if a == 0 and c == 0: K = -1 L = 4 * (d * e - b * f) elif c != 0: K = D L = 4 * c**2 * d**2 - 4 * b * c * d * e + 4 * a * c * e**2 + 4 * b**2 * c * f - 16 * a * c**2 * f else: K = D L = 4 * a**2 * e**2 - 4 * b * a * d * e + 4 * b**2 * a * f ok = L != 0 and not (K > 0 and L < 0) if not ok: raise ValueError("Rational Point on the conic does not exist") K = Rational(K).limit_denominator(10**12) L = Rational(L).limit_denominator(10**12) k1, k2 = K.p, K.q l1, l2 = L.p, L.q g = gcd(k2, l2) a1 = (l2 * k2) / g b1 = (k1 * l2) / g c1 = -(l1 * k2) / g a2 = sign(a1) * core(abs(a1), 2) r1 = sqrt(a1 / a2) b2 = sign(b1) * core(abs(b1), 2) r2 = sqrt(b1 / b2) c2 = sign(c1) * core(abs(c1), 2) r3 = sqrt(c1 / c2) g = gcd(gcd(a2, b2), c2) a2 = a2 / g b2 = b2 / g c2 = c2 / g g1 = gcd(a2, b2) a2 = a2 / g1 b2 = b2 / g1 c2 = c2 * g1 g2 = gcd(a2, c2) a2 = a2 / g2 b2 = b2 * g2 c2 = c2 / g2 g3 = gcd(b2, c2) a2 = a2 * g3 b2 = b2 / g3 c2 = c2 / g3 x, y, z = symbols("x y z") eq = a2 * x**2 + b2 * y**2 + c2 * z**2 solutions = diophantine(eq) if len(solutions) == 0: raise ValueError("Rational Point on the conic does not exist") flag = False for sol in solutions: syms = Tuple(*sol).free_symbols rep = {s: 3 for s in syms} sol_z = sol[2] if sol_z == 0: flag = True continue if not (isinstance(sol_z, Integer) or isinstance(sol_z, int)): syms_z = sol_z.free_symbols if len(syms_z) == 1: p = next(iter(syms_z)) p_values = Complement( S.Integers, solveset(Eq(sol_z, 0), p, S.Integers)) rep[p] = next(iter(p_values)) if len(syms_z) == 2: p, q = list(ordered(syms_z)) for i in S.Integers: subs_sol_z = sol_z.subs(p, i) q_values = Complement( S.Integers, solveset(Eq(subs_sol_z, 0), q, S.Integers)) if not q_values.is_empty: rep[p] = i rep[q] = next(iter(q_values)) break if len(syms) != 0: x, y, z = tuple(s.subs(rep) for s in sol) else: x, y, z = sol flag = False break if flag: raise ValueError("Rational Point on the conic does not exist") x = (x * g3) / r1 y = (y * g2) / r2 z = (z * g1) / r3 x = x / z y = y / z if a == 0 and c == 0: x_reg = (x + y - 2 * e) / (2 * b) y_reg = (x - y - 2 * d) / (2 * b) elif c != 0: x_reg = (x - 2 * d * c + b * e) / K y_reg = (y - b * x_reg - e) / (2 * c) else: y_reg = (x - 2 * e * a + b * d) / K x_reg = (y - b * y_reg - d) / (2 * a) return x_reg, y_reg
# 2 - Gas material_mode = 2 w_lin = np.linspace(1E-2, 1E7, N) w_log = np.logspace(-2, 7, N) w = np.concatenate((w_lin, w_log), axis=0) f = w / (2 * pi) S0_array = [0.2, 0.4, 0.6, 0.8, 1 - epsilon] S0_label = [str(i) for i in S0_array] k = Symbol('k') for i in range(len(S0_array)): S0 = S0_array[i] print('Progress: ' + str(int(100 * (i + 1) / 5)) + '%') disp_rel = transverse_disp(S0, w, material_mode) k_array = [list(solveset(i, k))[0] for i in disp_rel] speed_array = w[N:] / [abs(re(e)) for e in k_array][N:] attenuation_array = [abs(im(e)) for e in k_array][:N] plt.figure(1) plt.semilogx(f[N:], speed_array, label=S0_label[i]) plt.figure(2) plt.plot(f[:N], attenuation_array, label=S0_label[i]) plt.figure(1) plt.legend() plt.xlabel('frequency / Hz') plt.ylabel(r'velocity / $ms^{-1}$') plt.savefig('../plots/speed_freq_s.eps') plt.clf()
ax.set_ylabel(r'phase speed $(ms^{-1})$') ax.set_xlim(0, 1) for ax in axs2[:,1]: ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.set_xlabel(r'initial saturation $S_0$') ax.set_ylabel(r'attenuation $(m^{-1})$') ax.set_xlim(0, 1) for i in range(len(w_array)): counter += 1 print_progress(counter, total) w = w_array[i] # Transverse case disp_rel = transverse_disp(S0, w, material_mode) ks_array = [[list(solveset(d, k))[0]] for d in disp_rel] counter += 1 print_progress(counter, total) # Longitudinal case disp_rel = longitudinal_disp(S0, w, material_mode) kp_array = [list(nroots(d, maxsteps = 100))[0:3] for d in disp_rel] counter += 1 print_progress(counter, total) # Join arrays ks_array = np.array(ks_array) kp_array = np.array(kp_array) k_array = np.concatenate((ks_array, kp_array), axis = 1) for j in range(4): # Calculate speed and attenuation speed_array = w/[abs(re(e[j])) for e in k_array]
from sympy.solvers import solveset from sympy import Symbol, Interval, pprint x = Symbol('x') sol = solveset(x ** 2 - 1, x, Interval(0, 100)) print(sol)
def is_mono(var, e, lower, upper): """Determine whether an expression is monotonic in the given interval.""" e_deriv = deriv(var, e) zeros = solveset(sympy_style(e_deriv), sympy_style(var), Interval(sympy_style(lower), \ sympy_style(upper), left_open=True, right_open=True)) return list([holpy_style(z) for z in zeros])