def D_prec(R0, phi0, epsilon, sig, z): D565, grad565 = sp.pbdv(-0.565, -((R0 - z)/sig)) D1565, grad1565 = sp.pbdv(-1.565, -((R0 - z)/sig)) frontfac = ((np.exp( (-(R0 - z)**2)/(4.0*(sig**2))) * (sig**0.565))/(1.0 + 0.012*R0))*phi0 bracfac = 11.26*D565/sig + ((0.157 + 11.26*epsilon)/R0)*D1565 return frontfac * bracfac * toGray
def D_prec(R0, phi0, epsilon, sig, z): D565, grad565 = sp.pbdv(-0.565, -((R0 - z) / sig)) D1565, grad1565 = sp.pbdv(-1.565, -((R0 - z) / sig)) frontfac = ((np.exp((-(R0 - z)**2) / (4.0 * (sig**2))) * (sig**0.565)) / (1.0 + 0.012 * R0)) * phi0 bracfac = 11.26 * D565 / sig + ((0.157 + 11.26 * epsilon) / R0) * D1565 return frontfac * bracfac * toGray
def _expected_E_FW_acen(eobs_sq, sig_eobs_sq): ''' First moment of the expected E distribution i.e. <E>''' from math import sqrt, pi, exp CROSSOVER1 = -12.5 CROSSOVER2 = 18 x = (eobs_sq - sig_eobs_sq**2) / sig_eobs_sq xsqr = x**2 if x < CROSSOVER1: # Large negative argument: asymptotic approximation e_xpct = sqrt(-pi * sig_eobs_sq / x) * ( (-916620705 + xsqr * (91891800 + xsqr * (-11531520 + xsqr * (1935360 + xsqr * (-491520 + xsqr * 262144))))) / (-495452160 + xsqr * (55050240 + xsqr * (-7864320 + xsqr * (1572864 + xsqr * (-524288 + xsqr * 524288)))))) elif x > CROSSOVER2: # Large positive argument: asymptotic approximation e_xpct = sqrt(sig_eobs_sq) * ((-45045 + 32 * xsqr * (-315 + 8 * xsqr * (-15 - 16 * xsqr + 128 * xsqr**2))) / (32768 * x**7.5)) else: from scipy.special import pbdv, erfc # parabolic cylinder function D, complementary error function e_xpct = ( sqrt(sig_eobs_sq / 2) * exp(-xsqr / 4) * pbdv(-1.5, -x)[0] / # Scipy parabolic cylinder function returns value *and* derivative erfc(-x / sqrt(2))) return e_xpct
def cal_bragg_straggle(E, z, straggle): """ Calculates the Bragg peak based on the Bortfeld equation considering range straggling. This uses parabolic cylinder function, which is a fit to the Gaussian convolution with non-straggled curve (Bortfeld). :param E: scalar. Initial beam energy in MeV. :param z: a numpy array of positions to calculate the dose. The unit is centimeter. :param straggle: scalar. Initial energy sigma in MeV. :return: (dose, index of bragg peak: the maximum value of the dose vector) """ p = 1.77 # Unitless alpha = 2.2e-3 # Unitless g = 0.6 # Unitless beta = 0.012 # 1 / cm phiIN = 0.0001 # Primary fluence # phiIN = 0.1 rho = 1.00 # gm / cm3(Mass density of the medium) R = alpha * E**p # cm(Range, neglecting straggling) sigmamono = 0.012 * ( R**0.935 ) # 2nd March, remember to test with or without brackets same result. sigmaEzero = straggle sigmatotal = np.sqrt(sigmamono**2 + (sigmaEzero**2) * (alpha**2) * (p**2) * (E**(2 * p - 2))) eta = (R - z) * 1. / sigmatotal epsilon = 0.0 # print 'eta = ', eta pdd = [] denom = np.sqrt(2 * np.pi) * rho * p * (alpha**(1 / p)) * (1 + beta * R) for zd in eta: para1 = pbdv(-1 / p, -zd)[0] para2 = pbdv(-1 / p - 1, -zd)[0] numerator = phiIN * (np.exp(-(zd**2) / 4) * (sigmatotal**(1 / p)) * gamma(1 / p)) add1 = 1. / sigmatotal * para1 add2 = (beta / p + g * beta + epsilon / R) * para2 pdd_zd = (numerator / denom) * (add1 + add2) pdd.append(pdd_zd) pdd = np.array(pdd) dose_nostraggle, _ = cal_bragg_nostraggle(E=E, z=z) nan_index = np.argwhere(~np.isfinite(pdd)) pdd[nan_index] = dose_nostraggle[nan_index] return pdd, np.argmax(pdd)
def D(R0, phi0, epsilon, sig, z): """ This is the very specialised equation for water only. It's equation 28/29 in the paper """ if z < (R0 - 10*sig): fac = (phi0)/(1.0 + 0.012*R0) term1 = 17.93*((R0 - z)**-0.435) term2 = ((0.444 + 31.7*epsilon)/R0)*((R0-z)**0.565) return fac*(term1 + term2) * toGray elif z < (R0 + 5*sig): D565, grad565 = sp.pbdv(-0.565, -((R0 - z)/sig)) D1565, grad1565 = sp.pbdv(-1.565, -((R0 - z)/sig)) frontfac = ((np.exp( (-(R0 - z)**2)/(4.0*(sig**2))) * (sig**0.565))/(1.0 + 0.012*R0))*phi0 bracfac = 11.26*D565/sig + ((0.157 + 11.26*epsilon)/R0)*D1565 return frontfac * bracfac * toGray else: return 0.0
def D(R0, phi0, epsilon, sig, z): """ This is the very specialised equation for water only. It's equation 28/29 in the paper """ if z < (R0 - 10 * sig): fac = (phi0) / (1.0 + 0.012 * R0) term1 = 17.93 * ((R0 - z)**-0.435) term2 = ((0.444 + 31.7 * epsilon) / R0) * ((R0 - z)**0.565) return fac * (term1 + term2) * toGray elif z < (R0 + 5 * sig): D565, grad565 = sp.pbdv(-0.565, -((R0 - z) / sig)) D1565, grad1565 = sp.pbdv(-1.565, -((R0 - z) / sig)) frontfac = ((np.exp((-(R0 - z)**2) / (4.0 * (sig**2))) * (sig**0.565)) / (1.0 + 0.012 * R0)) * phi0 bracfac = 11.26 * D565 / sig + ((0.157 + 11.26 * epsilon) / R0) * D1565 return frontfac * bracfac * toGray else: return 0.0
def _expected_E_FW_cen(eobs_sq, sig_eobs_sq): ''' First moment of the expected E distribution i.e. <E>''' CROSSOVER1 = -17.5 CROSSOVER2 = 17.5 from math import pi, sqrt x = sig_eobs_sq / 2 - eobs_sq / sig_eobs_sq xsqr = x**2 if x < CROSSOVER1: pcd_ratio = ((1024 * sqrt(pi) * (-x)**6.5) / (3465 + xsqr * (840 + xsqr * (384 + xsqr * 1024)))) elif x > CROSSOVER2: pcd_ratio = ((3440640 + xsqr * (-491520 + xsqr * (98304 + xsqr * (-32768 + xsqr * 32768)))) / (675675 + xsqr * (-110880 + xsqr * (26880 + xsqr * (-12288 + xsqr * 32768))))) / sqrt(x) else: from scipy.special import pbdv pcd_ratio = pbdv(-1, x)[0] / pbdv(-0.5, x)[0] e_xpct = sqrt(sig_eobs_sq / pi) * pcd_ratio return e_xpct
def _expected_Esq_FW_cen(eobs_sq, sig_eobs_sq): ''' Second moment of the expected E distribution, i.e. <E**2> ''' CROSSOVER1 = -17.5 CROSSOVER2 = 17.5 x = sig_eobs_sq / 2 - eobs_sq / sig_eobs_sq xsqr = x**2 if x < CROSSOVER1: pcd_ratio = ((45045 + xsqr * (10080 + xsqr * (3840 + xsqr * (4096 - xsqr * 32768)))) / (x * (55440 + xsqr * (13440 + xsqr * (6144 + xsqr * 16384))))) elif x > CROSSOVER2: pcd_ratio = ((11486475 + xsqr * (-1441440 + xsqr * (241920 + xsqr * (-61440 + xsqr * 32768)))) / (x * (675675 + xsqr * (-110880 + xsqr * (26880 + xsqr * (-12288 + xsqr * 32768)))))) else: from scipy.special import pbdv pcd_ratio = pbdv(-1.5, x)[0] / pbdv(-0.5, x)[0] esq_xpct = sig_eobs_sq * pcd_ratio / 2 return esq_xpct
def calcAutoconversionIntegral(muChi,sigmaChi,muNcn,sigmaNcn,rhoChiNcn,alpha,beta): """Calculate the Khairoutdinov-Kogan autoconversion rate, upscaled over a single normal-lognormal PDF.""" from scipy.special import gamma, pbdv from math import sqrt, exp, pi sC = muChi/sigmaChi + rhoChiNcn*sigmaNcn*beta # sC = muChi/sigmaChi - rhoChiNcn*sigmaNcn*beta (parabCylFnc, parabCylDer) = pbdv(-alpha-1,-sC) # (parabCylFnc, parabCylDer) = pbdv(-alpha-1,sC) analyticIntegral = (1/sqrt(2*pi))*(sigmaChi**alpha) \ *exp(muNcn*beta + 0.5*(sigmaNcn*beta)**2 - 0.25*sC**2) \ *gamma(alpha+1)*parabCylFnc # pdb.set_trace() return analyticIntegral
def pcfd(v, x): return sc.pbdv(v, x)[0]
from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt from scipy import special import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = special.pbdv(0, R) Z = Z[0] surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_zlim(None, None) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
def write_report(self, data, interaction, dimensions, density, temperature): """Genertes a report in a *.txt file""" if interaction == 1: if not os.path.exists("ideal_gas"): os.mkdir("ideal_gas") f_report = open("ideal_gas/report_{0}d_{1}.txt".format(dimensions, datetime.now()), "w") f_plot = open("ideal_gas/plot_{0}d.cvs".format(dimensions, density), "a") avg_temp = self.calculate_average(data, "T") avg_pres = self.calculate_average(data, "P") avg_density = avg_pres/avg_temp error_density = (abs(density-avg_density)/density)*100 f_report.write("REPORT " + str(datetime.now()) + "\n" + "-----------------------------------------" + "\n" + "CONFIGURATION:" + "\n" + "Interaction -> Ideal Gas" + "\n" "Dimensions -> " + str(dimensions) + "\n" "Steps = " + str(MEASUREMENT_STEPS) + "\n" + "Density = " + str(density) + "\n" + "Temperature = " + str(temperature) + "\n" + "-----------------------------------------" + "\n" + "SIMULATION RESULTS:" + "\n" + "Temperature (Average) = " + str(avg_temp) + "\n" + "Pressure (Average) = " + str(avg_pres) + "\n" + "Density (Average) = " + str(avg_density) + "\n"+ "Density Error (%) = "+ str(error_density)) f_plot.write("{0}, {1}, {2} , {3}, {4}\n".format(avg_temp, avg_pres, avg_density, density, error_density)) if interaction == 2: if not os.path.exists("lennard_jones"): os.mkdir("lennard_jones") f_report = open("lennard_jones/report_{0}d_{1}.txt".format(dimensions, datetime.now()), "w") f_plot = open("lennard_jones/plot_{0}d.cvs".format(dimensions, density), "a") #kinetic_energy = self.calculate_average(data, "K") potential_energy = self.calculate_average(data, "V") total_energy = self.calculate_average(data, "E") avg_temp = self.calculate_average(data, "T") avg_pres = self.calculate_average(data, "P") hermite = ((pbdv(1/2., -(2/avg_temp)**(1/2.))[0])*2**(1/4.)* np.e**(.5/avg_temp)) B2 = (2/3.)*np.pi*(2*np.pi)**(1/2.)*(1/avg_temp)**(1/4.)*hermite virial_pres = density*avg_temp*(1 + density*B2) error_pres = (abs(virial_pres - avg_pres)/virial_pres)*100 f_report.write("REPORT " + str(datetime.now()) + "\n" + "-----------------------------------------" + "\n" + "CONFIGURATION:" + "\n" + "Interaction -> Lennard-Jones" + "\n" + "Dimensions -> " + str(dimensions) + "\n" + "Steps = " + str(MEASUREMENT_STEPS) + "\n" + "Density = " + str(density) + "\n" + "Temperature = " + str(temperature) + "\n" + "-----------------------------------------" + "\n" + "SIMULATION RESULTS:" + "\n" + "Temperature (Average) = " + str(avg_temp) + "\n" + "Second Virial Coefficient = " + str(B2) + "\n" + "Pressure (Average) = " + str(avg_pres) + "\n" + "Pressure (Virial) = " + str(virial_pres) + "\n" + "Pressure Error (%) = " + str(error_pres) + "\n" + "\n" + #"Kinetic energy average = " + str(kinetic_energy) + "\n" + "Potential energy average = " + str(potential_energy)+"\n"+ "Total energy average = " + str(total_energy) + "\n") f_plot.write("{0}, {1}, {2} , {3}, {4}\n".format(density, avg_temp, avg_pres, virial_pres, error_pres)) if interaction == 3: if not os.path.exists("pedestrian"): os.mkdir("pedestrian") f_report=open("pedestrian/report_{0}d_{1}.txt".format(dimensions, datetime.now()), "w") f_plot=open("pedestrian/plot_{0}d.cvs".format(dimensions, density), "a") kinetic_energy = self.calculate_average(data, "K") potential_energy = self.calculate_average(data, "V") total_energy = self.calculate_average(data, "E") avg_temp = self.calculate_average(data, "T") avg_pres = self.calculate_average(data, "P") B2 = 0. virial_pres = 1. error_pres = (abs(virial_pres - avg_pres)/virial_pres)*100 f_report.write("REPORT " + str(datetime.now()) + "\n" + "-----------------------------------------" + "\n" + "CONFIGURATION:" + "\n" + "Interaction -> Pedestrian" + "\n" + "Dimensions -> " + str(dimensions) + "\n" + "Steps = " + str(MEASUREMENT_STEPS) + "\n" + "Density = " + str(density) + "\n" + "Temperature = " + str(temperature) + "\n" + "-----------------------------------------" + "\n" + "SIMULATION RESULTS:" + "\n" + "Temperature (Average) = " + str(avg_temp) + "\n" + "Second Virial Coefficient = " + str(B2) + "\n" + "Pressure (Average) = " + str(avg_pres) + "\n" + "Pressure (Virial) = " + str(virial_pres) + "\n" + "Pressure Error (%) = " + str(error_pres) + "\n" + "\n" + "Kinetic energy average = " + str(kinetic_energy) + "\n" + "Potential energy average = " + str(potential_energy)+"\n"+ "Total energy average = " + str(total_energy) + "\n") f_plot.write("{0}, {1}, {2} , {3}, {4}\n".format(density, avg_temp, avg_pres, virial_pres, error_pres)) f_report.close() f_plot.close()