def test_add_1(): assert Order(x + x) == Order(x) assert Order(3 * x - 2 * x ** 2) == Order(x) assert Order(1 + x) == Order(1, x) assert Order(1 + 1 / x) == Order(1 / x) assert Order(ln(x) + 1 / ln(x)) == Order(ln(x)) assert Order(exp(1 / x) + x) == Order(exp(1 / x)) assert Order(exp(1 / x) + 1 / x ** 20) == Order(exp(1 / x))
def test_intrinsic_math1_codegen(): # not included: log10 from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, \ sin, sinh, sqrt, tan, tanh, N x = symbols('x') name_expr = [ ("test_fabs", abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_log", log(x)), ("test_ln", ln(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] numerical_tests = [] for name, expr in name_expr: for xval in 0.2, 0.5, 0.8: expected = N(expr.subs(x, xval)) numerical_tests.append((name, (xval,), expected, 1e-14)) for lang, commands in valid_lang_commands: if lang == "C": name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))] else: name_expr_C = [] run_test("intrinsic_math1", name_expr + name_expr_C, numerical_tests, lang, commands)
def euro_call_exact(S, K, T, r, sigma): # S: spot price # K: strike price # T: time to maturity # r: interest rate # sigma: volatility of underlying asset N = systats.Normal(0.0, 1.0) d1 = (sy.ln(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sy.sqrt(T)) d2 = (sy.ln(S / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sy.sqrt(T)) call = S * N.cdf(d1) - K * sy.exp(-r * T) * N.cdf(d2) return call
def test_solve_relation_for_derivatives(): from sympy import symbols, Function, ln x, y = symbols("x, y") f = symbols("f", cls=Function)(x, y) relation = ln(x * y + f) - f subsd = {x: 2, y: 1} diff_wrt = {x: 2, y: 1} df, df_err = solve_relation_for_derivatives( relation, {x: 2, y: 1}, f, {((x, 0), (y, 0)): 1.0}, diff_wrt, verbose=True, abstol=1e-8 ) assert abs(df[((x, 1), (y, 0))] - 0.46594127238) < 1e-8 assert abs(df[((x, 0), (y, 1))] - 0.9318825447699826) < 1e-8 assert abs(df[((x, 1), (y, 1))] + 0.17057414955751987) < 1e-8 assert abs(df[((x, 2), (y, 1))] - 0.37120710736327495) < 1e-8 x, y = symbols("x, y") # x_arg, y_arg = symbols('x_arg, y_arg') g = symbols("g", cls=Function)(x, y) # (x_arg, y_arg) relation = x ** 2 + y ** 2 - g # Circle subsd = {x: 1.0, y: 0.0} initial_guess_func_vals = {((x, 0),): 0.5} diff_wrt = {x: 1} dg, dg_err = solve_relation_for_derivatives( relation, subsd, g, initial_guess_func_vals, diff_wrt, verbose=True, abstol=1e-7 ) assert abs(dg[((x, 1),)] - 2.0) < 1e-7
def test_general_symbolic(self): a, b, c, d, e, x = syp.symbols('a,b,c,d,e,x') # natural log function y = a*syp.ln(b*x**c + d)+e phys = self.phys phys['pore.item1'] = 0.16e-14 phys['pore.item2'] = 4 phys['pore.item3'] = 1.4 phys['pore.item4'] = 0.133 phys['pore.item5'] = -5.1e-14 phys.add_model(propname='pore.source1', model=pm.generic_source_term.natural_logarithm, A1='pore.item1', A2='pore.item2', A3='pore.item3', A4='pore.item4', A5='pore.item5', X='pore.mole_fraction', regen_mode='normal') arg_map=collections.OrderedDict([('a', 'pore.item1'), ('b', 'pore.item2'), ('c', 'pore.item3'), ('d', 'pore.item4'), ('e', 'pore.item5'), ('x', 'pore.mole_fraction')]) phys.add_model(propname='pore.general', model=op.models.physics.generic_source_term.general_symbolic, eqn=y, arg_map=arg_map, regen_mode='normal') assert np.allclose(phys['pore.source1.rate'], phys['pore.general.rate']) assert np.allclose(phys['pore.source1.S1'], phys['pore.general.S1']) assert np.allclose(phys['pore.source1.S2'], phys['pore.general.S2'])
def test_ansi_math1_codegen(): # not included: log10 from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, \ sin, sinh, sqrt, tan, tanh, N x = symbols('x') name_expr = [ ("test_fabs", abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_ceil", ceiling(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_floor", floor(x)), ("test_log", log(x)), ("test_ln", ln(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] numerical_tests = [] for name, expr in name_expr: for xval in 0.2, 0.5, 0.8: expected = N(expr.subs(x, xval)) numerical_tests.append((name, (xval,), expected, 1e-14)) run_cc_test("ansi_math1", name_expr, numerical_tests)
def eta_fil(self, x, V_app, apprx=(0, 0, 0, 0)): m_eff = self.m_r * const.electron_mass mpmath.mp.dps = 20 x0 = Symbol('x0') # eta_fil x1 = Symbol('x1') # eta_ac x2 = Symbol('x2') # eta_hop x3 = Symbol('x3') # V_tunnel f0 = const.Boltzmann * self.T / (1 - self.alpha) / const.elementary_charge / self.z * \ ln(self.A_fil/self.A_ac*(exp(- self.alpha * const.elementary_charge * self.z / const.Boltzmann / self.T * x0) - 1) + 1) - x1# eta_ac = f(eta_fil) x1 = f(x0) f1 = x*2*const.Boltzmann*self.T/self.a/self.z/const.elementary_charge*\ asinh(self.j_0et/self.j_0hop*(exp(- self.alpha * const.elementary_charge * self.z / const.Boltzmann / self.T * x0) - 1)) - x2# eta_hop = f(eta_fil) f2 = x1 - x0 + x2 - x3 f3 = -V_app + ((self.C * 3 * sqrt(2 * m_eff * ((4+x3/2)*const.elementary_charge)) / 2 / x * (const.elementary_charge / const.Planck)**2 * \ exp(- 4 * const.pi * x / const.Planck * sqrt(2 * m_eff * ((4+x3/2)*const.elementary_charge))) * self.A_fil*x3) + (self.j_0et*self.A_fil*(exp(-self.alpha*const.elementary_charge*self.z*x0/const.Boltzmann/self.T) - 1))) * (self.R_el + self.R_S + self.rho_fil*(self.L - x) / self.A_fil) \ + x3 eta_fil, eta_ac, eta_hop, V_tunnel = nsolve((f0, f1, f2, f3), [x0, x1, x2, x3], apprx) eta_fil = np.real(np.complex128(eta_fil)) eta_ac = np.real(np.complex128(eta_ac)) eta_hop = np.real(np.complex128(eta_hop)) V_tunnel = np.real(np.complex128(V_tunnel)) current = ((self.C * 3 * sqrt(2 * m_eff * ((4+V_tunnel)*const.elementary_charge)) / 2 / x * (const.elementary_charge / const.Planck)**2 * \ exp(- 4 * const.pi * x / const.Planck * sqrt(2 * m_eff * ((4+V_tunnel)*const.elementary_charge))) * self.A_fil*V_tunnel) + (self.j_0et*self.A_fil*(exp(-self.alpha*const.elementary_charge*self.z*eta_fil/const.Boltzmann/self.T) - 1))) print(eta_fil, eta_ac, eta_hop, V_tunnel) # print(eta_ac - eta_fil + eta_hop - V_tunnel) return eta_fil, eta_ac, eta_hop, V_tunnel, current
def exact_put_option_price(S, K, T, r, sigma): #S: spot price #K: strike price #T: time to maturity #r: interest rate #sigma: volatility of underlying asset N = systats.Normal(0.0, 1.0) d1 = (sy.ln(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sy.sqrt(T)) d2 = (sy.ln(S / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sy.sqrt(T)) put_price = K * sy.exp(-r * T) * N.cdf(-d2) - S * N.cdf(-d1) return put_price
def exact_euro_put_div(S, K, T, r, q, sigma): # S: spot price # K: strike price # T: time to maturity # r: interest rate # q: rate of continuous dividend paying asset # sigma: volatility of underlying asset N = systats.Normal(0.0, 1.0) d1 = (sy.ln(S / K) + (r - q + 0.5 * sigma ** 2) * T) / (sigma * sy.sqrt(T)) d2 = (sy.ln(S / K) + (r - q - 0.5 * sigma ** 2) * T) / (sigma * sy.sqrt(T)) put = K * sy.exp(-r * T) * N.cdf(-d2) - S * sy.exp(-q * T) * N.cdf(-d1) return put
def getJeffreysPrior(rv): """ Uses SymPy to determine the Jeffreys prior of a random variable analytically. Args: rv: SymPy RandomSymbol, corresponding to a probability distribution Returns: list: List containing Jeffreys prior in symbolic form and corresponding lambda function Example: rate = Symbol('rate', positive=True) rv = stats.Exponential('exponential', rate) print getJeffreysPrior(rv) >>> (1/rate, <function <lambda> at 0x0000000007F79AC8>) """ # get support of random variable support = rv._sorted_args[0].distribution.set # get list of free parameters parameters = list(rv._sorted_args[0].distribution.free_symbols) x = abc.x # symbolic probability density function symPDF = density(rv)(x) # compute Fisher information matrix dim = len(parameters) G = Matrix.zeros(dim, dim) func = summation if support.is_iterable else integrate for i in range(0, dim): for j in range(0, dim): G[i, j] = func(simplify(symPDF * diff(ln(symPDF), parameters[i]) * diff(ln(symPDF), parameters[j])), (x, support.inf, support.sup)) # symbolic Jeffreys prior symJeff = simplify(sqrt(G.det())) # return symbolic Jeffreys prior and corresponding lambda function return symJeff, lambdify(parameters, symJeff, 'numpy')
def get_functions(var): # Denne generator laver alle spørgsmålene. yield exp(a*var) yield ln(a*var) yield a*(var**4) yield a/(var**4) yield sqrt(1+(var**4)) yield (1+var)**a yield exp(a*var**2)
def euro_vanilla_exact(S, K, T, r, sigma, option="call"): # S: spot price # K: strike price # T: time to maturity # r: interest rate # sigma: volatility of underlying asset N = systats.Normal(0.0, 1.0) d1 = (sy.ln(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sy.sqrt(T)) d2 = (sy.ln(S / K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sy.sqrt(T)) if option == "call": result = S * N.cdf(d1) - K * sy.exp(-r * T) * N.cdf(d2) if option == "put": result = K * sy.exp(-r * T) * N.cdf(-d2) - S * N.cdf(-d1) return result
def test_ansi_math1_codegen(): # not included: log10 from sympy import acos, asin, atan, ceiling, cos, cosh, floor, log, ln, sin, sinh, sqrt, tan, tanh, N, Abs x = symbols("x") name_expr = [ ("test_fabs", Abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_ceil", ceiling(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_floor", floor(x)), ("test_log", log(x)), ("test_ln", ln(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] result = codegen(name_expr, "C", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' "double test_fabs(double x) {\n return fabs(x);\n}\n" "double test_acos(double x) {\n return acos(x);\n}\n" "double test_asin(double x) {\n return asin(x);\n}\n" "double test_atan(double x) {\n return atan(x);\n}\n" "double test_ceil(double x) {\n return ceil(x);\n}\n" "double test_cos(double x) {\n return cos(x);\n}\n" "double test_cosh(double x) {\n return cosh(x);\n}\n" "double test_floor(double x) {\n return floor(x);\n}\n" "double test_log(double x) {\n return log(x);\n}\n" "double test_ln(double x) {\n return log(x);\n}\n" "double test_sin(double x) {\n return sin(x);\n}\n" "double test_sinh(double x) {\n return sinh(x);\n}\n" "double test_sqrt(double x) {\n return sqrt(x);\n}\n" "double test_tan(double x) {\n return tan(x);\n}\n" "double test_tanh(double x) {\n return tanh(x);\n}\n" ) assert result[1][0] == "file.h" assert result[1][1] == ( "#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n" "double test_fabs(double x);\ndouble test_acos(double x);\n" "double test_asin(double x);\ndouble test_atan(double x);\n" "double test_ceil(double x);\ndouble test_cos(double x);\n" "double test_cosh(double x);\ndouble test_floor(double x);\n" "double test_log(double x);\ndouble test_ln(double x);\n" "double test_sin(double x);\ndouble test_sinh(double x);\n" "double test_sqrt(double x);\ndouble test_tan(double x);\n" "double test_tanh(double x);\n#endif\n" )
def test_ansi_math1_codegen(): # not included: log10 from sympy import (acos, asin, atan, ceiling, cos, cosh, floor, log, ln, sin, sinh, sqrt, tan, tanh, Abs) x = symbols('x') name_expr = [ ("test_fabs", Abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_ceil", ceiling(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_floor", floor(x)), ("test_log", log(x)), ("test_ln", ln(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] result = codegen(name_expr, "C89", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' 'double test_fabs(double x) {\n double test_fabs_result;\n test_fabs_result = fabs(x);\n return test_fabs_result;\n}\n' 'double test_acos(double x) {\n double test_acos_result;\n test_acos_result = acos(x);\n return test_acos_result;\n}\n' 'double test_asin(double x) {\n double test_asin_result;\n test_asin_result = asin(x);\n return test_asin_result;\n}\n' 'double test_atan(double x) {\n double test_atan_result;\n test_atan_result = atan(x);\n return test_atan_result;\n}\n' 'double test_ceil(double x) {\n double test_ceil_result;\n test_ceil_result = ceil(x);\n return test_ceil_result;\n}\n' 'double test_cos(double x) {\n double test_cos_result;\n test_cos_result = cos(x);\n return test_cos_result;\n}\n' 'double test_cosh(double x) {\n double test_cosh_result;\n test_cosh_result = cosh(x);\n return test_cosh_result;\n}\n' 'double test_floor(double x) {\n double test_floor_result;\n test_floor_result = floor(x);\n return test_floor_result;\n}\n' 'double test_log(double x) {\n double test_log_result;\n test_log_result = log(x);\n return test_log_result;\n}\n' 'double test_ln(double x) {\n double test_ln_result;\n test_ln_result = log(x);\n return test_ln_result;\n}\n' 'double test_sin(double x) {\n double test_sin_result;\n test_sin_result = sin(x);\n return test_sin_result;\n}\n' 'double test_sinh(double x) {\n double test_sinh_result;\n test_sinh_result = sinh(x);\n return test_sinh_result;\n}\n' 'double test_sqrt(double x) {\n double test_sqrt_result;\n test_sqrt_result = sqrt(x);\n return test_sqrt_result;\n}\n' 'double test_tan(double x) {\n double test_tan_result;\n test_tan_result = tan(x);\n return test_tan_result;\n}\n' 'double test_tanh(double x) {\n double test_tanh_result;\n test_tanh_result = tanh(x);\n return test_tanh_result;\n}\n' ) assert result[1][0] == "file.h" assert result[1][1] == ( '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' 'double test_fabs(double x);\ndouble test_acos(double x);\n' 'double test_asin(double x);\ndouble test_atan(double x);\n' 'double test_ceil(double x);\ndouble test_cos(double x);\n' 'double test_cosh(double x);\ndouble test_floor(double x);\n' 'double test_log(double x);\ndouble test_ln(double x);\n' 'double test_sin(double x);\ndouble test_sinh(double x);\n' 'double test_sqrt(double x);\ndouble test_tan(double x);\n' 'double test_tanh(double x);\n#endif\n' )
def natural_logarithm_sym(target, X, A1='', A2='', A3='', A4='', A5=''): r""" Calculates the rate, as well as slope and intercept of the following function at the given value of *x*: .. math:: rate = A_{1} Ln( A_{2} x^{ A_{3} }+ A_{4})+ A_{5} Parameters ---------- A1 -> A5 : string The dictionary keys on the target object containing the coefficients values to be used in the source term model X : string or float/int or array/list The dictionary key on the target objecxt containing the the quantity of interest Returns ------- A dictionary containing the following three items: **'rate'** - The value of the source term function at the given X. **'S1'** - The slope of the source term function at the given X. **'S2'** - The intercept of the source term function at the given X. The slope and intercept provide a linearized source term equation about the current value of X as follow: .. math:: rate = S_{1} X + S_{2} """ A = _parse_args(target=target, key=A1, default=1.0) B = _parse_args(target=target, key=A2, default=1.0) C = _parse_args(target=target, key=A3, default=1.0) D = _parse_args(target=target, key=A4, default=1.0) E = _parse_args(target=target, key=A5, default=0.0) X = target[X] # Symbols used in symbolic function a, b, c, d, e, x = _syp.symbols('a,b,c,d,e,x') # Equation y = a*_syp.ln(b*x**c + d) + e # Callable functions r, s1, s2 = _build_func(eq=y, a=a, b=b, c=c, d=d, e=e, x=x) # Values r_val = r(A, B, C, D, E, X) s1_val = s1(A, B, C, D, E, X) s2_val = s2(A, B, C, D, E, X) values = {'S1': s1_val, 'S2': s2_val, 'rate': r_val} return values
def test_order_at_infinity(): assert Order(1 + x, (x, oo)) == Order(x, (x, oo)) assert Order(3*x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo))*3 == Order(x, (x, oo)) assert -28*Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(Order(x, (x, oo)), (x, oo)) == Order(x, (x, oo)) assert Order(Order(x, (x, oo)), (y, oo)) == Order(x, (x, oo), (y, oo)) assert Order(3, (x, oo)) == Order(1, (x, oo)) assert Order(x**2 + x + y, (x, oo)) == O(x**2, (x, oo)) assert Order(x**2 + x + y, (y, oo)) == O(y, (y, oo)) assert Order(2*x, (x, oo))*x == Order(x**2, (x, oo)) assert Order(2*x, (x, oo))/x == Order(1, (x, oo)) assert Order(2*x, (x, oo))*x*exp(1/x) == Order(x**2*exp(1/x), (x, oo)) assert Order(2*x, (x, oo))*x*exp(1/x)/ln(x)**3 == Order(x**2*exp(1/x)*ln(x)**-3, (x, oo)) assert Order(x, (x, oo)) + 1/x == 1/x + Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + 1 == 1 + Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + x == x + Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + x**2 == x**2 + Order(x, (x, oo)) assert Order(1/x, (x, oo)) + 1/x**2 == 1/x**2 + Order(1/x, (x, oo)) == Order(1/x, (x, oo)) assert Order(x, (x, oo)) + exp(1/x) == exp(1/x) + Order(x, (x, oo)) assert Order(x, (x, oo))**2 == Order(x**2, (x, oo)) assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo)) assert Order(x, (x, oo)) + Order(x**-2, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + Order(1/x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) - Order(x, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + Order(1, (x, oo)) == Order(x, (x, oo)) assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo)) assert Order(1/x, (x, oo)) + Order(1, (x, oo)) == Order(1, (x, oo)) assert Order(x, (x, oo)) + Order(exp(1/x), (x, oo)) == Order(x, (x, oo)) assert Order(x**3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(x**3, (x, oo)) assert Order(x**-3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(exp(2/x), (x, oo)) # issue 7207 assert Order(exp(x), (x, oo)).expr == Order(2*exp(x), (x, oo)).expr == exp(x) assert Order(y**x, (x, oo)).expr == Order(2*y**x, (x, oo)).expr == exp(log(y)*x)
def test_order_at_infinity(): assert Order(1 + x, x, oo) == Order(x, x, oo) assert Order(3*x, x, oo) == Order(x, x, oo) assert Order(x, x, oo)*3 == Order(x, x, oo) assert -28*Order(x, x, oo) == Order(x, x, oo) assert Order(Order(x, x, oo)) == Order(x, x, oo) assert Order(Order(x, x, oo), y) == Order(Order(x, x, oo), x, y) assert Order(3, x, oo) == Order(1, x, oo) assert Order(x**2 + x + y, x, oo) == O(x**2, x, oo) assert Order(x**2 + x + y, y, oo) == O(y, y, oo) assert Order(2*x, x, oo)*x == Order(x**2, x, oo) assert Order(2*x, x, oo)/x == Order(1, x, oo) assert Order(2*x, x, oo)*x*exp(1/x) == Order(x**2*exp(1/x), x, oo) assert Order(2*x, x, oo)*x*exp(1/x)/ln(x)**3 == Order(x**2*exp(1/x)*ln(x)**-3, x, oo) assert Order(x, x, oo) + 1/x == 1/x + Order(x, x, oo) == Order(x, x, oo) assert Order(x, x, oo) + 1 == 1 + Order(x, x, oo) == Order(x, x, oo) assert Order(x, x, oo) + x == x + Order(x, x, oo) == Order(x, x, oo) assert Order(x, x, oo) + x**2 == x**2 + Order(x, x, oo) assert Order(1/x, x, oo) + 1/x**2 == 1/x**2 + Order(1/x, x, oo) == Order(1/x, x, oo) assert Order(x, x, oo) + exp(1/x) == exp(1/x) + Order(x, x, oo) assert Order(x, x, oo)**2 == Order(x**2, x, oo) assert Order(x**3, x, oo)**-2 == Order(x**-6, x, oo) assert Order(x, x, oo) + Order(x**2, x, oo) == Order(x**2, x, oo) assert Order(x, x, oo) + Order(x**-2, x, oo) == Order(x, x, oo) assert Order(x, x, oo) + Order(1/x, x, oo) == Order(x, x, oo) assert Order(x, x, oo) - Order(x, x, oo) == Order(x, x, oo) assert Order(x, x, oo) + Order(1, x, oo) == Order(x, x, oo) assert Order(x, x, oo) + Order(x**2, x, oo) == Order(x**2, x, oo) assert Order(1/x, x, oo) + Order(1, x, oo) == Order(1, x, oo) assert Order(x, x, oo) + Order(exp(1/x), x, oo) == Order(x, x, oo) assert Order(x**3, x, oo) + Order(exp(2/x), x, oo) == Order(x**3, x, oo) assert Order(x**-3, x, oo) + Order(exp(2/x), x, oo) == Order(exp(2/x), x, oo)
def test_get_cb_from_rel__1(): from sympy import symbols, Function, ln x, y = symbols("x,y") f = symbols("f", cls=Function)(x, y) relation = ln(x * y + f) - f subsd = {x: 2, y: 1} subs_fs = frozenset(subsd.items()) # Hashable varied = f initial_guess = 1.0 cb = get_cb_from_rel(relation, subs_fs, f) assert cb(1.14619322062) < 1e-12 cb_numexpr = get_cb_from_rel(relation, subs_fs, f, use_numexpr=True) assert cb_numexpr(1.14619322062) < 1e-12 cb_autowrap = get_cb_from_rel(relation, subs_fs, f, (), bincompile=True, unitless=True) assert cb_autowrap(1.14619322062) < 1e-12
def print_Log(self, rule): with self.new_step(): if rule.base == sympy.E: self.append("The derivative of {} is {}.".format( self.format_math(rule.context), self.format_math(diff(rule)) )) else: # This case shouldn't come up often, seeing as SymPy # automatically applies the change-of-base identity self.append("The derivative of {} is {}.".format( self.format_math(sympy.log(rule.symbol, rule.base, evaluate=False)), self.format_math(1/(rule.arg * sympy.ln(rule.base))))) self.append("So {}".format( self.format_math(sympy.Eq( sympy.Derivative(rule.context, rule.symbol), diff(rule)))))
def test_solve_relation_num(use_numexpr=False, bincompile=False): from sympy import symbols, Function, ln x, y = symbols("x,y") f = symbols("f", cls=Function)(x, y) relation = ln(x * y + f) - f subsd = {x: 2, y: 1} varied = f initial_guess = 1.0 unitless = True x, y = solve_relation_num( relation, subsd, varied, initial_guess, (), use_numexpr, unitless, bincompile, verbose=True, yabstol=1e-9 ) assert abs(x - 1.14619322062) < 1e-8 x, y = symbols("x,y") g = symbols("g", cls=Function)(x, y) relation = x ** 2 + y ** 2 - g # Circle g_val, delta_rel = solve_relation_num(relation, {x: 1, y: 0}, g, 0.1, (), use_numexpr, verbose=True, abstol=1e-8) assert abs(g_val - 1) < 1e-7
def JeffreysPrior(LikeRV,low,high,param): """ Procedure Name: JeffreysPrior Purpose: Derive a Jeffreys Prior for a likelihood function Arguments: 1. LikeRV: The likelihood function (a random variable) 2. low: the lower support 3. high: the upper support 4. param: the unknown parameter Output: 1. JeffRV: the Jeffreys Prior distribution """ # If the likelihood function is continuous, compute the Jeffreys # Prior if LikeRV.ftype[0]=='continuous': likelihood=LikeRV.func[0] loglike=ln(likelihood) logdiff=diff(loglike,param) jefffunc=sqrt(integrate(likelihood*logdiff**2, (x,LikeRV.support[0], LikeRV.support[1]))) jefffunc=simplify(jefffunc) jefffunc=jefffunc.subs(param,x) JeffRV=RV([jefffunc],[low,high],LikeRV.ftype) return JeffRV
def Elogp(self, p, to_full_expr=False): """ Calculates the expectation of log p w.r.t to this distribution where p is also a distribution Args: p - An MVG object to_full_expr - Set to True to indicate that you want to use the full expression for the mean and covariance of this MVG Returns: res - The calculation of this expression """ a, A = self.mean, self.covar b, B = p.mean, p.covar if to_full_expr: a = utils.expand_to_fullexpr(a) A = utils.expand_to_fullexpr(A) b = utils.expand_to_fullexpr(b) B = utils.expand_to_fullexpr(B) return -Rational(1, 2) * (ln(Determinant(2 * pi * B)) + Trace(B.I * A) + (a - b).T * B.I * (a - b))
def _ln(self): """Returns the natural logarithm of the quaternion (_ln(q)). Example ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q._ln() log(sqrt(30)) + 2*sqrt(29)*acos(sqrt(30)/30)/29*i + 3*sqrt(29)*acos(sqrt(30)/30)/29*j + 4*sqrt(29)*acos(sqrt(30)/30)/29*k """ # _ln(q) = _ln||q|| + v/||v||*arccos(a/||q||) q = self vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) q_norm = q.norm() a = ln(q_norm) b = q.b * acos(q.a / q_norm) / vector_norm c = q.c * acos(q.a / q_norm) / vector_norm d = q.d * acos(q.a / q_norm) / vector_norm return Quaternion(a, b, c, d)
def qLogDifferentiation_template(): '''Differeniate log(e) e.g. diff ln(5*x+2)''' first_val = randint(-100,100) while first_val == 0: first_val = randint(-100,100) second_val = randint(-100,100) if second_val < 0: question = 'Differentiate ' + tostring(am.parse('ln((%sx%s))' % (first_val, second_val))) else: question = 'Differentiate ' + tostring(am.parse('ln((%sx+%s))' % (first_val, second_val))) question += ' with respect to ' + tostring(am.parse('x')) steps = [] diff_inside = diff(first_val*x+second_val) if second_val < 0: steps.append('Differentiate %s normally' % tostring(am.parse('%sx%s' % (first_val, second_val)))) else: steps.append('Differentiate %s normally' % tostring(am.parse('%sx+%s' % (first_val, second_val)))) steps.append('This will give %s which goes as numerator' % str(diff_inside)) if second_val < 0: steps.append('%s goes as denominator' % tostring(am.parse('%sx%s' % (first_val, second_val)))) else: steps.append('%s goes as denominator' % tostring(am.parse('%sx+%s' % (first_val, second_val)))) answer = [] answer.append(steps) answer.append(tostring(am.parse(str(diff(ln(first_val*x+second_val)))))) return question, answer
import sympy as sy x = sy.symbols('x') sy.init_printing(use_unicode=False) # Peak of distribution # peak = 3 # c = b^2/4a + ln(-a/pi)/2 b = 0 d = sy.sqrt(1 / (72 * sy.pi)) c = sy.ln(d) # (peak/d) sets the peak y = (sy.exp((-((x - 36)**2) / 72) + b * x + c)) # *(peak/d) #sy.plot(y,(x,0,100)) sy.pprint(y) # print(y.subs(x,0).evalf(20))
def test_simple_2(): assert Order(2 * x) * x == Order(x**2) assert Order(2 * x) / x == Order(1, x) assert Order(2 * x) * x * exp(1 / x) == Order(x**2 * exp(1 / x)) assert (Order(2 * x) * x * exp(1 / x) / ln(x)**3).expr == x**2 * exp(1 / x) * ln(x)**-3
import numpy as np import sympy as sp import matplotlib.pyplot as plt DEBUG = True error = 0.01 x, y = sp.symbols('x y') expression = sp.cos(sp.cos(x / 2)) * sp.ln(x - 1) function = sp.lambdify(x, expression, 'numpy') range = np.linspace(1.1, 4) plt.plot(range, function(range)) plt.plot(range, np.zeros_like(range)) plt.show() a = 1.5 b = 3 def check_range(function, a, b): return function(a) * function(b) < 0 print(f'Is range correct? : {check_range(function, a, b)}') def chord_method(function, a, b, expression, error): temp_a = a temp_b = b
def test_mul_1(): assert (x*ln(2 + x)).nseries(x, n=5) == x*log(2) + x**2/2 - x**3/8 + \ x**4/24 + O(x**5) assert (x * ln(1 + x)).nseries(x, n=5) == x**2 - x**3 / 2 + x**4 / 3 + O(x**5)
""" Notes: if some expressions do not simplify why they should they might have 'duplicates'. remove them by using remove_duplicates """ import numpy as np import sympy.physics.optics as so import sympy sympy.init_printing(use_unicode=True, use_latex=True, pretty_printing=True) from sympy import Symbol RMS_TO_FWHM = 2 * sympy.sqrt(2 * sympy.ln(2)) def gaussian_transmission_1D(sig, slit_opening): return sympy.erf(sympy.sqrt(2) * slit_opening / (4 * sig)) def gaussian_transmission_2D(sig, pinhole_diameter): return 1 - sympy.exp(-pinhole_diameter**2 / (8 * sig**2)) def get_symbol(expr, name): symbols = list(expr.free_symbols) match = [s for s in symbols if s.name == name] if len(match) == 0: return None if len(match) > 1: raise ValueError(expr, "has multiple parameters with the same name!") else: return match[0]
rms_test_error( model2_daylight_predictions(raw_test_data, m2_u_opt, m2_v_opt), daylight_durations(raw_test_data)) / 60)) #### Bayesian modeling ## Laplace approximation import utils.scipy_bayes as scp_bayes sigma, x_1 = sy.symbols('sigma x_1') u_bounds = (0, 1) sigma_bounds = (1e-4, 1) lp1_n = -sy.ln(sigma) - 0.5 * np.log(2 * np.pi) - (( (t_n - u * x_1) / sigma)**2) / 2 lp1_theta = np.log(1 / (u_bounds[1] - u_bounds[0])) + sy.ln( 1 / sigma) - np.log(np.log(sigma_bounds[1]) - np.log(sigma_bounds[0])) # ln(sigma) has a uniform prior on some interval def find_model1_map(raw_data): mat = model1_design_matrix(raw_data) t = mat[:, -1] x_1s = np.cos(psi_sf) * mat[:, 0] + np.sin(psi_sf) * mat[:, 1] return scp_bayes.find_map(lp1_theta, lp1_n, [t_n, x_1], [u, sigma], [t, x_1s], [0.0, 0.1], (u_bounds, sigma_bounds))
def test_power_x_x1(): assert (exp(x*ln(x))).nseries(x, 0, 4) == \ 1+x*log(x)+x**2*log(x)**2/2+x**3*log(x)**3/6 + O(x**4*log(x)**4)
import matplotlib.pyplot as plt from ExtraLibraries.Writer import Writer as Writer #********************************************************************************* # Initializing Symbols pi = sp.pi x , y = sp.symbols('x y') #********************************************************************************* # Initial Values Entered By User : (Hard Codded) f = (sp.sin(10*sp.pi*x)/(2*x)) + (x-1)**4 # change this function based on our own demand. lowerBoundry = 0.5 upperBoundry = 2.5 steps = 10**-4 plotSteps = 5 * 10**-3 numberOfSamples = int(sp.Abs(upperBoundry - lowerBoundry) * 20) g = x**4 + 2*x**5 + 3*x + 2 h = (sp.sin(2*x)/x) * (sp.cos(x**(sp.exp(1))) * sp.pi * sp.ln(2*x)) #********************************************************************************* #*********************** Methods Implementation ********************************** #********************************************************************************* def calculateDifferenciation(f,order): # calculates the nth-order derivation of a function derivatedFunction = f for i in range(0,order): derivatedFunction = sp.diff(derivatedFunction) return derivatedFunction ############################################################################### def getRandom( lowerBound , upperBound ): #returns a random number between the wanted boundries value = random() scaledValue = lowerBound + (value * (upperBound - lowerBound)) return scaledValue
[1990.0, 5281653820.0], [2000.0, 6079603571.0]]) def fill(i, j, t): if j == 0: return 1.0 if j == 1: return pop[i][t] if j == 2: return pop[i][t]**2 return pop[i][t]**3 # Line A = Matrix(4, 2, lambda i, j: fill(i, j, 0)) b = Matrix(4, 1, [ln(p[1]) for p in pop]) b = A.transpose() * b A = A.transpose() * A exp = A.LUsolve(b) t = symbols('t', real=True) f = E**exp[0, 0] * E**(exp[1, 0] * t) est = f.subs(t, 1980) actual = 4452584592 print("Funksjon:", f) print("1980: Estimert:", est, "Feil:", abs(est - actual))
def test_mul_1(): assert (x*ln(2+x)).nseries(x, 0, 4) == x*log(2)+x**2/2-x**3/8+x**4/24+ \ O(x**5) assert (x*ln(1+x)).nseries(x, 0, 4) == x**2- x**3/2 + x**4/3 + O(x**5)
from math import pi from sympy import symbols, cos, acos, sqrt, ln from sympy.plotting import plot, PlotGrid import sympy.plotting from sympy.physics.units import speed_of_light as c S = 1 / sqrt(2) # Numero de Courant definido para o problema N = symbols('N') # Variavel livre do plot (resolução de amostragem do grid) Csi = 1 + ((1 / S)**2) * (cos(2 * pi * S / N) - 1) # Eq 2.29b trans = 2 * pi * S / acos(1 - 2 * S**2) # Eq 2.30 # Calculo + plot da velocidade de fase normalizada p1 = plot( (2 * pi / N / acos(Csi), (N, trans, 10)), # eq 2.32 (normalizada) (2 / N, (N, 1, trans)), # eq 2.37a (normalizada) ylabel='vp/c (normalizada)', show=False) # Calculo + plot da constante de atenuação p2 = plot((-ln(-Csi - sqrt(Csi**2 - 1)), (N, 1, trans)), ylim=(0, 6), xlim=(1, 10), line_color='red', ylabel='αΔx (Np/célula do grid)', show=False) PlotGrid(1, 2, p1, p2) # Plotar os dois na mesma janela
def frank(): t, d = sy.symbols('t, d') A = sy.exp(-d * t) - 1 B = sy.exp(-d) - 1 G = -sy.ln(A / B) return G, [t, d]
def eval_exp(base, exp, integrand, symbol): return integrand / sympy.ln(base)
def test_intrinsic_math_codegen(): # not included: log10 from sympy import (acos, asin, atan, ceiling, cos, cosh, floor, log, ln, sin, sinh, sqrt, tan, tanh, Abs) x = symbols('x') name_expr = [ ("test_abs", Abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), # ("test_ceil", ceiling(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), # ("test_floor", floor(x)), ("test_log", log(x)), ("test_ln", ln(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] result = codegen(name_expr, "F95", "file", header=False, empty=False) assert result[0][0] == "file.f90" expected = ('REAL*8 function test_abs(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_abs = Abs(x)\n' 'end function\n' 'REAL*8 function test_acos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_acos = acos(x)\n' 'end function\n' 'REAL*8 function test_asin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_asin = asin(x)\n' 'end function\n' 'REAL*8 function test_atan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_atan = atan(x)\n' 'end function\n' 'REAL*8 function test_cos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_cos = cos(x)\n' 'end function\n' 'REAL*8 function test_cosh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_cosh = cosh(x)\n' 'end function\n' 'REAL*8 function test_log(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_log = log(x)\n' 'end function\n' 'REAL*8 function test_ln(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_ln = log(x)\n' 'end function\n' 'REAL*8 function test_sin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_sin = sin(x)\n' 'end function\n' 'REAL*8 function test_sinh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_sinh = sinh(x)\n' 'end function\n' 'REAL*8 function test_sqrt(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_sqrt = sqrt(x)\n' 'end function\n' 'REAL*8 function test_tan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_tan = tan(x)\n' 'end function\n' 'REAL*8 function test_tanh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_tanh = tanh(x)\n' 'end function\n') assert result[0][1] == expected assert result[1][0] == "file.h" expected = ('interface\n' 'REAL*8 function test_abs(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_acos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_asin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_atan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_cos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_cosh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_log(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_ln(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_sin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_sinh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_sqrt(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_tan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_tanh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n') assert result[1][1] == expected
airy = AiryDisk2D(radius=3)(x, y) figure() plt.loglog(Ns, [psf_to_sigma(g3, N, 0, 0) for N in Ns]) plt.loglog(Ns, [psf_to_sigma(g15, N, 0, 0) for N in Ns]) plt.loglog(Ns, [psf_to_sigma(airy, N, 0, 0) for N in Ns]) plt.loglog(Ns, [psf_to_sigma(img, N, 0, 0) for N in Ns]) # %% from sympy import Function, Sum, symbols, ln, Eq from sympy.abc import N, i η, ζ = symbols('ζ,η') P = Function('P')(ζ, η) l = Sum(ln(P), (i, 1, N)) l # %% l.diff(η, 2).simplify() # %% (l.diff(η, 1) ** 2).simplify() # %% from astropy.modeling.functional_models import Gaussian1D # %% def fisher(pdf_grid, dx): normed = pdf_grid / np.trapz(pdf_grid, dx=dx)
def process(self): _kwargs = self.inputs['x'].to_dict() outSym = sp.ln(self.inputs['x'].expression) self.outputs['f(x)'] = QuSym(outSym, **_kwargs) return super().process()
def test_issue_9116(): n = Symbol('n', positive=True, integer=True) assert ln(n).is_nonnegative is True assert log(n).is_nonnegative is True
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import math as mth import sympy as sp import matplotlib.pyplot as plt x, y = sp.symbols('x y') A = x ** 2 * sp.ln(x) func = sp.lambdify(x, A) a_S = 1 b_S = 2 diff_A = 2*x**3*y**3-2*x*y #diff_A = x * y ** 2 + y diff_func = sp.lambdify((x, y), diff_A) diff_aS = 0 diff_bS = 1 y0 = 1 x0 = 0 def trapez(func, a, b, n): h = (b - a) / n return h * sum([(func(a + h * i) + func(a + h * (i + 1))) / 2 for i in range(n)]) def simpson(func, a, b, n): h = (b - a) / n
def secant_method_q6(x, x2): return x - ((((x - 2)**2 - ln(x)) * (x - x2)) / (((x - 2)**2 - ln(x)) - ((x2 - 2)**2 - ln(x2))))
super().__init__(f, h, [4 / 6, -4 / 6, -1 / 12, 1 / 12]) self.args = [1, -1, 2, -2] class DerivativeNum5(Derivative): def __init__(self, f, h): super().__init__(f, h, [3 / 4, -3 / 4, -3 / 20, 3 / 20, 1 / 60, -1 / 60]) self.args = [1, -1, 2, -2, 3, -3] if __name__ == '__main__': xSym = smp.Symbol('x') functionsSym = [ smp.sin(xSym ** 2), smp.cos(smp.sin(xSym)), smp.exp(smp.cos(smp.sin(xSym))), smp.ln(xSym + 3), smp.sqrt(xSym + 3) ] functions = [smp.lambdify(xSym, f) for f in functionsSym] x0 = 5 derivativesAnalyticalSym = [smp.diff(f, xSym) for f in functionsSym] # Анализ сходимости формул численного дифф. derivativesAnalytical = [smp.lambdify(xSym, f) \ for f in derivativesAnalyticalSym] derivativesNumerical = [ DerivativeNum1,
) print(f' {"-"*54}\n') return p # funciton call examples if __name__ == "__main__": # setting the question x = sp.Symbol('x') q = 'b' if q == 'a': p = [[1.1, 9.025013], [1.2, 11.02318], [1.3, 13.46374], [1.4, 16.44465]] fx = sp.exp(2 * x) if q == 'b': p = [[7.4, -68.3193], [7.6, -71.6982], [7.8, -75.1576], [8.0, -78.6974]] fx = sp.ln(x + 2) - (x + 1)**2 if q == 'c': p = [[-3 / 10, -0.27652], [-2 / 10, -0.25074], [-1 / 10, -0.16134], [0, 0]] fx = sp.exp(2 * x) - sp.cos(2 * x) p = three_point_differentiation(p) p = three_point_error(p, fx)
def ln(obj): '''ln对数计算 【参数说明】 obj:对谁求ln对数,obj可以是以下数据类型: ①int或float;②Num;③NumItem;④LSym;⑤LSymItem;⑥Const;⑦Measure或Uncertainty。 【返回值】 根据obj的数据类型,返回值的数据类型如下: ①int、float → float; ②Num → Num; ③NumItem → NumItem; ④LSym → LSym; ⑤LSymItem → LSymItem; ⑥Const → Const; ⑦Measure、Uncertainty → Uncertainty。''' if type(obj) == int or type(obj) == float: return math.log(obj) objType = str(type(obj)) if objType == "<class 'analyticlab.num.Num'>": obj._Num__resetDigit() n = obj._Num__newInstance() n._Num__value = math.log(obj._Num__value) #数值的有效数字位数为相应指数的小数点后位数 n._Num__d_behind = obj._Num__d_valid n._Num__d_front = nf.getDigitFront(abs(n._Num__value)) n._Num__d_valid = n._Num__d_front + n._Num__d_behind return n elif objType == "<class 'analyticlab.numitem.NumItem'>": return obj._NumItem__newInstance([ln(n) for n in obj._NumItem__arr]) elif objType == "<class 'analyticlab.lsym.LSym'>": ### 括号与文本预处理 ### o_symBrac = obj._LSym__symBrac o_symText = obj._LSym__symText o_calBrac = obj._LSym__calBrac o_calText = obj._LSym__calText symText = sNum = calText = symBrac = calBrac = None if 4 >= obj._LSym__symPrior: if obj._LSym__genSym: o_symBrac += 1 o_symText = obj._LSym__bracket(o_symBrac) % o_symText if 4 >= obj._LSym__calPrior: if obj._LSym__genCal: o_calBrac += 1 o_calText = obj._LSym__bracket(o_calBrac) % o_calText ### 合成表达式 ### if obj._LSym__genSym: symText = r'\ln{%s}' % (o_symText) symBrac = o_symBrac if obj._LSym__genCal: sNum = ln(obj._LSym__sNum) calText = r'\ln{%s}' % (o_calText) calBrac = o_calBrac return obj._LSym__newInstance(sNum, symText, calText, symBrac, calBrac, 4, 4, False, obj._LSym__s_decR) elif objType == "<class 'analyticlab.lsymitem.LSymItem'>": new = obj._LSymItem__newInstance() if type(obj._LSymItem__lsyms) == list: new._LSymItem__lsyms = [ln(ni) for ni in obj._LSymItem__lsyms] else: new._LSymItem__lsyms = {} for ki in obj._LSymItem__lsyms.keys(): new._LSymItem__lsyms[ki] = ln(obj._LSymItem__lsyms[ki]) if obj._LSymItem__sepSymCalc: new._LSymItem__sepSym = ln(obj._LSymItem__sepSym) return new elif objType == "<class 'analyticlab.const.Const'>": ### 括号与文本预处理 ### o_symBrac = obj._Const__symBrac o_symText = obj._Const__symText o_calBrac = obj._Const__calBrac o_calText = obj._Const__calText if 4 >= obj._Const__symPrior: o_symBrac += 1 o_symText = obj._Const__bracket(o_symBrac) % o_symText if 4 >= obj._Const__calPrior: o_calBrac += 1 o_calText = obj._Const__bracket(o_calBrac) % o_calText ### 合成表达式 ### symText = r'\ln %s' % o_symText calText = r'\ln %s' % o_calText return obj._Const__newInstance(symText, calText, o_symBrac, o_calBrac, 4, 4, math.log(obj.value()), 1, False, obj._Const__s_decR, False, obj._Const__c_decR) elif objType == "<class 'analyticlab.measure.measure.Measure'>" or objType == "<class 'analyticlab.measure.basemeasure.BaseMeasure'>": return obj._Uncertainty__newInstance( sympy.ln(obj._Uncertainty__symbol), ln(obj._Measure__vl), obj._Uncertainty__measures, obj._Uncertainty__consts, obj._Uncertainty__lsyms, False)
def eval_reciprocal(func, integrand, symbol): return sympy.ln(func)
def test_mul_0(): assert (x * ln(x)).nseries(x, n=5) == x * ln(x)
def getEa0RT(kon, koff, phi): Ea0RT = -(phi * sp.ln(koff) + (1 - phi) * sp.ln(kon)) return Ea0RT
def test_power_x_x1(): assert (exp(x*ln(x))).nseries(x, n=4) == \ 1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)
def getTGfRT(tf): tGfRT = sp.ln(tf) return tGfRT
def getGfRT(kon, koff): GfRT = sp.ln(koff) - sp.ln(kon) return GfRT
def test_intrinsic_math_codegen(): # not included: log10 from sympy import (acos, asin, atan, ceiling, cos, cosh, floor, log, ln, sin, sinh, sqrt, tan, tanh, Abs) x = symbols('x') name_expr = [ ("test_abs", Abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_cos", cos(x)), ("test_cosh", cosh(x)), ("test_log", log(x)), ("test_ln", ln(x)), ("test_sin", sin(x)), ("test_sinh", sinh(x)), ("test_sqrt", sqrt(x)), ("test_tan", tan(x)), ("test_tanh", tanh(x)), ] result = codegen(name_expr, "F95", "file", header=False, empty=False) assert result[0][0] == "file.f90" expected = ( 'REAL*8 function test_abs(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_abs = abs(x)\n' 'end function\n' 'REAL*8 function test_acos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_acos = acos(x)\n' 'end function\n' 'REAL*8 function test_asin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_asin = asin(x)\n' 'end function\n' 'REAL*8 function test_atan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_atan = atan(x)\n' 'end function\n' 'REAL*8 function test_cos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_cos = cos(x)\n' 'end function\n' 'REAL*8 function test_cosh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_cosh = cosh(x)\n' 'end function\n' 'REAL*8 function test_log(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_log = log(x)\n' 'end function\n' 'REAL*8 function test_ln(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_ln = log(x)\n' 'end function\n' 'REAL*8 function test_sin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_sin = sin(x)\n' 'end function\n' 'REAL*8 function test_sinh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_sinh = sinh(x)\n' 'end function\n' 'REAL*8 function test_sqrt(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_sqrt = sqrt(x)\n' 'end function\n' 'REAL*8 function test_tan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_tan = tan(x)\n' 'end function\n' 'REAL*8 function test_tanh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'test_tanh = tanh(x)\n' 'end function\n' ) assert result[0][1] == expected assert result[1][0] == "file.h" expected = ( 'interface\n' 'REAL*8 function test_abs(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_acos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_asin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_atan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_cos(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_cosh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_log(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_ln(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_sin(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_sinh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_sqrt(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_tan(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_tanh(x)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'end function\n' 'end interface\n' ) assert result[1][1] == expected
def eval_log(func, integrand, symbol): return sympy.ln(func)
def test_simple_2(): assert Order(2 * x) * x == Order(x ** 2) assert Order(2 * x) / x == Order(1, x) assert Order(2 * x) * x * exp(1 / x) == Order(x ** 2 * exp(1 / x)) assert (Order(2 * x) * x * exp(1 / x) / ln(x) ** 3).expr == x ** 2 * exp(1 / x) * ln(x) ** -3
def positif(expression, variable=None, strict=False): u"""Retourne l'ensemble sur lequel une expression à variable réelle est positive (resp. strictement positive).""" from .sympy_functions import factor # L'étude du signe se fait dans R, on indique donc à sympy que la variable est réelle. if variable is None: variable = extract_var(expression) if hasattr(expression, "subs"): old_variable = variable variable = Symbol("_tmp", real=True) expression = expression.subs({old_variable: variable}) ens_def = ensemble_definition(expression, variable) try: expression = factor(expression, variable, "R", decomposer_entiers=False) except NotImplementedError: if param.debug: print "Warning: Factorisation impossible de ", expression ## print "T455451", expression, variable if hasattr(expression, "is_Pow") and expression.is_Pow and expression.as_base_exp( )[1].is_rational: base, p = expression.as_base_exp() # Le dénominateur ne doit pas s'annuler : if p < 0: strict = True if p.is_integer and p.is_even: if strict: return ens_def * (R - (positif(base, variable, strict=False) - positif(base, variable, strict=True))) else: return ens_def else: return ens_def * positif(base, variable, strict=strict) if hasattr(expression, "is_Mul") and expression.is_Mul: posit = R posit_nul = R for facteur in expression.args: # pos : ensemble des valeurs pour lequelles l'expression est positive # pos_nul : ensemble des valeurs pour lequelles l'expression est positive ou nulle pos = positif(facteur, variable, strict=True) pos_nul = positif(facteur, variable, strict=False) # posit : les deux sont strictements positifs, ou les deux sont strictements négatifs # posit_nul : les deux sont positifs ou nuls, ou les deux sont négatifs ou nuls posit, posit_nul = (posit * pos + (-posit_nul) * (-pos_nul)) * ens_def, (posit_nul * pos_nul + (-posit) * (-pos)) * ens_def ## print "resultat", facteur, res #### if res is NotImplemented: #### return NotImplemented ## # le résultat est positif si les deux facteurs sont positifs, ou si les deux facteurs sont négatifs: ## resultat = resultat*res + (-resultat)*(-res) if strict: return posit else: return posit_nul if getattr(expression, "is_positive", None) is True: # > 0 return ens_def if getattr(expression, "is_negative", None) is True: # < 0 return vide if getattr(expression, "is_positive", None) is False and strict: # <= 0 return vide if getattr(expression, "is_negative", None) is False and not strict: # >= 0 return ens_def if getattr(expression, "is_zero", None) is True and not strict: # == 0 return ens_def if isinstance(expression, (int, float, long)): if expression > 0 or (expression == 0 and not strict): return ens_def else: return vide # pas besoin de l'ensemble de définition pour les fonctions polynomiales if hasattr(expression, "is_polynomial") and expression.is_polynomial(): P = expression.as_poly(variable) if P.degree() == 1: a, b = P.all_coeffs() if a > 0: return Intervalle(-b / a, +oo, inf_inclus=not strict) else: # a<0 (car a != 0) return Intervalle(-oo, -b / a, sup_inclus=not strict) elif P.degree() == 2: a, b, c = P.all_coeffs() d = b**2 - 4 * a * c if d > 0: x1 = (-b - sqrt(d)) / (2 * a) x2 = (-b + sqrt(d)) / (2 * a) x1, x2 = min(x1, x2), max(x1, x2) if a > 0: return Intervalle(-oo, x1, sup_inclus=not strict) + Intervalle( x2, +oo, inf_inclus=not strict) else: # a<0 (car a != 0) return Intervalle(x1, x2, inf_inclus=not strict, sup_inclus=not strict) elif d == 0: x0 = -b / (2 * a) if a > 0: return Intervalle(-oo, x0, sup_inclus=not strict) + Intervalle( x0, +oo, inf_inclus=not strict) else: return Intervalle(x0, x0, sup_inclus=not strict) else: # d < 0 if a > 0: return R else: return vide # a*f(x)+b > 0 <=> f(x)+b/a > 0 pour a > 0, -f(x) - b/a > 0 pour a < 0 if getattr(expression, "is_Add", False): args = expression.args if len(args) == 2: liste_constantes = [] liste_autres = [] for arg in args: if _is_var(arg, variable): liste_autres.append(arg) else: liste_constantes.append(arg) if len(liste_autres) == 1: partie_constante = Add(*liste_constantes) partie_variable = liste_autres[0] if getattr(partie_variable, "is_Mul", False): liste_facteurs_constants = [] liste_autres_facteurs = [] for facteur in partie_variable.args: if _is_var(facteur, variable): liste_autres_facteurs.append(facteur) else: liste_facteurs_constants.append(facteur) if liste_facteurs_constants: facteur_constant = Mul(*liste_facteurs_constants) autre_facteur = Mul(*liste_autres_facteurs) if _is_pos(facteur_constant): return positif(autre_facteur + partie_constante / facteur_constant, variable, strict=strict) elif _is_neg(facteur_constant): return ens_def * (R - positif( autre_facteur + partie_constante / facteur_constant, variable, strict=not strict)) # Logarithme : if isinstance(expression, ln): return positif(expression.args[0] - 1, variable, strict=strict) # Résolution de ln(X1) + ln(X2) + ... + b > 0, où X1=f1(x), X2 = f2(x) ... if getattr(expression, "is_Add", False): args = expression.args liste_constantes = [] liste_ln = [] # Premier passage : on remplace a*ln(X1) par ln(X1**a) for arg in args: if getattr(arg, "is_Mul", False): liste_constantes = [] liste_ln = [] for facteur in arg.args: if isinstance(facteur, ln) and _is_var(facteur, variable): liste_ln.append(facteur) elif not _is_var(facteur, variable): liste_constantes.append(facteur) ## print facteur, liste_constantes, liste_ln if len(liste_constantes) == len( arg.args) - 1 and len(liste_ln) == 1: expression += ln(liste_ln[0].args[0]** Add(*liste_constantes)) - arg ## print "Resultat 1er passage:", expression # Deuxième passage : ln(X1)+ln(X2)+b>0 <=> X1*X2-exp(-b)>0 for arg in args: if isinstance(arg, ln) and hasattr( arg, "has_any_symbols") and arg.has(variable): liste_ln.append(arg) elif not hasattr(arg, "has_any_symbols") or not arg.has(variable): liste_constantes.append(arg) if liste_ln and len(liste_ln) + len(liste_constantes) == len(args): # ln(X1)+ln(X2)+b>0 <=> X1*X2-exp(-b)>0 contenu_log = Mul(*(logarithme.args[0] for logarithme in liste_ln)) contenu_cst = exp(-Add(*liste_constantes)) return ens_def * positif( contenu_log - contenu_cst, variable, strict=strict) # Exponentielle # Résolution de a*exp(f(x)) + b > 0 if getattr(expression, "is_Add", False): a_ = Wild('a') b_ = Wild('b') X_ = Wild('X') match = expression.match(a_ * exp(X_) + b_) if match is not None: a = match[a_] b = match[b_] X = match[X_] if a != 0 and not a.has(variable) and not b.has(variable): if _is_pos(b): if _is_pos(a): return ens_def elif _is_neg(a): # l'ensemble de définition ne change pas return positif(-X + ln(-b / a), variable, strict=strict) elif _is_neg(b): if _is_pos(a): return positif(X - ln(-b / a), variable, strict=strict) elif _is_neg(a): return vide # Cas très particulier : on utilise le fait que exp(x)>=x+1 sur R if getattr(expression, "is_Add", False): expr = expression changements = False for arg in expr.args: if isinstance(arg, exp): changements = True expr += arg.args[0] + 1 - arg if changements and (ens_def - positif(expr, variable, strict=strict) == vide): return ens_def # Sommes contenant des logarithmes : if getattr(expression, "is_Add", False): # Cas très particulier : on utilise le fait que ln(x)<=x-1 sur ]0;+oo[ expr = expression changements = False for arg in expr.args: if isinstance(arg, ln): changements = True expr += arg.args[0] + 1 - arg if changements: try: ## print "S458475", -expr non_positif = positif(-expr, variable, strict=not strict) # complementaire (ens_def - positif(expr, variable, strict=not strict) == vide) if (ens_def - non_positif == vide): return vide except NotImplementedError: pass # Somme contenant des logarithmes : si aucune autre méthode n'a fonctionné, on tente ln(a)+ln(b)>0 <=> a*b>1 (pour a>0 et b>0) expr = Mul(*(exp(arg) for arg in expression.args)) - 1 try: return ens_def * positif(expr, variable, strict=strict) except NotImplementedError: pass ## print "Changement de variable." # En dernier recours, on tente un changement de variable : tmp2 = Symbol("_tmp2", real=True) # changements de variables courants : x², exp(x), ln(x), sqrt(x), x³ : for X in (variable**2, variable**3, exp(variable), ln(variable), sqrt(variable)): expr = expression.subs(X, tmp2) # Si la nouvelle variable apparait une seule fois, # le changement de variable produirait une récurrence infinie ! if variable not in expr.atoms() and count_syms(expr, X) > 1: ## print "nouvelle variable:", X solution_temp = positif(expr, tmp2, strict=strict) solution = vide for intervalle in solution_temp.intervalles: sol = R a = intervalle.inf b = intervalle.sup if a != -oo: sol *= positif(X - a, variable, strict=strict) if b != oo: sol *= positif(b - X, variable, strict=strict) solution += sol return ens_def * solution raise NotImplementedError