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 test_latex_functions(): assert latex(exp(x)) == "$e^{x}$" assert latex(exp(1) + exp(2)) == "$e + e^{2}$" f = Function("f") assert latex(f(x)) == "$\\operatorname{f}\\left(x\\right)$" beta = Function("beta") assert latex(beta(x)) == r"$\operatorname{beta}\left(x\right)$" assert latex(sin(x)) == r"$\operatorname{sin}\left(x\right)$" assert latex(sin(x), fold_func_brackets=True) == r"$\operatorname{sin}x$" assert latex(sin(2 * x ** 2), fold_func_brackets=True) == r"$\operatorname{sin}2 x^{2}$" assert latex(sin(x ** 2), fold_func_brackets=True) == r"$\operatorname{sin}x^{2}$" assert latex(asin(x) ** 2) == r"$\operatorname{asin}^{2}\left(x\right)$" assert latex(asin(x) ** 2, inv_trig_style="full") == r"$\operatorname{arcsin}^{2}\left(x\right)$" assert latex(asin(x) ** 2, inv_trig_style="power") == r"$\operatorname{sin}^{-1}\left(x\right)^{2}$" assert latex(asin(x ** 2), inv_trig_style="power", fold_func_brackets=True) == r"$\operatorname{sin}^{-1}x^{2}$" assert latex(factorial(k)) == r"$k!$" assert latex(factorial(-k)) == r"$\left(- k\right)!$" assert latex(floor(x)) == r"$\lfloor{x}\rfloor$" assert latex(ceiling(x)) == r"$\lceil{x}\rceil$" assert latex(abs(x)) == r"$\lvert{x}\rvert$" assert latex(re(x)) == r"$\Re{x}$" assert latex(im(x)) == r"$\Im{x}$" assert latex(conjugate(x)) == r"$\overline{x}$" assert latex(gamma(x)) == r"$\operatorname{\Gamma}\left(x\right)$" assert latex(Order(x)) == r"$\operatorname{\mathcal{O}}\left(x\right)$"
def Theta_Equation(self, l="undef", m="undef", theta=theta): """ l - orbital quantum number m - magnetic quantum number """ if l == "undef": l = self.l_val if m == "undef": m = self.m_val # Prevents integer division and float l,m l = int(l) m = int(m) mode = self.select_exec_mode(theta) gL = self.Generalized_Legendre(l, m, theta).subs(theta, sympy.cos(theta)) if gL: rat_part = sympy.sqrt( Rational((2 * l + 1), 2) * Rational(factorial(l - sympy.abs(m)), factorial(l + sympy.abs(m))) ) if mode == "numer": return (rat_part * gL).evalf() elif mode == "analit": return (rat_part * gL).expand() return False
def test_latex_functions(): assert latex(exp(x)) == "$e^{x}$" assert latex(exp(1) + exp(2)) == "$e + e^{2}$" f = Function('f') assert latex(f(x)) == '$\\operatorname{f}\\left(x\\right)$' beta = Function('beta') assert latex(beta(x)) == r"$\operatorname{beta}\left(x\right)$" assert latex(sin(x)) == r"$\operatorname{sin}\left(x\right)$" assert latex(sin(x), fold_func_brackets=True) == r"$\operatorname{sin}x$" assert latex(sin(2*x**2), fold_func_brackets=True) == \ r"$\operatorname{sin}2 x^{2}$" assert latex(factorial(k)) == r"$k!$" assert latex(factorial(-k)) == r"$\left(- k\right)!$" assert latex(floor(x)) == r"$\lfloor{x}\rfloor$" assert latex(ceiling(x)) == r"$\lceil{x}\rceil$" assert latex(abs(x)) == r"$\lvert{x}\rvert$" assert latex(re(x)) == r"$\Re{x}$" assert latex(im(x)) == r"$\Im{x}$" assert latex(conjugate(x)) == r"$\overline{x}$" assert latex(gamma(x)) == r"$\operatorname{\Gamma}\left(x\right)$" assert latex(Order(x)) == r"$\operatorname{\mathcal{O}}\left(x\right)$"
def run_Lagrange_interp_abs_conv(N=[3, 6, 12, 24]): f = sp.abs(1 - 2 * x) f = sp.sin(2 * sp.pi * x) fn = sp.lambdify([x], f, modules='numpy') resolution = 50001 import numpy as np xcoor = np.linspace(0, 1, resolution) fcoor = fn(xcoor) Einf = [] E2 = [] h = [] for _N in N: psi, points = Lagrange_polynomials_01(x, _N) u = interpolation(f, psi, points) un = sp.lambdify([x], u, modules='numpy') ucoor = un(xcoor) e = fcoor - ucoor Einf.append(e.max()) E2.append(np.sqrt(np.sum(e * e / e.size))) h.append(1. / _N) print Einf print E2 print h print N # Assumption: error = CN**(-N) print 'convergence rates:' for i in range(len(E2)): C1 = E2[i] / (N[i]**(-N[i] / 2)) C2 = Einf[i] / (N[i]**(-N[i] / 2)) print N[i], C1, C2
def run_Lagrange_interp_abs_conv(N=[3, 6, 12, 24]): f = sm.abs(1-2*x) f = sm.sin(2*sm.pi*x) fn = sm.lambdify([x], f, modules='numpy') resolution = 50001 import numpy as np xcoor = np.linspace(0, 1, resolution) fcoor = fn(xcoor) Einf = [] E2 = [] h = [] for _N in N: psi, points = Lagrange_polynomials_01(x, _N) u = interpolation(f, psi, points) un = sm.lambdify([x], u, modules='numpy') ucoor = un(xcoor) e = fcoor - ucoor Einf.append(e.max()) E2.append(np.sqrt(np.sum(e*e/e.size))) h.append(1./_N) print Einf print E2 print h print N # Assumption: error = CN**(-N) print 'convergence rates:' for i in range(len(E2)): C1 = E2[i]/(N[i]**(-N[i]/2)) C2 = Einf[i]/(N[i]**(-N[i]/2)) print N[i], C1, C2
def sp_derive(): import sympy as sp vars = 'G_s, s_n, s_p_n, w_n, dw_n, ds_n, G_s, G_w, c, phi' syms = sp.symbols(vars) for var, sym in zip(vars.split(','), syms): globals()[var.strip()] = sym s_n1 = s_n + ds_n w_n1 = w_n + dw_n tau_trial = G_s * (s_n1 - s_p_n) print('diff', sp.diff(tau_trial, ds_n)) print(tau_trial) sig_n1 = G_w * w_n1 print(sig_n1) tau_fr = (c + sig_n1 * sp.tan(phi)) * \ sp.Heaviside(sig_n1 - c / sp.tan(phi)) print(tau_fr) d_tau_fr = sp.diff(tau_fr, dw_n) print(d_tau_fr) f_trial = sp.abs(tau_trial) - tau_fr print(f_trial) d_gamma = f_trial / G_s print('d_gamma') sp.pretty_print(d_gamma) print('d_gamma_s') sp.pretty_print(sp.diff(d_gamma, ds_n)) print('tau_n1') tau_n1 = sp.simplify(tau_trial - d_gamma * G_s * sp.sign(tau_trial)) sp.pretty_print(tau_n1) print('dtau_n1_w') dtau_n1_w = sp.diff(tau_n1, dw_n) sp.pretty_print(dtau_n1_w) print('dtau_n1_s') dtau_n1_s = sp.diff(d_gamma * sp.sign(tau_trial), ds_n) print(dtau_n1_s) s_p_n1 = s_p_n + d_gamma * sp.sign(tau_trial) print(s_p_n1)
def test_latex_functions(): assert latex(exp(x)) == "$e^{x}$" assert latex(exp(1)+exp(2)) == "$e + e^{2}$" f = Function('f') assert latex(f(x)) == '$\\operatorname{f}\\left(x\\right)$' beta = Function('beta') assert latex(beta(x)) == r"$\operatorname{beta}\left(x\right)$" assert latex(sin(x)) == r"$\operatorname{sin}\left(x\right)$" assert latex(sin(x), fold_func_brackets=True) == r"$\operatorname{sin}x$" assert latex(sin(2*x**2), fold_func_brackets=True) == \ r"$\operatorname{sin}2 x^{2}$" assert latex(factorial(k)) == r"$k!$" assert latex(factorial(-k)) == r"$\left(- k\right)!$" assert latex(floor(x)) == r"$\lfloor{x}\rfloor$" assert latex(ceiling(x)) == r"$\lceil{x}\rceil$" assert latex(abs(x)) == r"$\lvert{x}\rvert$" assert latex(re(x)) == r"$\Re{x}$" assert latex(im(x)) == r"$\Im{x}$" assert latex(conjugate(x)) == r"$\overline{x}$" assert latex(gamma(x)) == r"$\operatorname{\Gamma}\left(x\right)$" assert latex(Order(x)) == r"$\operatorname{\mathcal{O}}\left(x\right)$"
def sp_derive(): import sympy as sp vars = 'G_s, s_n, s_p_n, w_n, dw_n, ds_n, G_s, G_w, c, phi' syms = sp.symbols(vars) for var, sym in zip(vars.split(','), syms): globals()[var.strip()] = sym s_n1 = s_n + ds_n w_n1 = w_n + dw_n tau_trial = G_s * (s_n1 - s_p_n) print 'diff', sp.diff(tau_trial, ds_n) print tau_trial sig_n1 = G_w * w_n1 print sig_n1 tau_fr = (c + sig_n1 * sp.tan(phi)) * sp.Heaviside(sig_n1 - c / sp.tan(phi)) print tau_fr d_tau_fr = sp.diff(tau_fr, dw_n) print d_tau_fr f_trial = sp.abs(tau_trial) - tau_fr print f_trial d_gamma = f_trial / G_s print 'd_gamma' sp.pretty_print(d_gamma) print 'd_gamma_s' sp.pretty_print(sp.diff(d_gamma, ds_n)) print 'tau_n1' tau_n1 = sp.simplify(tau_trial - d_gamma * G_s * sp.sign(tau_trial)) sp.pretty_print(tau_n1) print 'dtau_n1_w' dtau_n1_w = sp.diff(tau_n1, dw_n) sp.pretty_print(dtau_n1_w) print 'dtau_n1_s' dtau_n1_s = sp.diff(d_gamma * sp.sign(tau_trial), ds_n) print dtau_n1_s s_p_n1 = s_p_n + d_gamma * sp.sign(tau_trial) print s_p_n1
def chop(expr, tol = 1e-10): """suppress small numerical values""" expr = sp.expand(sp.sympify(expr)) if expr.is_Symbol: return expr assert expr.is_Add return sp.Add(*[term for term in expr.as_Add() if sp.abs(term.as_coeff_terms()[0]) >= tol])
def abs(*args, **kw): arg0 = args[0] if isinstance(arg0, (int, float, long)): return _math.abs(*args,**kw) elif isinstance(arg0, complex): return _cmath.abs(*args,**kw) elif isinstance(arg0, _sympy.Basic): return _sympy.abs(*args,**kw) else: return _numpy.abs(*args,**kw)
def run_Lagrange_leastsq_abs(N): """Least-squares with of Lagrange polynomials for |1-2x|.""" f = sm.abs(1-2*x) # This f will lead to failure of sympy integrate, fallback on numerical int. psi, points = Lagrange_polynomials_01(x, N) Omega=[0, 1] u = least_squares(f, psi, Omega) comparison_plot(f, u, Omega, filename='Lagrange_ls_abs_%d.pdf' % (N+1), plot_title='Least squares approximation by '\ 'Lagrange polynomials of degree %d' % N)
def run_Lagrange_leastsq_abs(N): """Least-squares with of Lagrange polynomials for |1-2x|.""" f = sp.abs(1 - 2 * x) # This f will lead to failure of sympy integrate, fallback on numerical int. psi, points = Lagrange_polynomials_01(x, N) Omega = [0, 1] u = least_squares(f, psi, Omega) comparison_plot(f, u, Omega, filename='Lagrange_ls_abs_%d' % (N+1), plot_title='Least squares approximation by '\ 'Lagrange polynomials of degree %d' % N)
def Generalized_Legendre(self, n=0, m=0, x=x): mode = self.select_exec_mode(x) if mode != "undef": legendre_polinomial = self.Legendre(n=n, x=x) rat_part = (1 - (x ** 2)) ** (sympy.abs(m) / 2.0) diff_part = sympy.diff(legendre_polinomial, x, abs(m)) return (rat_part * diff_part).expand() else: return False
def Phi_Equation(self, m="undef", phi=phi): if m == "undef": m = self.m_val m = int(m) mode = self.select_exec_mode(phi) if mode == "numer": phi_val = self.phi self.phi = Symbol("phi") elif mode == "custom_var": self.phi = Symbol(phi) elif mode == "undef": return False left_part = 1 / sympy.sqrt(2 * sympy.pi) right_part = sympy.cos(sympy.abs(m) * self.phi) if m >= 0 else sympy.sin(sympy.abs(m) * self.phi) if mode == "numer": return (left_part * right_part).evalf() elif mode == "analit" or mode == "custom_var": return (left_part * right_part).expand()
def R_par(m, theta_i): """ Fraction of parallel-polarized light that is reflected (R_p). Calculate reflected fraction of incident power (or flux) assuming that the E-field of the incident light is parallel to the plane of incidence Args: m : complex index of refraction [-] theta_i : incidence angle from normal [radians] Returns: reflected power [-] """ return sympy.abs(r_par_amplitude(m, theta_i))**2
def R_per(m, theta_i): """ Fraction of perpendicular-polarized light that is reflected (R_s). Calculates reflected fraction of incident power (or flux) assuming that the E-field of the incident light is perpendicular to the plane of incidence Args: m : complex index of refraction [-] theta_i : incidence angle from normal [radians] Returns: reflected irradiance [-] """ return sympy.abs(r_per(m, theta_i))**2
def l2_norm(f, lim): """ Calculates L2 norm of the function "f", over the domain lim=(x, a, b). x ...... the independent variable in f over which to integrate a, b ... the limits of the interval Example: >>> l2_norm(1, (x, -1, 1)) 2**(1/2) >>> l2_norm(x, (x, -1, 1)) 1/3*6**(1/2) """ return sqrt(integrate(abs(f)**2, lim))
def test_maxima_functions(): assert parse_maxima('expand( (x+1)^2)') == x**2 + 2*x + 1 assert parse_maxima('factor( x**2 + 2*x + 1)') == (x+1)**2 assert parse_maxima('trigsimp(2*cos(x)^2 + sin(x)^2)') == 2 - sin(x)**2 assert parse_maxima('trigexpand(sin(2*x)+cos(2*x))') == (-1) + 2*cos(x)**2 + 2*cos(x)*sin(x) assert parse_maxima('solve(x^2-4,x)') == [2, -2] assert parse_maxima('limit((1+1/x)^x,x,inf)') == E assert parse_maxima('limit(sqrt(-x)/x,x,0,minus)') == -oo assert parse_maxima('diff(x^x, x)') == x**x*(1 + log(x)) assert parse_maxima('sum(k, k, 1, n)') == (n**2 +n)/2 assert parse_maxima('product(k, k, 1, n)', name_dict=dict( n=Symbol('n',integer=True), k=Symbol('k',integer=True) ) ) == factorial(n) assert parse_maxima('ratsimp((x^2-1)/(x+1))') == x-1 assert abs( parse_maxima('float(sec(%pi/3) + csc(%pi/3))') - 3.154700538379252) < 10**(-5)
def T_per(m, theta_i): """ Fraction of perpendicular-polarized light that is transmitted (T_s). Calculate transmitted fraction of incident power (or flux) assuming that the E-field of the incident light is perpendicular to the plane of incidence Args: m : complex index of refraction [-] theta_i : incidence angle from normal [radians] Returns: transmitted field amplitude [-] """ c = sympy.cos(theta_i) s = sympy.sin(theta_i) d = sympy.sqrt(m * m - s * s) # m*cos(theta_t) ts = 2 * c / (c + d) return d / c * sympy.abs(ts)**2
def T_par(m, theta_i): """ Fraction of parallel-polarized light that is transmitted (T_p). Calculate transmitted fraction of incident power (or flux) assuming that the E-field of the incident light is parallel to the plane of incidence Args: m : complex index of refraction [-] theta_i : incidence angle from normal [radians] Returns: transmitted irradiance [-] """ c = sympy.cos(theta_i) s = sympy.sin(theta_i) d = sympy.sqrt(m * m - s * s) # m*cos(theta_t) tp = 2 * c * m / (m * m * c + d) return d / c * sympy.abs(tp)**2
def test_maxima_functions(): assert parse_maxima('expand( (x+1)^2)') == x**2 + 2 * x + 1 assert parse_maxima('factor( x**2 + 2*x + 1)') == (x + 1)**2 assert parse_maxima('trigsimp(2*cos(x)^2 + sin(x)^2)') == 2 - sin(x)**2 assert parse_maxima('trigexpand(sin(2*x)+cos(2*x))') == ( -1) + 2 * cos(x)**2 + 2 * cos(x) * sin(x) assert parse_maxima('solve(x^2-4,x)') == [2, -2] assert parse_maxima('limit((1+1/x)^x,x,inf)') == E assert parse_maxima('limit(sqrt(-x)/x,x,0,minus)') == -oo assert parse_maxima('diff(x^x, x)') == x**x * (1 + log(x)) assert parse_maxima('sum(k, k, 1, n)') == (n**2 + n) / 2 assert parse_maxima('product(k, k, 1, n)', name_dict=dict(n=Symbol('n', integer=True), k=Symbol('k', integer=True))) == factorial(n) assert parse_maxima('ratsimp((x^2-1)/(x+1))') == x - 1 assert abs( parse_maxima('float(sec(%pi/3) + csc(%pi/3))') - 3.154700538379252) < 10**(-5)
def test_latex_functions(): assert latex(exp(x)) == "e^{x}" assert latex(exp(1)+exp(2)) == "e + e^{2}" f = Function('f') assert latex(f(x)) == '\\operatorname{f}\\left(x\\right)' beta = Function('beta') assert latex(beta(x)) == r"\operatorname{beta}\left(x\right)" assert latex(sin(x)) == r"\operatorname{sin}\left(x\right)" assert latex(sin(x), fold_func_brackets=True) == r"\operatorname{sin}x" assert latex(sin(2*x**2), fold_func_brackets=True) == \ r"\operatorname{sin}2 x^{2}" assert latex(sin(x**2), fold_func_brackets=True) == \ r"\operatorname{sin}x^{2}" assert latex(asin(x)**2) == r"\operatorname{asin}^{2}\left(x\right)" assert latex(asin(x)**2,inv_trig_style="full") == \ r"\operatorname{arcsin}^{2}\left(x\right)" assert latex(asin(x)**2,inv_trig_style="power") == \ r"\operatorname{sin}^{-1}\left(x\right)^{2}" assert latex(asin(x**2),inv_trig_style="power",fold_func_brackets=True) == \ r"\operatorname{sin}^{-1}x^{2}" assert latex(factorial(k)) == r"k!" assert latex(factorial(-k)) == r"\left(- k\right)!" assert latex(floor(x)) == r"\lfloor{x}\rfloor" assert latex(ceiling(x)) == r"\lceil{x}\rceil" assert latex(abs(x)) == r"\lvert{x}\rvert" assert latex(re(x)) == r"\Re{x}" assert latex(im(x)) == r"\Im{x}" assert latex(conjugate(x)) == r"\overline{x}" assert latex(gamma(x)) == r"\operatorname{\Gamma}\left(x\right)" assert latex(Order(x)) == r"\operatorname{\mathcal{O}}\left(x\right)"
def SGN_S(x): return x/abs(x)
def test_ccode_exceptions(): assert ccode(ceiling(x)) == "ceil(x)" assert ccode(abs(x)) == "fabs(x)"
def eval_cross_section(N_atoms_uc, csection, kaprange, tau_list, eig_list, kapvect, wtlist, fflist, temperature, eief = True, efixed = 14.7): """ N_atoms_uc - number of atoms in unit cell csection - analytic cross-section expression kaprange - kappa modulus kapvect - list of kappa vectors tau_list - list of taus eig_list - list of eigenvalues wtlist - list of omegas fflist - magnetic form factor list temperature - temperature eief - True => E_initial = efixed, False => E_final = efixed efixed - fixed energy; either E_final or E_initial, subject to eief """ print "begin part 2" # Kappa vector kap = sp.Symbol('kappa', real = True) t = sp.Symbol('t', real = True) w = sp.Symbol('w', real = True) tau = sp.Symbol('tau', real = True) Q = sp.Symbol('q', real = True) L = sp.Symbol('L', real = True) wq = sp.Symbol('wq', real = True) kapxhat = sp.Symbol('kapxhat',real=True) kapyhat = sp.Symbol('kapyhat',real=True) kapzhat = sp.Symbol('kapzhat',real=True) kapunit = kapvect.copy() kapunit[:,0]=kapvect[:,0]/kaprange kapunit[:,1]=kapvect[:,1]/kaprange kapunit[:,2]=kapvect[:,2]/kaprange # Front constants and stuff for the cross-section boltz = 8.617343e-2 gamr0 = 1.913*2.818 hbar = 1#6.582*10**-13 g = 2.0 temperature = temperature debye_waller = 1.0 #exp(-2*W) front_constant = ((gamr0**2)*debye_waller/(2*pi*hbar)).evalf() #(gamr0)**2#/(2*pi*hbar) print front_constant # kappa, omegas, tau, eigs temp1 = [] for kapi in range(len(kapvect)): temp2 =[] for wi in range(len(wtlist)): temp3=[] for taui in range(len(tau_list)): print 'k,w,t',kapi,wi,taui ws=[] csectempp = deepcopy(csection) csectempm = deepcopy(csection) #qvalp = kapvect[kapi] - tau_list[taui] + qmins #qvalm = kapvect[kapi] - tau_list[taui] - qplus csectempp = csectempp.subs(sp.DiracDelta(kap - Q - tau),sp.S(1)) csectempp = csectempp.subs(sp.DiracDelta(kap + Q - tau),sp.S(0)) csectempm = csectempm.subs(sp.DiracDelta(kap - Q - tau),sp.S(0)) csectempm = csectempm.subs(sp.DiracDelta(kap + Q - tau),sp.S(1)) csectempp = csectempp.subs(kapxhat,kapunit[kapi,0]) csectempp = csectempp.subs(kapyhat,kapunit[kapi,1]) csectempp = csectempp.subs(kapzhat,kapunit[kapi,2]) csectempm = csectempm.subs(kapxhat,kapunit[kapi,0]) csectempm = csectempm.subs(kapyhat,kapunit[kapi,1]) csectempm = csectempm.subs(kapzhat,kapunit[kapi,2]) for eigi in range(len(eig_list[taui])): eigcsecp=deepcopy(csectempp) eigcsecm=deepcopy(csectempm) eigtemp = deepcopy(eig_list[0][eigi]) spinmag = sp.Symbol('S', real = True) kx = sp.Symbol('kx', real = True) ky = sp.Symbol('ky', real = True) kz = sp.Symbol('kz', real = True) eigtemp = eigtemp.subs(spinmag, sp.S(1.0)) eigtemp = eigtemp.subs(kx, kapvect[kapi][0]) eigtemp = eigtemp.subs(ky, kapvect[kapi][1]) eigtemp = eigtemp.subs(kz, kapvect[kapi][2]) eigtemp = sp.abs(eigtemp.evalf(chop=True)) # sp.Pow( sp.exp(-np.abs(eig_list[0][eigi])/boltz) - 1 ,-1) #\temperature term taken out nval = sp.Pow(sp.exp(sp.abs(eigtemp)/(boltz*temperature))-1,-1).evalf() for i in range(N_atoms_uc): nq = sp.Symbol('n%i'%(i,), real = True) eigcsecp = eigcsecp.subs(nq,nval) eigcsecm = eigcsecm.subs(nq,nval) wvalp = eigtemp - wtlist[wi] wvalm = eigtemp + wtlist[wi] eigcsecp = eigcsecp.subs((w-wq),wvalp) eigcsecp = eigcsecp.subs((w+wq),wvalm) eigcsecp = sp.re(eigcsecp.evalf(chop = True)) eigcsecm = eigcsecm.subs((w-wq),wvalp) eigcsecm = eigcsecm.subs((w+wq),wvalm) eigcsecm = sp.re(eigcsecm.evalf(chop = True)) # if np.abs(wvalp) < 0.1: # eigcsecp = eigcsecp.subs(sp.DiracDelta(w - wq), sp.S(1)) # eigcsecm = eigcsecm.subs(sp.DiracDelta(w - wq), sp.S(0)) # else: # eigcsecp = eigcsecp.subs(sp.DiracDelta(w - wq), sp.S(0)) # eigcsecm = eigcsecm.subs(sp.DiracDelta(w - wq), sp.S(0)) # if np.abs(wvalm) < 0.1: # eigcsecp = eigcsecp.subs(sp.DiracDelta(w + wq), sp.S(0)) # eigcsecm = eigcsecm.subs(sp.DiracDelta(w + wq), sp.S(1)) # else: # eigcsecp = eigcsecp.subs(sp.DiracDelta(w + wq), sp.S(0)) # eigcsecm = eigcsecm.subs(sp.DiracDelta(wq + w), sp.S(0)) # eief == True => ei=efixed # eief == False => ef=efixed kpk = 0. if eief == True: ei = efixed ef = ei - eigtemp kpk = ef/ei else: ef = efixed ei = ef + eigtemp kpk = ef/ei ws.append(kpk*(eigcsecp+eigcsecm)) temp3.append(sum(ws)) temp2.append(np.sum(np.array(temp3))) temp1.append(temp2) temp1 = np.array(temp1) csdata = np.array(sp.re(temp1.T)) print csdata.shape #Multiply data by front constants csdata = front_constant*csdata #Multiply by Form Factor print fflist.shape csdata = fflist*csdata return kapvect, wtlist, csdata
def test_parser(): assert abs(parse_maxima('float(1/3)') - 0.333333333) < 10**(-5) assert parse_maxima('13^26') == 91733330193268616658399616009 assert parse_maxima('sin(%pi/2) + cos(%pi/3)') == Rational(3, 2) assert parse_maxima('log(%e)') == 1
def test_parser(): assert abs(parse_maxima('float(1/3)') - 0.333333333) < 10**(-5) assert parse_maxima('13^26') == 91733330193268616658399616009 assert parse_maxima('sin(%pi/2) + cos(%pi/3)') == Rational(3,2) assert parse_maxima('log(%e)') == 1
def eval_cross_section(N_atoms_uc, csection, kaprange, tau_list, eig_list, kapvect, wtlist, fflist, temperature, eief = True, efixed = 14.7): """ N_atoms_uc - number of atoms in unit cell csection - analytic cross-section expression kaprange - kappa modulus kapvect - list of kappa vectors tau_list - list of taus eig_list - list of eigenvalues wtlist - list of omegas fflist - magnetic form factor list temperature - temperature eief - True => E_initial = efixed, False => E_final = efixed efixed - fixed energy; either E_final or E_initial, subject to eief """ print "Begin Numerical Evaluation of Cross-Section" kapunit = kapvect.copy() kapunit[:,0]=kapvect[:,0]/kaprange kapunit[:,1]=kapvect[:,1]/kaprange kapunit[:,2]=kapvect[:,2]/kaprange temperature = temperature front_constant = ((GAMMA_R0_VALUE**2)*DEBYE_WALLER_VALUE/(2*pi*HBAR_VALUE)).evalf() #(gamr0)**2#/(2*pi*hbar) print front_constant # kappa, omegas, tau, eigs temp1 = [] for kapi in range(len(kapvect)): temp2 =[] for wi in range(len(wtlist)): temp3=[] for taui in range(len(tau_list)): # print 'k,w,t',kapi,wi,taui ws=[] #qplus = kapvect[kapi] + tau_list[taui] #qmins = tau_list[taui] - kapvect[kapi] csectempp = copy(csection) csectempm = copy(csection) #qvalp = kapvect[kapi] - tau_list[taui] + qmins #qvalm = kapvect[kapi] - tau_list[taui] - qplus csectempp = csectempp.subs(DD_KTMQ_SYM,sp.S(1)) csectempp = csectempp.subs(DD_KTPQ_SYM,sp.S(0)) csectempm = csectempm.subs(DD_KTMQ_SYM,sp.S(0)) csectempm = csectempm.subs(DD_KTPQ_SYM,sp.S(1)) # csectempp = csectempp.subs(sp.DiracDelta(KAP_SYM - Q_SYM - TAU_SYM),sp.S(1)) # csectempp = csectempp.subs(sp.DiracDelta(KAP_SYM + Q_SYM - TAU_SYM),sp.S(0)) # csectempm = csectempm.subs(sp.DiracDelta(KAP_SYM - Q_SYM - TAU_SYM),sp.S(0)) # csectempm = csectempm.subs(sp.DiracDelta(KAP_SYM + Q_SYM - TAU_SYM),sp.S(1)) # print 'm' # print csectempm # print 'p' # print csectempp csectempp = csectempp.subs(KAPXHAT_SYM,kapunit[kapi,0]) csectempp = csectempp.subs(KAPYHAT_SYM,kapunit[kapi,1]) csectempp = csectempp.subs(KAPZHAT_SYM,kapunit[kapi,2]) csectempm = csectempm.subs(KAPXHAT_SYM,kapunit[kapi,0]) csectempm = csectempm.subs(KAPYHAT_SYM,kapunit[kapi,1]) csectempm = csectempm.subs(KAPZHAT_SYM,kapunit[kapi,2]) for eigi in range(len(eig_list[taui])): eigcsecp=copy(csectempp) eigcsecm=copy(csectempm) # print 'a' # print eigcsecp # print eigcsecm eigtemp = copy(eig_list[0][eigi]) # print 'eig', eigtemp # print 'kappa' # print kapvect[kapi][0] # print kapvect[kapi][1] # print kapvect[kapi][2] eigtemp = eigtemp.subs(S_SYM, sp.S(1.0)) eigtemp = eigtemp.subs(KX_SYM, kapvect[kapi][0]) eigtemp = eigtemp.subs(KY_SYM, kapvect[kapi][1]) eigtemp = eigtemp.subs(KZ_SYM, kapvect[kapi][2]) eigtemp = sp.abs(eigtemp.evalf(chop=True)) # sp.Pow( sp.exp(-np.abs(eig_list[0][eigi])/boltz) - 1 ,-1) #\temperature term taken out # print 'eig' # print eigtemp.evalf() # print 'a' # print eigcsecp # print eigcsecm nval = sp.Pow(sp.exp(sp.abs(eigtemp)/(BOLTZ_VALUE*temperature))-1,-1).evalf() for i in range(N_atoms_uc): nq = sp.Symbol('n%i'%(i,), real = True) eigcsecp = eigcsecp.subs(nq,nval) eigcsecm = eigcsecm.subs(nq,nval) # print 'b' # print eigcsecp # print eigcsecm wvalp = eigtemp - wtlist[wi] wvalm = eigtemp + wtlist[wi] # print 'w vals' # print wvalp # print wvalm eigcsecp = eigcsecp.subs((W_SYM - WQ_SYM),wvalp) eigcsecp = eigcsecp.subs((W_SYM + WQ_SYM),wvalm) eigcsecp = sp.re(eigcsecp.evalf(chop = True)) eigcsecm = eigcsecm.subs((W_SYM - WQ_SYM),wvalp) eigcsecm = eigcsecm.subs((W_SYM + WQ_SYM),wvalm) eigcsecm = sp.re(eigcsecm.evalf(chop = True)) # if np.abs(wvalp) < 0.1: # eigcsecp = eigcsecp.subs(sp.DiracDelta(w - wq), sp.S(1)) # eigcsecm = eigcsecm.subs(sp.DiracDelta(w - wq), sp.S(0)) # else: # eigcsecp = eigcsecp.subs(sp.DiracDelta(w - wq), sp.S(0)) # eigcsecm = eigcsecm.subs(sp.DiracDelta(w - wq), sp.S(0)) # if np.abs(wvalm) < 0.1: # eigcsecp = eigcsecp.subs(sp.DiracDelta(w + wq), sp.S(0)) # eigcsecm = eigcsecm.subs(sp.DiracDelta(w + wq), sp.S(1)) # else: # eigcsecp = eigcsecp.subs(sp.DiracDelta(w + wq), sp.S(0)) # eigcsecm = eigcsecm.subs(sp.DiracDelta(wq + w), sp.S(0)) # # print 'p' # print eigcsecp # print 'm' # print eigcsecm # eief == True => ei=efixed # eief == False => ef=efixed kpk = 0. if eief == True: ei = efixed ef = ei - eigtemp kpk = ef/ei else: ef = efixed ei = ef + eigtemp kpk = ef/ei ws.append(kpk*(eigcsecp+eigcsecm)) temp3.append(sum(ws)) temp2.append(np.sum(np.array(temp3))) temp1.append(temp2) temp1 = np.array(temp1) csdata = np.array(sp.re(temp1.T)) print csdata.shape #Multiply data by front constants #csdata = front_constant*csdata #Multiply by Form Factor print fflist.shape csdata = (0.5*G_VALUE*fflist)**2*csdata return kapvect, wtlist, csdata
def Square_Wave_Function_Ion_Negative(self, R="undef"): if R == "undef": R = self.R return sympy.abs(self.Wave_Function_Ion_Negative(R)) ** 2
def single_cross_section_calc(theta, phi, rad, N_atoms_uc, atom_list, csection, tau, eig_list, wt, temperature, eief = True, efixed = 14.7): temperature = temperature front_constant = ((GAMMA_R0_VALUE**2)*DEBYE_WALLER_VALUE/(2*pi*HBAR_VALUE)).evalf() kx = rad*np.sin(theta)*np.cos(phi) ky = rad*np.sin(theta)*np.sin(phi) kz = rad*np.cos(theta) kap = np.array([kx,ky,kz]) kapunit = kap.copy() kapunit[0]=kap[0]/rad kapunit[1]=kap[1]/rad kapunit[2]=kap[2]/rad ws=[] #csectempp = deepcopy(csection) #good #csectempm = deepcopy(csection) #good csectempp = copy(csection) #good csectempm = copy(csection) #good cs_expr = sp.lambdify((KAP_SYM,Q_SYM,TAU_SYM,W_SYM,WQ_SYM,KAPXHAT_SYM,KAPYHAT_SYM,KAPZHAT_SYM), expr2, modules = "numpy") #res_np = expr_np(Svals[:,newaxis,newaxis,newaxis],xvals[newaxis,:,newaxis,newaxis],yvals[newaxis,newaxis,:,newaxis],zvals[newaxis,newaxis,newaxis,:]) res_np2 = expr_np2(xvals[:,newaxis,newaxis],yvals[newaxis,:,newaxis],zvals[newaxis,newaxis,:]) csectempp = csectempp.subs(sp.DiracDelta(KAP_SYM - Q_SYM - TAU_SYM),sp.S(1)) csectempp = csectempp.subs(sp.DiracDelta(KAP_SYM + Q_SYM - TAU_SYM),sp.S(0)) csectempm = csectempm.subs(sp.DiracDelta(KAP_SYM - Q_SYM - TAU_SYM),sp.S(0)) csectempm = csectempm.subs(sp.DiracDelta(KAP_SYM + Q_SYM - TAU_SYM),sp.S(1)) csectempp = csectempp.subs(KAPXHAT_SYM,kapunit[0]) csectempp = csectempp.subs(KAPYHAT_SYM,kapunit[1]) csectempp = csectempp.subs(KAPZHAT_SYM,kapunit[2]) csectempm = csectempm.subs(KAPXHAT_SYM,kapunit[0]) csectempm = csectempm.subs(KAPYHAT_SYM,kapunit[1]) csectempm = csectempm.subs(KAPZHAT_SYM,kapunit[2]) for eigi in range(len(eig_list)): #eigcsecp=deepcopy(csectempp) #good #eigcsecm=deepcopy(csectempm) #eigtemp = deepcopy(eig_list[0][eigi]) eigcsecp=copy(csectempp) #good eigcsecm=copy(csectempm) eigtemp = copy(eig_list[0][eigi]) eig_expr = sp.lambdify((S_SYM,KX_SYM,KY_SYM,KZ_SYM), sp.abs(eigtemp))#, modules = "numpy") eigval = eig_expr(S(1.0),kap[0],kap[1],kap[2]).evalf(chop=True) eigtemp = eigtemp.subs(S_SYM, sp.S(1.0)) eigtemp = eigtemp.subs(KX_SYM, kap[0]) eigtemp = eigtemp.subs(KY_SYM, kap[1]) eigtemp = eigtemp.subs(KZ_SYM, kap[2]) eigtemp = sp.abs(eigtemp.evalf(chop=True)) #works #eigtemp = chop(np.abs(eigtemp)) nval = sp.Pow(sp.exp(eigtemp/(BOLTZ_VALUE*temperature))-1,-1).evalf() #works #nval = np.power(np.exp(np.abs(eigtemp)/(BOLTZ*temperature))-1,-1) for i in range(N_atoms_uc): nq = sp.Symbol('n%i'%(i,), real = True) eigcsecp = eigcsecp.subs(nq,nval) eigcsecm = eigcsecm.subs(nq,nval) wvalp = eigtemp - wt wvalm = eigtemp + wt eigcsecp = eigcsecp.subs((W_SYM - WQ_SYM),wvalp) eigcsecp = eigcsecp.subs((W_SYM + WQ_SYM),wvalm) eigcsecp = sp.re(eigcsecp.evalf(chop = True)) # works #eigcsecp = chop(eigcsecp) eigcsecm = eigcsecm.subs((W_SYM - WQ_SYM),wvalp) eigcsecm = eigcsecm.subs((W_SYM + WQ_SYM),wvalm) eigcsecm = sp.re(eigcsecm.evalf(chop = True)) #works #eigcsecm = chop(eigcsecm) # eief == True => ei=efixed # eief == False => ef=efixed kpk = 0. if eief == True: ei = efixed ef = ei - eigtemp kpk = ef/ei else: ef = efixed ei = ef + eigtemp kpk = ef/ei ws.append(kpk*(eigcsecp+eigcsecm)) csdata = sp.re(sum(ws)) #Multiply data by front constants csdata = front_constant*csdata #Multiply by Form Factor csdata = G_VALUE*csdata #print kx,'\t\t',ky,'\t\t',kz,'\t\t',csdata return csdata#*np.sin(theta)*rad**2
lf = lambdify_t(f) tt = np.arange(dt,t+dt,dt) return lf(tt).sum() * dt _gexpr = gamma_expr(5.4, 5.2) - 0.35 * gamma_expr(10.8, 7.35) _gexpr = _gexpr / _getint(_gexpr) _glover = lambdify_t(_gexpr) glover = implemented_function('glover', _glover) glovert = lambdify_t(glover(T)) # Derivative of Glover HRF _dgexpr = _gexpr.diff(T) dpos = sympy.Derivative((T >= 0), T) _dgexpr = _dgexpr.subs(dpos, 0) _dgexpr = _dgexpr / _getint(sympy.abs(_dgexpr)) _dglover = lambdify_t(_dgexpr) dglover = implemented_function('dglover', _dglover) dglovert = lambdify_t(dglover(T)) del(_glover); del(_gexpr); del(dpos); del(_dgexpr); del(_dglover) # AFNI's HRF _aexpr = ((T >= 0) * T)**8.6 * sympy.exp(-T/0.547) _aexpr = _aexpr / _getint(_aexpr) _afni = lambdify_t(_aexpr) afni = implemented_function('afni', _afni) afnit = lambdify_t(afni(T))
return lf(tt).sum() * dt deft = DeferredVector('t') _gexpr = gamma_params(5.4, 5.2) - 0.35 * gamma_params(10.8,7.35) _gexpr = _gexpr / _getint(_gexpr) _glover = vectorize(_gexpr) glover = aliased_function('glover', _glover) n = {} glovert = vectorize(glover(deft)) # Derivative of Glover HRF _dgexpr = _gexpr.diff(t) dpos = Derivative((t >= 0), t) _dgexpr = _dgexpr.subs(dpos, 0) _dgexpr = _dgexpr / _getint(abs(_dgexpr)) _dglover = vectorize(_dgexpr) dglover = aliased_function('dglover', _dglover) dglovert = vectorize(dglover(deft)) del(_glover); del(_gexpr); del(dpos); del(_dgexpr); del(_dglover) # AFNI's HRF _aexpr = ((t >= 0) * t)**8.6 * exp(-t/0.547) _aexpr = _aexpr / _getint(_aexpr) _afni = vectorize(_aexpr) afni = aliased_function('afni', _afni) afnit = vectorize(afni(deft)) # Primitive of the HRF -- temoprary fix to handle blocks
def gen_mag(self, ident, val): return sym.abs(val.exp)
def test_abs(): assert str(abs(x)) == "abs(x)" assert str(abs(Rational(1,6))) == "1/6" assert str(abs(Rational(-1,6))) == "1/6"
def test_abs(): assert str(abs(x)) == "abs(x)" assert str(abs(Rational(1, 6))) == "1/6" assert str(abs(Rational(-1, 6))) == "1/6"
def single_cross_section_calc(theta, phi, rad, N_atoms_uc, atom_list, csection, tau, eig_list, wt, temperature, eief = True, efixed = 14.7): temperature = temperature front_constant = ((GAMMA_R0_VALUE**2)*DEBYE_WALLER_VALUE/(2*pi*HBAR_VALUE)).evalf() kx = rad*np.sin(theta)*np.cos(phi) ky = rad*np.sin(theta)*np.sin(phi) kz = rad*np.cos(theta) kap = np.array([kx,ky,kz]) # kapunit = kap.copy() # kapunit[0]=kap[0]/rad # kapunit[1]=kap[1]/rad # kapunit[2]=kap[2]/rad ws=[] #csectempp = deepcopy(csection) #good #csectempm = deepcopy(csection) #good csectempp = copy(csection) #good csectempm = copy(csection) #good csectempp = csectempp.subs(DD_KTMQ_SYM,sp.S(1)) csectempp = csectempp.subs(DD_KTPQ_SYM,sp.S(0)) csectempm = csectempm.subs(DD_KTMQ_SYM,sp.S(0)) csectempm = csectempm.subs(DD_KTPQ_SYM,sp.S(1)) # csectempp = csectempp.subs(sp.DiracDelta(KAP_SYM - Q_SYM - TAU_SYM),sp.S(1)) # csectempp = csectempp.subs(sp.DiracDelta(KAP_SYM + Q_SYM - TAU_SYM),sp.S(0)) # csectempm = csectempm.subs(sp.DiracDelta(KAP_SYM - Q_SYM - TAU_SYM),sp.S(0)) # csectempm = csectempm.subs(sp.DiracDelta(KAP_SYM + Q_SYM - TAU_SYM),sp.S(1)) csectempp = csectempp.subs(KAPXHAT_SYM,kap[0]/rad) csectempp = csectempp.subs(KAPYHAT_SYM,kap[1]/rad) csectempp = csectempp.subs(KAPZHAT_SYM,kap[2]/rad) csectempm = csectempm.subs(KAPXHAT_SYM,kap[0]/rad) csectempm = csectempm.subs(KAPYHAT_SYM,kap[1]/rad) csectempm = csectempm.subs(KAPZHAT_SYM,kap[2]/rad) # eig_list = eig_list[0].tolist() # eig_func = sp.lambdify((S_SYM,KX_SYM,KY_SYM,KZ_SYM),eig_list,modules="numpy") # eigens = np.abs(np.array(eig_func(sp.S(1,0),kx,ky,kz))) # cs_func = sp.lambdify((DD_KTPQ_SYM,DD_KTMQ_SYM,KAPXHAT_SYM,KAPYHAT_SYM,KAPZHAT_SYM,W_SYM,WQ_SYM) # ,[csection,csection],modules="numpy") # csvals = cs_func([1,0],[0,1],kap[0]/rad,kap[1]/rad,kap[2]/rad,) for eigi in range(len(eig_list)): # for eigi in eigens: #eigcsecp=deepcopy(csectempp) #good #eigcsecm=deepcopy(csectempm) #eigtemp = deepcopy(eig_list[0][eigi]) eigcsecp=copy(csectempp) #good eigcsecm=copy(csectempm) eigtemp = copy(eig_list[0][eigi]) #good eigtemp = eigtemp.subs(S_SYM, sp.S(1.0)) eigtemp = eigtemp.subs(KX_SYM, kap[0]) eigtemp = eigtemp.subs(KY_SYM, kap[1]) eigtemp = eigtemp.subs(KZ_SYM, kap[2]) eigtemp = sp.abs(eigtemp.evalf(chop=True)) #works #eigtemp = chop(np.abs(eigtemp)) # nval = sp.Pow(sp.exp(eigi/(BOLTZ_VALUE*temperature))-1,-1).evalf() #nval = sp.Pow(sp.exp(eigtemp/(BOLTZ_VALUE*temperature))-1,-1).evalf() #works #nval = np.power(np.exp(np.abs(eigtemp)/(BOLTZ*temperature))-1,-1) nval = sp.S(0) for i in range(N_atoms_uc): nq = sp.Symbol('n%i'%(i,), real = True) eigcsecp = eigcsecp.subs(nq,nval) eigcsecm = eigcsecm.subs(nq,nval) wvalp = eigtemp - wt wvalm = eigtemp + wt # wvalp = eigi - wt # wvalm = eigi + wt eigcsecp = eigcsecp.subs((W_SYM - WQ_SYM),wvalp) eigcsecp = eigcsecp.subs((W_SYM + WQ_SYM),wvalm) eigcsecp = sp.re(eigcsecp.evalf(chop = True)) # works #eigcsecp = chop(eigcsecp) eigcsecm = eigcsecm.subs((W_SYM - WQ_SYM),wvalp) eigcsecm = eigcsecm.subs((W_SYM + WQ_SYM),wvalm) eigcsecm = sp.re(eigcsecm.evalf(chop = True)) #works #eigcsecm = chop(eigcsecm) # eief == True => ei=efixed # eief == False => ef=efixed kpk = 0. if eief == True: ei = efixed # ef = ei - eigi ef = ei - eigtemp kpk = ef/ei else: ef = efixed # ef = ei + eigi ei = ef + eigtemp kpk = ef/ei ws.append(kpk*(eigcsecp+eigcsecm)) csdata = sp.re(sum(ws)) #Multiply data by front constants csdata = front_constant*csdata # CHECK THIS! THIS IS IMPORTANT AND MAY SCREW THINGS UP #Multiply by Form Factor ff = 0 for i in range(N_atoms_uc): el = elements[atom_list[i].atomicNum] val = atom_list[i].valence if val != None: Mq = el.magnetic_ff[val].M_Q(rad) else: Mq = el.magnetic_ff[0].M_Q(rad) ff = Mq csdata = (0.5*G_VALUE*ff)**2*csdata #print kx,'\t\t',ky,'\t\t',kz,'\t\t',csdata return csdata#*np.sin(theta)*rad**2
plotlist = np.array([[(k+1)/256., vtrans[k%256]] for k in range(768)]) plt.plot(plotlist[:,0], plotlist[:,1]) # what does the following line do? plt.axhline(0) # add labels plt.show() plot3(1, 2700.0) plot3(1/3., 200.0) plot3(3.0, 5.0) eq2 = (ir * (r + 1/(1j*omega*c) + 1j*omega*l) + vo - 1, ir - (1j*omega*c + 1/(1j*omega*l)) * vo) sol2 = # complete this line vos2 = simplify(sol2[vo]) irs = simplify(sol2[ir]) # why should irs be passed to sympy.abs() before squaring? power = (r**2) *( sympy.abs(irs)**2) flist3 = [sympy.abs(vos2.subs(numvalue).subs({r: 10.0*3**s})) for s in range(0, 3)] omega_axis = np.linspace(10000, 70000, 1000) lines = # ... # what does plt.setp() do? plt.setp(lines[0], lw=2) plt.setp(lines[1], ls='--' # add labels and ticks plt.minorticks_on() plt.show() # replicate fig. 2.10