def delay(omegaV, free): E_0 = -1.1591 E_m = [-0.8502, -0.3278, -0.1665] T = 3/0.02419 delta_m = np.zeros(np.size(E_m)) for j in (0, 1, 2): delta_m[j] = E_m[j] - E_0 optSize = np.size(omegaV) alpha1f = np.zeros(optSize, 'complex') alpha3f = np.zeros(optSize, 'complex') realFactor = np.zeros(optSize, 'complex') imagFactor = np.zeros(optSize, 'complex') T = 3 / 0.02419 for i in range(0, np.size(defs.omega_dip)-1): alpha1f[i] = dipole.constructDipole(omegaV[i], defsDipole.wf1) alpha3f[i] = dipole.constructDipole(omegaV[i], defsDipole.wf3) dawsArg1st = T*(delta_m[0] - omegaV) dawsArg3rd = T*(delta_m[1] - omegaV) realFactor = np.real((alpha1f * np.exp(-free*np.power(dawsArg1st,2.0)))\ + (alpha3f * np.exp(-np.sqrt(free)*np.power(dawsArg3rd, 2.0)))) imagFactor = (alpha1f * ((-2 * cmath.sqrt(-1))\ / (np.sqrt(np.pi))) * spcl.dawsn(free*dawsArg1st))\ + (alpha3f * ((-2 * cmath.sqrt(-1))\ / (np.sqrt(np.pi))) * spcl.dawsn(np.sqrt(free)*dawsArg3rd)) dE = np.gradient(omegaV) dIm = np.gradient(imagFactor, dE) dRe = np.gradient(realFactor, dE) derivFactor = (realFactor * dIm) - (np.imag(imagFactor * dRe)) zSquared = realFactor*realFactor + np.imag(imagFactor)*np.imag(imagFactor) ans = (realFactor * np.imag(dIm) - np.imag(imagFactor * dRe)) / zSquared return ans
def TAnalytic(self): """ z = vector of z coordinate postions such that 0 is surface and bed is negative thickness w = vertical velocity in meters per second. also a vector of the same size as z H = ice thickness ubar = vertical average of the horizontal speed in meters per second. alpha = surface slope as a ratio of rise to run. lamb = elevational lapse rate Qgeo = geothermal heat flow Ts = Surface temperature (mean annual) OUTPUT: T = a vector of temperatures (almost) """ z = self.Z w = self.w_z / spy H = self.Z[0] - self.Z[-1] ubar = (self.u_b + 0.8 * (self.u_s - self.u_b)) / spy #np.average([self.u_s, self.u_b]) / spy alpha = deg2ratio(self.pz_spx) lamb = self.lmbda Qgeo = self.Q_geo Ts = self.theta_s k = self.k # Thermal conductivity of ice W/m/K rhoi = self.lrho # Density of ice kg/m^3 cp = self.cp # Heat Capacity of ice J/K/kg w = w * spy ubar = ubar * spy xphi = np.sqrt(np.abs(w[0] - w[-1]) / (2 * H * (k/(rhoi * cp)*spy))) coef = 2. * ubar * alpha * lamb * H / (w[0] - w[-1]) T = Ts - Qgeo / (k * xphi) * np.sqrt(np.pi)/2. * \ (ss.erf(xphi*H) - ss.erf(xphi * (-z))) \ + coef * (ss.dawsn(xphi * H) - ss.dawsn(xphi * (-z))) return [T[-1::-1]] # Be careful with this, your coordinate system may be different.
def rate_functions_model_2(a_t,b_t,a_s,b_s,j0,c0,temp): ks = (a_s/np.sqrt(temp))*np.exp(-b_s*b_s/temp) kt = (a_t/np.sqrt(temp))*np.exp(-b_t*b_t/temp) j = (1.0/(2.0*np.sqrt(np.pi)))*((a_s/np.sqrt(temp))*special.dawsn(b_s/np.sqrt(temp)) - (a_t/np.sqrt(temp))*special.dawsn(b_t/np.sqrt(temp))) + j0 + c0*temp return ks,kt,j
def rate_functions_model_3(a_t,b_t,a_s,b_s,j0,c,lamb0,lamb_coef,temp): ks = (a_s*(1.0+c*temp)/np.sqrt(temp))*np.exp(-b_s*b_s/temp) kt = (a_t*(1.0+c*temp)/np.sqrt(temp))*np.exp(-b_t*b_t/temp) j = (1.0/(2.0*np.sqrt(np.pi)))*((a_s*(1.0+c*temp)/np.sqrt(temp))*special.dawsn(b_s/np.sqrt(temp)) - (a_t*(1.0+c*temp)/np.sqrt(temp))*special.dawsn(b_t/np.sqrt(temp))) + j0*(1.0-(c*temp)) lamb = lamb0 + temp*lamb_coef return ks,kt,j,lamb
def _siegert_interm(y_th, y_r, tau_m, t_ref, gl_order): """Calculate Siegert without exp(-y_th**2) factor for y_r <= 0 <= y_th.""" assert np.all((y_r <= 0) & (0 <= y_th)) e_V_th_2 = np.exp(-y_th**2) I_erfcx = 2 * dawsn(y_th) I_erfcx += e_V_th_2 * _erfcx_integral(y_th, np.abs(y_r), gl_order) return 1 / (e_V_th_2 * t_ref + tau_m * np.sqrt(np.pi) * I_erfcx)
def testDawsnSmall(self, dtype): seed_stream = test_util.test_seed_stream() x = self.evaluate( tf.random.uniform( [int(1e4)], 0., 1., dtype=dtype, seed=seed_stream())) self.assertAllClose( scipy_special.dawsn(x), self.evaluate(tfp.math.dawsn(x)))
def Daws(x, n, method): if method == 'Trap': #apply Trapezoidal method integral_real = Trap(expo, 0, x, n) return np.exp(-x**2) * integral_real elif method == 'Simp': #apply Simpsons method integral_real = Simp(expo, 0, x, n) return np.exp(-x**2) * integral_real elif method == 'Scipy': #use scipy library return special.dawsn(x) elif method == 'Gauss': #apply gauss method integral = 0 s, w = gaussxwab(n, 0, x) for i in range(n): integral += w[i] * expo(s[i]) return np.exp(-x**2) * integral else: return 'Input error :D'
def FourierSum(self,gam,nu): A0 = 0.0*gam; # make this the same shape as gam, if gam is an array alpha = 2 * (np.arcsinh(gam)-gam/np.sqrt(1+gam**2)) beta = 2*gam/np.sqrt(1+gam**2) dnu = np.ceil(nu) - nu for n in range(self.terms): A0 += np.exp(-alpha*(n+dnu))*spsf.dawsn(np.sqrt(beta*(n+dnu))) # only valid for m=0 return A0;
def test_dawsn_larger(self, dtype): x = np.random.uniform(1., 100., size=int(1e4)).astype(dtype) try: from scipy import special # pylint: disable=g-import-not-at-top self.assertAllClose( special.dawsn(x), self.evaluate(special_math_ops.dawsn(x))) except ImportError as e: tf_logging.warn('Cannot test special functions: %s' % str(e))
def g(x): """Calculate `x + (1-2x^2) D(x)`, where D(x) is the dawson function""" # For x < 50, use dawsn from scipy # For x > 100, use dawsn expansion b = blend(x, 50, 100) y1 = x + (1 - 2 * x**2) * special.dawsn(x) y2 = dawsn_expansion_drop_first( x) - dawsn_expansion_drop_first_two(x) * 2 * x**2 return b * y2 + (1 - b) * y1
def fitDipoleFactors(omegaF, m1, m3, c_1, c_3, free): E_0 = -1.1591 E_m = [-0.8502, -0.3278, -0.1665] T = 3/0.02419 delta_m = np.zeros(np.size(E_m)) for j in (0, 1, 2): delta_m[j] = E_m[j] - E_0 optSize = np.size(omegaF) alpha1f = np.zeros(optSize, 'complex') alpha3f = np.zeros(optSize, 'complex') omegaV = np.zeros(optSize) realFactor = np.zeros(optSize, 'complex') imagFactor = np.zeros(optSize, 'complex') i = 0 T = 3 / 0.02419 for x in omegaF: omegaV[i] = x # alpha1f[i] = m1*x + c_1#constructDipole(x, defs.wf1) + c_1 # alpha3f[i] = m3*x + c_3#constructDipole(x, defs.wf3) + c_3 alpha1f[i] = constructDipole(x, defs.wf1) + c_1 alpha3f[i] = constructDipole(x, defs.wf3) + c_3 i = i + 1 # print "Dipoles Calc'd" dawsArg1st = T*(delta_m[0] - omegaV) dawsArg3rd = T*(delta_m[1] - omegaV) realFactor = (alpha1f * np.exp(-np.power(dawsArg1st,2.0)))\ + (alpha3f * np.exp(-np.power(dawsArg3rd, 2.0))) imagFactor = (alpha1f * ((-2 * cmath.sqrt(-1))\ / (np.sqrt(np.pi))) * spcl.dawsn(np.sqrt(free)*dawsArg1st))\ + (alpha3f * ((-2 * cmath.sqrt(-1))\ / (np.sqrt(np.pi))) * spcl.dawsn(np.sqrt(free)*dawsArg3rd)) domegaV = np.gradient(omegaV) phase_fit = np.arctan(np.imag(imagFactor)/np.real(realFactor)) dphi_fit = np.gradient(phase_fit, domegaV) # print "dPhi calc'd" #return omegaV return dphi_fit
def fit_alphas_dynamic(omegaV, m_1, b_1, m_3, b_3, alpha_free): dawsarg_1st = T*(delta_m[0] - omegaV) dawsarg_3rd = T*(delta_m[1] - omegaV) alpha1f = fit_dipoles(omegaV, m_1, b_1) alpha3f = fit_dipoles3(omegaV, m_3, b_3) real_factor = (alpha1f*np.exp(-alpha_free*T*T*(delta_m[0]-omegaV)\ *(delta_m[0]-omegaV)))\ + (alpha3f* np.exp(-alpha_free*T*T*\ (delta_m[1]-omegaV)*(delta_m[1]-omegaV))) imag_factor = (alpha1f*(-2*cmath.sqrt(-1))/\ (np.sqrt(np.pi))*spcl.dawsn(np.sqrt(alpha_free)*dawsarg_1st)) + \ (alpha3f*((-2*cmath.sqrt(-1))/\ (np.sqrt(np.pi)))*spcl.dawsn(np.sqrt(alpha_free)*dawsarg_3rd)) domegaV = np.gradient(omegaV) phase_fit = np.arctan(np.imag(imag_factor)/np.real(real_factor)) dphi_fit = np.gradient(phase_fit, domegaV) return dphi_fit
def fitAlphas(omegaV, b1A, b1B, b1C, b1D, b1E, b1F, \ b3A, b3B, b3C, b3D, b3E, b3F, b3G, b3H, b3I, alpha_free): dawsarg_1st = defs.T*(defs.delta_m[0] - omegaV) dawsarg_3rd = defs.T*(defs.delta_m[1] - omegaV) alpha1f = alphaOne(omegaV, b1A, b1B, b1C, b1D, b1E, b1F) alpha3f = alphaThree(omegaV, b3A, b3B, b3C, b3D, b3E, b3F, b3G, b3H, b3I) real_factor = (alpha1f*np.exp(-alpha_free*defs.T*defs.T*(defs.delta_m[0]-omegaV)\ *(defs.delta_m[0]-omegaV)))\ + (alpha3f * np.exp(-alpha_free* defs.T * defs.T *\ (defs.delta_m[1]-omegaV)*(defs.delta_m[1]-omegaV))) imag_factor = (alpha1f*(-2*cmath.sqrt(-1))/\ (np.sqrt(np.pi))*spcl.dawsn(np.sqrt(alpha_free)*dawsarg_1st)) + \ (alpha3f*((-2*cmath.sqrt(-1))/\ (np.sqrt(np.pi)))*spcl.dawsn(np.sqrt(alpha_free)*dawsarg_3rd)) domegaV = np.gradient(omegaV) phase_fit = np.arctan(np.imag(imag_factor)/np.real(real_factor)) dphi_fit = np.gradient(phase_fit, domegaV) return dphi_fit
def _half_folded_tau_over_folded_var_freq_dist(self, x, S): if S < 0: S = -S rs = np.sqrt(S) var_normaliser = 4.0 * rs * dawsn(rs / 2.0) - S * self._SCAL if x <= self._DENOMINATOR: numerati = float(self.N) / (S * (1 - x)) else: numerati = 1.0 / (2.0 * S * x * (1 - x)) foldtau_over_fold_var_freq_dist = numerati * float(var_normaliser) return 0.5 * foldtau_over_fold_var_freq_dist
def int_exact(self, X): q = np.zeros(X.size) i = 0 fun1 = lambda x: np.power(erfcx(-x), 2) * dawsn(x) fun2 = lambda x: np.exp(-x * x) * np.power(erfcx(-x), 2) for x in X: y1, _ = quad(fun1, -np.inf, x) y2, _ = quad(fun2, -np.inf, x) q[i] = -np.pi / 4 * y1 + np.power(np.sqrt(np.pi) / 2, 3) * erfi(x) * y2 i += 1 return q
def main(): # evaluate at x = 4 x = 4 # store results as [[N], [Trapezoidal], [Simpson], [Gauss]] result = [[], [], [], []] for i in range(3, 12): N = 2 ** i # evaluate Dawson for various N using each integration method and store result result[0].append(N) result[1].append(evaluate_dawson(trapezoidal_integral, N, x)) result[2].append(evaluate_dawson(simpson_integral, N, x)) result[3].append(evaluate_dawson(gauss_wrapper, N, x)) # title for the table headers = ["N", "Trapezoidal rule", "Simpson's rule", "Gaussian Quadrature"] # create and print table using result tab = tabulate(np.array(result).T, headers=headers, tablefmt="pretty") print(tab) # the practical error estimation I_2N - I_N using np.diff as result already # contains evaluation for I_N, I_2N, I_4N... error = np.diff(result) error[1] = 1 / 3 * error[0] # Need to multiply by 1/3 for Trapezoidal method error[2] = 1 / 15 * error[1] # Need to multiply by 1/15 for Simpson's method # plot the error estimation plt.figure() # since diff subtracts the conscutive entries of array, plot by excluding the # first N as result[0][1:] plt.loglog(result[0][1:], error[1], label = "Trapezoidal") plt.loglog(result[0][1:], error[2], label="Simpson's") plt.loglog(result[0][1:], error[3], label = "Gaussian") plt.legend() plt.xlabel("N") plt.ylabel("Error") plt.title("Practical error estimation for different integration methods") plt.savefig("Q1ai.pdf") # evaluating Dawson function using scipy.special.dawsn dawsn_eval = dawsn(4) # plot the absolute relative error by taking dawsn as the True value plt.figure() # log-log plot for absolute relative error for all 3 methods plt.loglog(result[0], np.abs(dawsn_eval - result[1]) / dawsn_eval, label = "Trapezoidal") plt.loglog(result[0], np.abs(dawsn_eval - result[2]) / dawsn_eval, label = "Simpson's") plt.loglog(result[0], np.abs(dawsn_eval - result[3]) / dawsn_eval, label = "Gaussian") plt.legend() plt.xlabel("N") plt.ylabel("Error") plt.title("Absolute relative error using scipy.special.dawsn as the true value") plt.savefig("Q1aii.pdf")
def _get_variance_units_little_del_square(self): """ Returns steady-state phenotypic variance, in units little delta squared """ SHAPE_S, SCALE_S = float(self.E2Ns)**2 / float(self.V2Ns), float( self.V2Ns) / float(self.E2Ns) S_dist = gamma(SHAPE_S, loc=0., scale=SCALE_S) to_integrate = lambda ss: 4.0 * np.sqrt(np.abs(ss)) * dawsn( np.sqrt(np.abs(ss)) / 2.0) * S_dist.pdf(ss) b = S_dist.ppf(0.99999999999999) myintegral = quad(to_integrate, 0, b)[0] var_0_del_square = myintegral * self._MUT_INPUT return var_0_del_square
def _the_integral_variance_per_unit_mut_input(self, x): if x <= self._a: return 0 if self._a < x < self._SCAL / 2.0: numeratori = 2.0 * self._N * ( 2 * (self._rs * dawsn(self._rs / 2.0) - 1 + np.exp(-self._S * x * (1 - x)) * (1 - self._rs * dawsn(self._rs / 2.0 * (1.0 - 2.0 * x))))) else: if x > self._b: x = self._b integtilldenom = 2.0 * self._N * ( 2 * (self._rs * dawsn(self._rs / 2.0) - 1 + np.exp(-self._S * self._DENOMINATOR * (1 - self._DENOMINATOR)) * (1 - self._rs * dawsn(self._rs / 2.0 * (1.0 - 2.0 * self._DENOMINATOR))))) numeratori = 2.0 * self._rs * np.sqrt(np.pi) * np.exp( -self._S / 4.0) * (erfi(self._rs / 2.0 * (1.0 - self._SCAL)) - erfi(self._rs / 2.0 * (1.0 - 2.0 * x))) numeratori += integtilldenom return numeratori
def rho_EQ(Vs,D,V): Rv = np.copy(V) (vT,vR) = (1.0,0.0) tmpg = np.greater(V,vR) indp = (np.where(tmpg)) sqrtD = np.sqrt(D) np.seterr(all='ignore') try: intovT = special.dawsn((vT-Vs)/sqrtD)*np.exp((vT-Vs)**2/D) intovSD = special.dawsn(-Vs/sqrtD)*np.exp(Vs**2/D) Rv[indp[0][:]] = -special.dawsn((V[indp[0][:]]-Vs)/sqrtD)+np.exp(-(V[indp[0][:]]-Vs)**2/D)*intovT if(indp[0][0]>1): Rv[0:indp[0][0]] = np.exp(-np.square(V[0:indp[0][0]]-Vs)/D)*(-intovSD + intovT) tmpl = np.less(V,-2.0/3.0) indp = np.where(tmpl) Rv[indp[0][:]] = 0.0 sum_c = (V[2]-V[1])*np.sum(Rv) Rv = Rv/sum_c except: sum_c = (V[2]-V[1])*np.sum(Rv) Rv = Rv/sum_c return (Rv,sum_c)
def error(self, f, a, fc, s): #, b): b = np.pi * (self.start - self.t0) * 1E-3 result = a * np.exp(-(s * b)**2) * np.imag( np.exp(-2j * (f - fc) * b) * sp.dawsn(-(f - fc) / s + 1j * s * b)) # This function often misbehaves while exploring parameter space. # Specifically, both np.exp(...) and np.imag(...) can blow up, but are supposed to (partially) cancel. # But it doesn't work out numerically, and we just get np.inf or np.nan. # I'd like an elegant solution to this problem, but for now just catch these errors. if (np.isinf(result)).any() or (np.isnan(result)).any(): return a return result
def presetAlphas(omegaV, alpha_free): dawsarg_1st = defs.T*(defs.delta_m[0] - omegaV) dawsarg_3rd = defs.T*(defs.delta_m[1] - omegaV) alpha1f = alphaOne(omegaV, -9.81535556e+00, 3.13975075e-01, 4.94111384e+02, 4.29958163e-01, -2.09667678e+00, 5.85035181e+00) alpha3f = alphaThree(omegaV,\ 3.26519717e-01, -3.86939149e-01, -6.38185123e+00, 9.69371148e+00, 6.33599497e-02, -1.60485987e-01, -1.36571022e-01, 1.15095946e-02, -7.15781666e-02) real_factor = (alpha1f*np.exp(-alpha_free*defs.T*defs.T*(defs.delta_m[0]-omegaV)\ *(defs.delta_m[0]-omegaV)))\ + (alpha3f * np.exp(-alpha_free* defs.T * defs.T *\ (defs.delta_m[1]-omegaV)*(defs.delta_m[1]-omegaV))) imag_factor = (alpha1f*(-2*cmath.sqrt(-1))/\ (np.sqrt(np.pi))*spcl.dawsn(np.sqrt(alpha_free)*dawsarg_1st)) + \ (alpha3f*((-2*cmath.sqrt(-1))/\ (np.sqrt(np.pi)))*spcl.dawsn(np.sqrt(alpha_free)*dawsarg_3rd)) domegaV = np.gradient(omegaV) phase_fit = np.arctan(np.imag(imag_factor)/np.real(real_factor)) dphi_fit = np.gradient(phase_fit, domegaV) return dphi_fit
def _kg(self, x, w, Gau_delta): ''' auxiliary component for a static Gaussian Kubo Toyabe in longitudinal field, x [mus], w [mus-1], Gau_delta [mus-1] w = 2*pi*gamma_mu*L_field ''' Dt = Gau_delta * x DDtt = Dt**2 DD = Gau_delta**2 sqr2 = sqrt(2) argf = w / (sqr2 * Gau_delta) fdc = dawsn(argf) wx = w * x if (w != 0): # non-vanishing Longitudinal Field Aa = real( exp(-0.5 * DDtt + 1j * wx) * dawsn(-argf - 1j * Dt / sqr2)) Aa[Aa == inf] = 0 # bi-empirical fix nan_to_num(Aa, copy=False) # empirical fix A = sqr2 * (Aa + fdc) f = 1. - 2. * DD / w**2 * (1 - exp(-.5 * DDtt) * cos(wx)) + 2. * ( Gau_delta / w)**3 * A else: f = (1. + 2. * (1 - DDtt) * exp(-.5 * DDtt)) / 3. return f
def _kg(self, t, w, Δ): ''' auxiliary component for a static Gaussian Kubo Toyabe in longitudinal field, t [mus], w [mus-1], Δ [mus-1], note that t can be different from self._x_ w = 2*pi*gamma_mu*L_field ''' Dt = Δ * t DDtt = Dt**2 DD = Δ**2 sqr2 = sqrt(2) argf = w / (sqr2 * Δ) fdc = dawsn(argf) wt = w * t if (w != 0): # non-vanishing Longitudinal Field Aa = real( exp(-0.5 * DDtt + 1j * wt) * dawsn(-argf - 1j * Dt / sqr2)) Aa[Aa == inf] = 0 # bi-empirical fix nan_to_num(Aa, copy=False) # empirical fix A = sqr2 * (Aa + fdc) f = 1. - 2. * DD / w**2 * (1 - exp(-.5 * DDtt) * cos(wt)) + 2. * ( Δ / w)**3 * A else: f = (1. + 2. * (1 - DDtt) * exp(-.5 * DDtt)) / 3. return f
def gaussian1d_complex(x,h,a,dx,fwhm): """Return a 1D gaussian given a set of parameters. :param x: Array giving the positions where the gaussian is evaluated :param h: Height :param a: Amplitude :param dx: Position of the center :param fwhm: FWHM, :math:`\\text{FWHM} = \\text{Width} \\times 2 \\sqrt{2 \\ln 2}` """ if not isinstance(x, np.ndarray): x = np.array(x) w = fwhm / (2. * gvar.sqrt(2. * gvar.log(2.))) b = (x - dx) / (np.sqrt(2) * w) return (h + a * gvar.exp(-b**2.), h + a * 2 / np.sqrt(np.pi) * special.dawsn(b))
def int_exact(self, X): '''Integral of the 2nd order Dawson function (with a change of order of integration)''' q = np.zeros(X.size) i = 0 fun1 = lambda x: np.power(erfcx(-x), 2) * dawsn(x) fun2 = lambda x: np.exp(-x * x) * np.power(erfcx(-x), 2) for x in X: if x < -25: #== -np.inf: q[i] = self.int_asym_neginf(x) else: y1, _ = quad(fun1, -np.inf, x) y2, _ = quad(fun2, -np.inf, x) q[i] = -np.pi / 4 * y1 + np.power(np.sqrt(np.pi) / 2, 3) * erfi(x) * y2 i += 1 return q
def Daws(x, n, method): if method == 'Trap': #apply Trapezoidal method integral_real = Trap(expo, 0, x, n) return np.exp(-x**2) * integral_real elif method == 'Simp': #apply Simpsons method integral_real = Simp(expo, 0, x, n) return np.exp(-x**2) * integral_real elif method == 'Scipy': #use scipy library return special.dawsn(x) else: return 'Input error :D'
def _pdf_k32(self, r, f, x, j): # PDF of k^3/2 g = self.mod.g x13 = x**(1. / 3) x23 = x**(2. / 3) sig2fac = self.mod.s2 / self.mod.s2j[j] E = (f - x23) * sig2fac c = (x > 0) func = numpy.zeros(len(x)) if (sum(c) > 0): if (self.ani): p = r / self.mod.raj[j] F = dawsn(x13 * p * sqrt(sig2fac)) / p func[c] = F[c] / (x13[c] * sqrt(sig2fac)) * self._Eg(E[c], g) else: func[c] = self._Eg(E[c], g) if (sum(~c) > 0): func[~c] = self._Eg(E[~c], g) return func
def animated_point_source_in_room(): from scipy.special import dawsn N = 128 x = np.linspace(-2, 2, N + 1)[:-1] + 0j dx = np.real(x[1] - x[0]) M = N // 2 y = z = x x, y, z = np.meshgrid(x, y, z, indexing='ij') # Inwards surging spherical wave with a gaussian profile # TODO: Figure out how to do an actual point source r = np.sqrt(x * x + y * y + z * z) r1 = 20 * r - 15 u = -(np.exp(-r1**2) + 2j / np.sqrt(np.pi) * dawsn(r1)) / (r + 1) boundary = 0 * x wave_equation = WaveEquation(u, boundary, dx, dt=dx, decay=0) u = wave_equation.u[:, :, M] plots = [ pylab.imshow(np.real(u), vmin=-0.05, vmax=0.05, extent=(-2, 2, -2, 2)) ] plots.extend(pylab.plot(np.linspace(-2, 2, N), np.real(u[M]))) plots.extend(pylab.plot(np.linspace(-2, 2, N), np.imag(u[M]))) def update(frame): wave_equation.step() print(wave_equation.t) u = wave_equation.u[:, :, M] plots[0].set_data(np.real(u)) plots[1].set_ydata(np.real(u[M])) plots[2].set_ydata(np.imag(u[M])) return plots FuncAnimation(pylab.gcf(), update, frames=range(18), init_func=lambda: plots, blit=True, repeat=True, interval=20) pylab.show()
def k_0_H(x, ker_opts): # parameters: sigma_SB = ker_opts['sigma_SB'] # prefactor ell = ker_opts['ell'] # lengthscale SB_ker_type = ker_opts['SB_ker_type'] # type of kernel used a = 1. / (sqrt(2) * ell) * x # inverse quadratic kernel if SB_ker_type == 'IQ': out_val = -a / (1. + a**2) # squared exponential kernel elif SB_ker_type == 'SE': out_val = 2. / sqrt(pi) * dawsn(a) # multiply by prefactor out_val = (sigma_SB**2) * out_val return out_val
def _pdf_k32(self, r, f, x, j): # PDF of k^3/2 g = self.mod.g x13 = x**(1./3) x23 = x**(2./3) sig2fac = self.mod.s2/self.mod.s2j[j] E = (f-x23)*sig2fac c = (x>0) func = numpy.zeros(len(x)) if (sum(c)>0): if (self.ani): p = r/self.mod.raj[j] F = dawsn(x13*p*sqrt(sig2fac))/p func[c] = F[c]/(x13[c]*sqrt(sig2fac))*self._Eg(E[c],g) else: func[c] = self._Eg(E[c],g) if (sum(~c)>0): func[~c] = self._Eg(E[~c],g) return func
def sincgauss1d_flux(a, fwhm, sigma): """Compute flux of a 1D sinc convoluted with a Gaussian of parameter sigma. :param a: Amplitude :param fwhm: FWHM of the sinc :param sigma: Sigma of the gaussian :param no_err: (Optional) No error is returned (default False) """ if np.all(np.isnan(gvar.mean(sigma))) or np.all(np.isclose(gvar.mean(sigma), 0)): return sinc1d_flux(a, fwhm) width = fwhm / orb.constants.FWHM_SINC_COEFF width /= math.pi def compute_flux(ia, isig, iwid): idia = orb.cgvar.dawsni(isig / (math.sqrt(2) * iwid)) expa2 = gvar.exp(isig**2./2./iwid**2.) if not np.isclose(gvar.mean(idia),0): return ia * math.pi / math.sqrt(2.) * isig * expa2 / idia else: return gvar.gvar(np.inf, np.inf) try: _A = sigma / (np.sqrt(2) * width) dia = special.dawsn(1j*_A) expa2 = np.exp(_A**2.) return (a * np.pi / np.sqrt(2.) * 1j * sigma * expa2 / dia).real except TypeError: pass if isinstance(a, np.ndarray): result = np.empty_like(a) for i in range(np.size(a)): result.flat[i] = compute_flux( a.flat[i], sigma.flat[i], width.flat[i]) else: result = compute_flux(a, sigma, width) return result
""" Question 2a Authors: Genevieve Beauregard (Primary), Anna Shirlkalina """ import numpy as np import scipy.optimize as spop import matplotlib.pyplot as plt from scipy import special import Lab2_functions as func from time import time #Question 2a N = 8 x = 4 print("Dawsons actual=>", special.dawsn(4)) print("") print("For N =", N, ",") print("Our trap Dawson =>", func.D_trap(x, N)) print("Our simp Dawson =>", func.D_simp(x, N)) print("") # Uncomment the below to get the error of for N slices # N2b_trap= 2**(2) # error = abs(special.dawsn(4) - func.D_trap(x, N2b_trap)) # print("For N =", N2b_trap) # print("Our trap Dawson =>", func.D_trap(x, N2b_trap)) # print("Error =", error)
i_log_q = 1 / log(q) a = pi_squared * i_log_q b = exp(a) b4 = b ** 4 c = 0.5 * sqrt(-pi * i_log_q) return 2 / sqrt(pi) * sum(dawson(sqrt(-a) * (t - n)) for n in range(-10, 11)) * c / ((1 + 2 * (b + b4)) * c - 0.5) theta_c = theta_complement xs = [i * 0.0001 for i in range(3000)] print max(abs(dawson(x) - dawsn(x)) for x in xs) def float_list_to_bytes(l): bs = bytearray() for f in l: mantissa, exponent = frexp(f) mantissa = int(mantissa * 256 ** 6) exponent = max(0, min(255, exponent + 128)) bs.extend(mantissa.to_bytes(6, 'big')) bs.append(exponent) return bytes(bs) bs = float_list_to_bytes([1,2,3,6.45,23.231]) import zlib
def DI(a): return dawsn(a)
def isomer(aaiso, ciso, conj, conq, coniso, dii, drrho, drrhoh, eergi, egiso, exki, fciso, ffiso, fjh, fregi, niso, ngrpi, ndr, nt, ngroup, q, qh, rho, rhoh, r, rerg, rgisoi, rootki, soriso, tau): tiso = tau - ciso #IF (TISO) 10, 20, 20 #10 if (tiso < 0): #RETURN return rtiso = math.sqrt(tiso) #20 l = 1 while (l < niso): exki[l-1] = math.exp(-tiso*dii[l-1]) #Changed [l] to [l-1] because Python arrays start at 1. rtkii[l-1] = math.sqrt(tiso*dii[l-1]) #Changed [l] to [l-1] soriso[l-1] = ai[l-1]*exxi[l-1] #Changed [l] to [l-1] l += 1 #CONTINUE end while loop #30 i = 1 j = 1 k = 1 l = 1 while (i < ndr): #ENDS AT 220 ri = 1/r[i-1] #Changed [i] to [i-1] r2i = ri * ri cj = conj * r2i cq = conq * r2i while (j < nt): #ENDS AT 140 cur = 0.0 qrh = 0.0 cqh = cq * rhoh[i-1][j-1] #Changed [i] and [j] to [i-1] [j-1] avrad = drrhoh[i-1][j-1] * ri #Changed [i] and [j] to [i-1] [j-1] while (k < ngroup): #ENDS AT 130 gmfp = drrhoh[i-1][j-1] * rgisoi[k-1] #Changed [x] to [x-1] emfp = math.exp(-gmfp) facto = fciso[k-1] + ffiso[k-1] * gmfp #Changed [x] to [x-1] consj = cj * rergi[k-1] * emfp #Changed [x] to [x-1] consq = cqh * eergi[k-1] * emfp #Changed [x] to [x-1] aj = avrad * 20550000 * math.sqrt(gmfp) ah = (1.186 - 0.062 * egiso[k-1]) * aj #Changed [x] to [x-1] fkj = factor * 10000/(1.0+bbiso[k-1]*gmfp) #Changed [x] to [x-1] fkq = facto * 10000/(1.1+aaiso[k-1]*gmfp) #Changed [x] to [x-1] exfkj = math.sqrt(-rtiso*fkj) exkfg = math.sqrt(-rtiso*fkq) while (l < niso): #ENDS AT 120 cifkj = rootki[l-1] * fkj #Changed [x] to [x-1] cifkg = rootki[l-1] * fkq #Changed [x] to [x-1] xj1 = cifkj * 0.5 xq1 = cifkq * 0.5 cixj = xj1**2 # xj1 squared cixq = xq1**2 # xq1 squared excixj = math.exp(-cixj) excixq = math.exp(cixq) daj = exfkj - exki[l-1] #Changed [x] to [x-1] daq = exfkq - exki[l-1] #Changed [x] to [x-1] daj = aj * coniso[l-1] * daj #Changed [x] to [x-1] daq = ah * coniso[l-1] * daq #Changed [x] to [x-1] dbj = cifkj * exki[l-1] * excixj * aj * coniso[l-1] #Changed [x] to [x-1] dbq = cifkq * exki[l-1] * excixg * ah * coniso[l-1] #Changed [x] to [x-1] xj2 = rtkii[l-1] - xj1 #Changed [x] to [x-1] xq2 = rtkii[l-1] - xq1 #Changed [x] to [x-1] # if (xj2) 40, 50, 60 # go to 40 if neg, go to 50 if 0, go to 60 if positive if (xj2 < 0): #if neg xj2 = -xj2 #40 # CALLING dawsn FUNCTIONS. wasn't sure where these would be, so I'm just calling special.METHODNAME convj = daj + dbj * (special.dawsn(xj1) - special.dawsn(xj2)) #GOTO 70 elif (xj2 == 0): convj = daj + dbj * special.dawsn(xj1) #50 #GO TO 70 else: #elif (xj2 > 0) convj = daj + dbj * special.dawsn(xj1) + special.dawsn(xj2) #60 #CONTINUE #70 if (xq2 < 0): xq2 = -xq2 #80 convq = daq + dbq * (special.dawsn(xq1) - special.dawsn(xq2)) #GO TO 110 elif (xq2 == 0): convq = daq + dbq * special.dawsn(xq1) #90 #GO TO 110 else: #elif (xq2 > 0): convq = daq + dbq * (special.dawsn(xq1) + special.dawsn(xq2))#100 #CONTINUE #110 cur = (convj + soriso[l-1]) * consj * fregi[k-1] + cur #Changed [x] to [x-1] qrh = (convq + soriso[l-1]) * consq * fregi[k-1] + qrh #Changed [x] to [x-1] l += 1 #CONTINUE end while loop l #120 k += 1 # CONTINUE end while loop k #130 fjh[i-1][j-1] = cur + fjh[i-1][j-1] #Changed [x] to [x-1] qh[i-1][j-1] = qrh + qh[i-1][j-1] #Changed [x] to [x-1] j += 1 #CONTINUE end while loop j #140 j = 1 k = 1 l = 1 while (j < ntm1): #ENDS AT 210 qrg = 0.0 cqg = cq * rho[i-1][j-1] #Changed [x] to [x-1] avrad = drrho[i-1][j-1] * ri #Changed [x] to [x-1] while (k < ngrpi): #ENDS AT 200 gmfp = drrho[i-1][j-1] * rgisoi[k-1] #Changed [x] to [x-1] facto = fciso[k-1] + ffiso[k-1] + gmfp #Changed [x] to [x-1] consg = cqg * eergi[k-1] * exp(-gmfp) #Changed [x] to [x-1] ag = avrad * (1.186 - 0.062 * egiso[k-1]) * 20550000 * math.sqrt(gmfp) #Changed [x] to [x-1] fkg = facto * 10000/(1.1+aaiso[k-1] * gmfp) #Changed [x] to [x-1] exfkg = math.exp(-rtiso * fkg) while (l < niso): #ENDS AT 190 cifkg = rootki[l-0] * fkg #Changed [x] to [x-1] xg1 = cifkg * 0.5 cixg = xg1**2 excixg = math.exp(-cixg) dag = exfkg - exki[l-1] #Changed [x] to [x-1] dag = ag * coniso[l-1] * dag #Changed [x] to [x-1] dbg = cifkg * exki[l-1] * excixg * ag * coniso[l-1] #Changed [x] to [x-1] xg2 = rtkii[l-1] - xg1 #Changed [x] to [x-1] # if (xg2) 150, 160, 170 # go to 150 if neg, go to 160 if 0, go to 170 if positive if (xg2 < 0): xg2 = -xg2 #150 convg = dag + dbg * \ (special.dawsn(xg1) - special.dawsn(xg2)) #GO TO 180 elif (xg2 == 0): convg = dag + dbg * special.dawsn(xg1) #160 #GO TO 180 else: #elif (xg2 > 0) convg = dag + dbg * (special.dawsn(xg1) + special.dawsn(xg2)) #170 # CONTINUE end if/else #180 qrg = (convg + soriso[l-1]) * consg * fregi[k-1] + qrg #Changed [x] to [x-1] l += 1 #CONTINUE end while loop l #190 k += 1 #CONTINUE end while loop k #200 q[i-1][j-1] = qrg + q[i-1][j-1] #Changed [x] to [x-1] j += 1 #CONTINUE end while loop j #210 i += 1
start = time() for _ in range(n): func() end = time() return (end - start) / n if __name__ == "__main__": dawson_traprule = lambda x, N: np.exp(-1 * x**2) * traprule( 0, x, lambda t: np.exp(t**2), N) dawson_simprule = lambda x, N: np.exp(-1 * x**2) * simprule( 0, x, lambda t: np.exp(t**2), N) print("Q2a i:") print("Trapezoid Rule:", dawson_traprule(4, 8)) print("Simpson's Rule:", dawson_simprule(4, 8)) print("Exact Value:", scis.dawsn(4)) print("") print("Q2a ii:") Nt = 200000 Ns = 1000 print("Trapezoid Rule Error: ", dawson_traprule(4, Nt) - scis.dawsn(4)) print("Number of Slices:", Nt) print("Simpson's Rule Error:", dawson_simprule(4, Ns) - scis.dawsn(4)) print("Number of Slices:", Ns) print("Traprule Time (s):", time_code(lambda: dawson_traprule(4, Nt), 10)) print("Simprule Time (s):", time_code(lambda: dawson_simprule(4, Ns), 10)) print("Scipy Function Time (s):", time_code(lambda: scis.dawsn(4), 1000)) print("")
def get(self, x, x0): from scipy.special import dawsn return 0.5 / x0 * (2 * self.wm1 * (dawsn((x + x0) * self.wm1) - dawsn( (x - x0) * self.wm1)) - 1.0j * self.norm * (np.exp(-( (x + x0) * self.wm1)**2) - np.exp(-((x - x0) * self.wm1)**2)))
def numpy_dawsn(x): return dawsn(x)