def generate_initial_velocities(atoms, m, T): v = [] for n in range(len(atoms)): a = np.sqrt((k[0] * T) / m[n]) transl_vec = np.full(3, maxwell(scale=a).stats('m') / 2) distr = maxwell.rvs(scale=a, size=3) v.append((distr - transl_vec) * 2) return np.array(v)
def quiver_desired_velocity(crStats\ ,further_conditioning = None ,grid_x=40,grid_y=40,small_incr=.00001\ ,qty='vel' ,spec_type='gt' ,img_format='png' ,**kw): x_class_v,y_class_v,u_means,v_means,u_delta,v_delta,u_all,v_all =\ sub_eval_desired_velocity_qtys(crStats ,further_conditioning\ ,grid_x,grid_y,small_incr\ ,qty\ ,spec_type) plt.figure() plt.hist2d(u_delta,v_delta,**hist2d_param) plt.title('Overall noise distribution') plt.savefig(PATH_PREFIX + 'total_noise_%s_%s.%s' % (qty,spec_type,img_format)) rv = maxwell() speed_delta = np.sqrt(np.asarray(u_delta)**2 + np.asarray(v_delta)**2) loc,scale = maxwell.fit(speed_delta) plt.figure() plt.hist(speed_delta,**hist_param_noLog) x = np.linspace(0,2,100) plt.plot(x,maxwell.pdf(x,scale=scale,loc=loc)) plt.title('Overall abs noise distribution') plt.savefig(PATH_PREFIX + 'maxwellian_noise_%s_%s.%s' % (qty,spec_type,img_format)) temperature = np.sqrt( np.asarray([np.var(us) for us in u_all]) + np.asarray([np.var(vs) for vs in v_all]) ) speed = [np.mean(np.sqrt(np.asarray(us)**2 + np.asarray(vs)**2)) for us,vs in zip(u_all,v_all) ] plt.figure() plt.quiver(x_class_v,y_class_v,u_means,v_means,temperature,**kw) plt.colorbar() plt.title('cross-realization "thermal" noise [m/s]') plt.xlabel('x [m]') plt.ylabel('y [m]') plt.savefig(PATH_PREFIX + 'quiver_thermal_noise_%s_%s.%s' % (qty,spec_type,img_format)) plt.figure() plt.quiver(x_class_v,y_class_v,u_means,v_means,speed,**kw) plt.colorbar() plt.title('average speed') plt.xlabel('x [m]') plt.ylabel('y [m]') plt.savefig(PATH_PREFIX + 'quiver_average_modulus_%s_%s.%s' % (qty,spec_type,img_format))
def plot_velocity_distribution(snap, temp): """ Plots histogram of atomic speeds against analytical Maxwell-Boltzman distribution for input temperature, ``temp``. Parameters ---------- snap : :class:`mdhandle.snap.Snap` :class:`~mdhandle.snap.Snap` object. temp : float Temperature for analytical Maxwell distribution Returns -------- 0 Successfully completed velocity distribution plot. -1 An error has occured and velocity distribution plot was not generated. """ kb = units.KBOLTZ[snap.meta['units']] speed = vectors.magnitude(snap.get_vector(('vx', 'vy', 'vz')))*\ units.VELOCITY[snap.meta['units']]**2 if np.unique(snap.get_scalar('mass')).size > 1: logger.warning('Cannot handle polyatomic system') return -1 # Taking mass as constant based on value at index 0 mass = snap.get_scalar('mass')[0]*units.MASS[snap.meta['units']] # See: <http://mathworld.wolfram.com/MaxwellDistribution.html> # Energy factor is applied to bring to SI units for calculation. # if metal or other unit system. a = np.sqrt(kb*temp/mass * units.ENERGY[snap.meta['units']]) scale = 1 / np.sqrt(a) # Maxwell-Boltzmann RV based on temperature maxwell_rv = maxwell(loc=0, scale=scale) x = np.linspace(0, np.minimum( maxwell_rv.dist.b, speed.max() )) # Plotting fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, maxwell_rv.pdf(x), linewidth=2) n, bins, patches = ax.hist(speed, 100, normed=True, facecolor='red', alpha=0.75) return 0
def maxwell_boltzmann(T, m, lengthscale=1): # Mean molecular weight if isinstance(m, numbers.Real): m *= atomic_mass # Temperature if isinstance(T, numbers.Real): T *= Kelvin if isinstance(lengthscale, numbers.Real): T *= meter # Maxwell-Boltzmann velocity distribution # velocity scale value in units of a per sec vscale = (np.sqrt(k_B * T.si / m.si) / lengthscale.si).to('/s') return maxwell(0, vscale.value)
def run(): min_long = np.pi / 12 max_long = 2 * np.pi - np.pi / 12 LongitudeGenerator = stats.uniform(loc=min_long, scale=max_long - min_long) # Generate, then freeze the distribution: min_lat = np.pi / 6 max_lat = np.pi / 4 LatitudeGenerator = math_operations.SphericalLatitudeGen(a=min_lat, b=max_lat)() n_points = 1000 theta_points = LongitudeGenerator.rvs(size=n_points) phi_points = LatitudeGenerator.rvs(size=n_points) points = math_operations.vect_from_spherical_coords( theta_points, phi_points) MyPointCloud = PointCloud(points, point_color="k", display_marker='.', point_size=4, linewidth=0, name="Uniformly distributed points") ax_dic = scatter_plot_3d(MyPointCloud, savefile='hold') set_3d_axes_equal(ax_dic['ax']) plt.legend() plt.show() # ============================================================= # max_val = 100 rv_gen_1 = stats.uniform(0, 10) random_walk_1 = math_operations.stochastic_flare_process( stop_value=max_val, distribution=rv_gen_1) plt.plot(random_walk_1, color='r', label="Uniform") rv_gen_2 = stats.maxwell(0, 3) random_walk_2 = math_operations.stochastic_flare_process( stop_value=max_val, distribution=rv_gen_2) plt.plot(random_walk_2, color='k', label='Maxwell') plt.legend() plt.show()
mean, var, skew, kurt = maxwell.stats(moments='mvsk') # Display the probability density function (``pdf``): x = np.linspace(maxwell.ppf(0.01), maxwell.ppf(0.99), 100) ax.plot(x, maxwell.pdf(x), 'r-', lw=5, alpha=0.6, label='maxwell pdf') # Alternatively, the distribution object can be called (as a function) # to fix the shape, location and scale parameters. This returns a "frozen" # RV object holding the given parameters fixed. # Freeze the distribution and display the frozen ``pdf``: rv = maxwell() ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') # Check accuracy of ``cdf`` and ``ppf``: vals = maxwell.ppf([0.001, 0.5, 0.999]) np.allclose([0.001, 0.5, 0.999], maxwell.cdf(vals)) # True # Generate random numbers: r = maxwell.rvs(size=1000) # And compare the histogram: ax.hist(r, density=True, histtype='stepfilled', alpha=0.2)
# -*- coding: UTF-8 -*- # Ejemplo de distrbuciones del módulo stats de Scipy import numpy as np import matplotlib.pyplot as plt from scipy.stats import cauchy, gamma, maxwell, norm SAMPLE_SIZE = 100 x = np.linspace(-5, 5, 1000) # Inicializo las distribuciones cauchy_dist = cauchy() gamma_dist = gamma(1, scale=2.) maxwell_dist = maxwell() norm_dist = norm() # Calculo la funcion de densidad de probabilidad de cada distribucion cauchy_pdf = cauchy_dist.pdf(x) gamma_pdf = gamma_dist.pdf(x) maxwell_pdf = maxwell_dist.pdf(x) norm_pdf = norm_dist.pdf(x) fig = plt.figure("Distribuciones") sp1 = fig.add_subplot(221, title='Distribucion de Cauchy') sp2 = fig.add_subplot(222, title='Distribucion Gamma') sp3 = fig.add_subplot(223, title='Distribucion de Maxwell') sp4 = fig.add_subplot(224, title='Distribucion Normal')
def all_dists(): # dists param were taken from scipy.stats official # documentaion examples # Total - 89 return { "alpha": stats.alpha(a=3.57, loc=0.0, scale=1.0), "anglit": stats.anglit(loc=0.0, scale=1.0), "arcsine": stats.arcsine(loc=0.0, scale=1.0), "beta": stats.beta(a=2.31, b=0.627, loc=0.0, scale=1.0), "betaprime": stats.betaprime(a=5, b=6, loc=0.0, scale=1.0), "bradford": stats.bradford(c=0.299, loc=0.0, scale=1.0), "burr": stats.burr(c=10.5, d=4.3, loc=0.0, scale=1.0), "cauchy": stats.cauchy(loc=0.0, scale=1.0), "chi": stats.chi(df=78, loc=0.0, scale=1.0), "chi2": stats.chi2(df=55, loc=0.0, scale=1.0), "cosine": stats.cosine(loc=0.0, scale=1.0), "dgamma": stats.dgamma(a=1.1, loc=0.0, scale=1.0), "dweibull": stats.dweibull(c=2.07, loc=0.0, scale=1.0), "erlang": stats.erlang(a=2, loc=0.0, scale=1.0), "expon": stats.expon(loc=0.0, scale=1.0), "exponnorm": stats.exponnorm(K=1.5, loc=0.0, scale=1.0), "exponweib": stats.exponweib(a=2.89, c=1.95, loc=0.0, scale=1.0), "exponpow": stats.exponpow(b=2.7, loc=0.0, scale=1.0), "f": stats.f(dfn=29, dfd=18, loc=0.0, scale=1.0), "fatiguelife": stats.fatiguelife(c=29, loc=0.0, scale=1.0), "fisk": stats.fisk(c=3.09, loc=0.0, scale=1.0), "foldcauchy": stats.foldcauchy(c=4.72, loc=0.0, scale=1.0), "foldnorm": stats.foldnorm(c=1.95, loc=0.0, scale=1.0), # "frechet_r": stats.frechet_r(c=1.89, loc=0.0, scale=1.0), # "frechet_l": stats.frechet_l(c=3.63, loc=0.0, scale=1.0), "genlogistic": stats.genlogistic(c=0.412, loc=0.0, scale=1.0), "genpareto": stats.genpareto(c=0.1, loc=0.0, scale=1.0), "gennorm": stats.gennorm(beta=1.3, loc=0.0, scale=1.0), "genexpon": stats.genexpon(a=9.13, b=16.2, c=3.28, loc=0.0, scale=1.0), "genextreme": stats.genextreme(c=-0.1, loc=0.0, scale=1.0), "gausshyper": stats.gausshyper(a=13.8, b=3.12, c=2.51, z=5.18, loc=0.0, scale=1.0), "gamma": stats.gamma(a=1.99, loc=0.0, scale=1.0), "gengamma": stats.gengamma(a=4.42, c=-3.12, loc=0.0, scale=1.0), "genhalflogistic": stats.genhalflogistic(c=0.773, loc=0.0, scale=1.0), "gilbrat": stats.gilbrat(loc=0.0, scale=1.0), "gompertz": stats.gompertz(c=0.947, loc=0.0, scale=1.0), "gumbel_r": stats.gumbel_r(loc=0.0, scale=1.0), "gumbel_l": stats.gumbel_l(loc=0.0, scale=1.0), "halfcauchy": stats.halfcauchy(loc=0.0, scale=1.0), "halflogistic": stats.halflogistic(loc=0.0, scale=1.0), "halfnorm": stats.halfnorm(loc=0.0, scale=1.0), "halfgennorm": stats.halfgennorm(beta=0.675, loc=0.0, scale=1.0), "hypsecant": stats.hypsecant(loc=0.0, scale=1.0), "invgamma": stats.invgamma(a=4.07, loc=0.0, scale=1.0), "invgauss": stats.invgauss(mu=0.145, loc=0.0, scale=1.0), "invweibull": stats.invweibull(c=10.6, loc=0.0, scale=1.0), "johnsonsb": stats.johnsonsb(a=4.32, b=3.18, loc=0.0, scale=1.0), "johnsonsu": stats.johnsonsu(a=2.55, b=2.25, loc=0.0, scale=1.0), "ksone": stats.ksone(n=1e03, loc=0.0, scale=1.0), "kstwobign": stats.kstwobign(loc=0.0, scale=1.0), "laplace": stats.laplace(loc=0.0, scale=1.0), "levy": stats.levy(loc=0.0, scale=1.0), "levy_l": stats.levy_l(loc=0.0, scale=1.0), "levy_stable": stats.levy_stable(alpha=0.357, beta=-0.675, loc=0.0, scale=1.0), "logistic": stats.logistic(loc=0.0, scale=1.0), "loggamma": stats.loggamma(c=0.414, loc=0.0, scale=1.0), "loglaplace": stats.loglaplace(c=3.25, loc=0.0, scale=1.0), "lognorm": stats.lognorm(s=0.954, loc=0.0, scale=1.0), "lomax": stats.lomax(c=1.88, loc=0.0, scale=1.0), "maxwell": stats.maxwell(loc=0.0, scale=1.0), "mielke": stats.mielke(k=10.4, s=3.6, loc=0.0, scale=1.0), "nakagami": stats.nakagami(nu=4.97, loc=0.0, scale=1.0), "ncx2": stats.ncx2(df=21, nc=1.06, loc=0.0, scale=1.0), "ncf": stats.ncf(dfn=27, dfd=27, nc=0.416, loc=0.0, scale=1.0), "nct": stats.nct(df=14, nc=0.24, loc=0.0, scale=1.0), "norm": stats.norm(loc=0.0, scale=1.0), "pareto": stats.pareto(b=2.62, loc=0.0, scale=1.0), "pearson3": stats.pearson3(skew=0.1, loc=0.0, scale=1.0), "powerlaw": stats.powerlaw(a=1.66, loc=0.0, scale=1.0), "powerlognorm": stats.powerlognorm(c=2.14, s=0.446, loc=0.0, scale=1.0), "powernorm": stats.powernorm(c=4.45, loc=0.0, scale=1.0), "rdist": stats.rdist(c=0.9, loc=0.0, scale=1.0), "reciprocal": stats.reciprocal(a=0.00623, b=1.01, loc=0.0, scale=1.0), "rayleigh": stats.rayleigh(loc=0.0, scale=1.0), "rice": stats.rice(b=0.775, loc=0.0, scale=1.0), "recipinvgauss": stats.recipinvgauss(mu=0.63, loc=0.0, scale=1.0), "semicircular": stats.semicircular(loc=0.0, scale=1.0), "t": stats.t(df=2.74, loc=0.0, scale=1.0), "triang": stats.triang(c=0.158, loc=0.0, scale=1.0), "truncexpon": stats.truncexpon(b=4.69, loc=0.0, scale=1.0), "truncnorm": stats.truncnorm(a=0.1, b=2, loc=0.0, scale=1.0), "tukeylambda": stats.tukeylambda(lam=3.13, loc=0.0, scale=1.0), "uniform": stats.uniform(loc=0.0, scale=1.0), "vonmises": stats.vonmises(kappa=3.99, loc=0.0, scale=1.0), "vonmises_line": stats.vonmises_line(kappa=3.99, loc=0.0, scale=1.0), "wald": stats.wald(loc=0.0, scale=1.0), "weibull_min": stats.weibull_min(c=1.79, loc=0.0, scale=1.0), "weibull_max": stats.weibull_max(c=2.87, loc=0.0, scale=1.0), "wrapcauchy": stats.wrapcauchy(c=0.0311, loc=0.0, scale=1.0), }
# Ejemplo de distrbuciones del módulo stats de Scipy import numpy as np import matplotlib.pyplot as plt from scipy.stats import cauchy, gamma, maxwell, norm SAMPLE_SIZE = 100 x = np.linspace(-5,5,1000) # Inicializo las distribuciones cauchy_dist = cauchy() gamma_dist = gamma(1, scale=2.) maxwell_dist = maxwell() norm_dist = norm() # Calculo la funcion de densidad de probabilidad de cada distribucion cauchy_pdf = cauchy_dist.pdf(x) gamma_pdf = gamma_dist.pdf(x) maxwell_pdf = maxwell_dist.pdf(x) norm_pdf = norm_dist.pdf(x) fig = plt.figure("Distribuciones") sp1 = fig.add_subplot(221, title='Distribucion de Cauchy') sp2 = fig.add_subplot(222, title='Distribucion Gamma') sp3 = fig.add_subplot(223, title='Distribucion de Maxwell') sp4 = fig.add_subplot(224, title='Distribucion Normal')