Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import print_function
- import numpy as np
- import datetime
- import espressomd
- from espressomd.pair_criteria import DistanceCriterion #required for cluster analysis
- from espressomd.observables import ParticleVelocities
- from espressomd.cluster_analysis import ClusterStructure #for cluster analysis
- from espressomd.accumulators import Correlator
- import espressomd.magnetostatics as magnetostatics
- espressomd.assert_features('DIPOLES', 'LENNARD_JONES', 'ROTATION')
- import tidynamics
- import matplotlib.pyplot as plt
- #helper functions
- from functions import combinationRuleEpsilon
- from functions import combinationRuleSigma
- from functions import averageClusterSize
- from functions import addParticles
- from vtf_files import _writevsf
- from vtf_files import _writevcf
- from scipy.optimize import curve_fit
- def func(x, a, b, c, d, e):
- return a * np.exp(-b * x) + c * np.sin(d * x) + e
- class ParticleType:
- def __init__(self, type, n, density, dipoleMoment, sigma, epsilon, cut):
- self.type = type
- self.n = n
- self.density = density
- self.dipoleMoment = dipoleMoment
- self.sigma = sigma
- self.epsilon = epsilon
- self.cut = cut
- def __str__(self):
- return "type: {}\tn: {}\tdensity: {}\tdipoleMoment: {}\tsigma: {}\tepsilon: {}\tcut: {:.4f}" \
- .format(self.type,self.n,self.density,self.dipoleMoment,self.sigma,self.epsilon,self.cut)
- def main():
- ################### Parameters start ###################
- # Simulation parameters
- densitySmall = 0.001
- densityLarge = 0.02
- sigmaSmall = 1. #Diameter of small particle | Definition needed here since multiple ParticleType members depend on it | * 10^-9m
- sigmaLarge = 2. #Diameter of large particle | Definition needed here since multiple ParticleType members depend on it | * 10^-9m
- dipoleMomentSmall = 3.
- dipoleMomentLarge = 3.
- settings = {"autocorrelation": True, \
- "densityAnalysis": False, \
- "vtf": False, \
- "dipoleAnalysis": False, \
- "radialDistribution": False,\
- "structureFactor": False }
- # System parameters
- nStepsEquil = 1000 #maximum amount of configs during equilibration
- nConfigs = 10 #Amount of Configurations to simulate in equilibrium (for averaging measurements)
- iStepsPerConfigEquil = 200 #integration steps between measurements during equilibration (energy)
- iStepsPerConfigAna = 200 #integration steps between measurements during Analysis (exluding autocorrelation)
- timeStep = 0.01
- temperature = 1.
- gamma = 1.
- #analysis parameters for multiple systems
- nCycles = 20
- dDensity = 0.04 #delta density | for densityAnalysis
- dMoment = 4. #delta dipole moment | for dipoleAnalysis
- iterateSmall = False
- iterateLarge = True
- if not settings["dipoleAnalysis"] and not settings["densityAnalysis"]: # only multiple runs if needed
- nCycles = 1
- #derived parameters / free parameters
- boxLength = 60
- boxVolume = np.power(boxLength,3)
- volumeSmall = np.pi/6.*np.power(sigmaSmall,3) #volume of small sphere
- volumeLarge = np.pi/6.*np.power(sigmaLarge,3) #volume of large sphere
- nSmall = int(densitySmall*boxVolume/volumeSmall) #amount of small particles
- nLarge = int(densityLarge*boxVolume/volumeLarge) #amount of large particles
- wcaCut = 2.**(1. / 6.) # ~1.13
- particleTypes = []
- small = ParticleType(type=0,n=nSmall,density=densitySmall,dipoleMoment=dipoleMomentSmall,sigma=sigmaSmall,epsilon=1,cut=wcaCut*sigmaSmall)
- particleTypes.append(small)
- large = ParticleType(type=1,n=nLarge,density=densityLarge,dipoleMoment=dipoleMomentLarge,sigma=sigmaLarge,epsilon=1,cut=wcaCut*sigmaLarge)
- particleTypes.append(large)
- nTypes = len(particleTypes)
- nParticles = sum(particleType.n for particleType in particleTypes)
- #analysis Parameters
- dc = DistanceCriterion(cut_off=particleTypes[1].cut) # cutoff big particle
- cs = ClusterStructure(pair_criterion=dc)
- ################### Parameters end ###################
- if settings["densityAnalysis"]:
- fpDensity = open('density{}.dat'.format(datetime.datetime.now()), mode="w+t")
- fpDensity.write("densitySmall, densityLarge, Amount of clusters, Avg. cluster size\n")
- if settings["dipoleAnalysis"]:
- fpDipole = open('dipole{}.dat'.format(datetime.datetime.now()), mode="w+t")
- fpDipole.write("dipoleMomentSmall, dipoleMomentLarge, Amount of clusters, Avg. cluster size\n")
- #init system #1
- system = espressomd.System(box_l=boxLength*np.ones(3))
- system.periodicity = [1, 1, 1] #periodic boundary condition in all directions
- system.time_step = timeStep
- # Lennard-Jones interaction (WCA Potential)
- for i in range(nTypes):
- for j in range(i,nTypes):
- lj_sig = combinationRuleSigma(particleTypes[i].sigma, particleTypes[j].sigma)
- lj_cut = combinationRuleSigma(particleTypes[i].cut, particleTypes[j].cut)
- lj_eps = combinationRuleEpsilon(particleTypes[i].epsilon, particleTypes[j].epsilon)
- system.non_bonded_inter[particleTypes[i].type, particleTypes[j].type].lennard_jones.set_params(
- epsilon=lj_eps, sigma=lj_sig, cutoff=lj_cut, shift="auto")
- for iCycle in range(nCycles):
- #init system #2
- system.seed = iCycle
- system.actors.clear()
- #system.seed = 42
- #init particles
- if system.part.n_part_types>0:
- system.part.clear()
- print("Particletypes:")
- for p in particleTypes : print(p)
- print("\n")
- addParticles(particleTypes,system)
- #print("nPart in system: ",system.number_of_particles(type=particleTypes[0].type))
- # Lennard Jones / WCA Equilibration - Cold, highly damped system
- minDistS = 0
- minDistL = 0
- minDistSL = 0
- cap = 1.0
- system.force_cap=cap
- system.thermostat.turn_off()
- system.thermostat.set_langevin(kT=temperature/10.0, gamma=gamma*5.0, seed=iCycle)
- while minDistS< particleTypes[0].sigma or minDistL<particleTypes[1].sigma or minDistSL<(particleTypes[0].sigma+particleTypes[1].sigma)/2.0:
- #Warmup Helper: Cap max. force, increase slowly for overlapping particles
- minDistS = system.analysis.min_dist([particleTypes[0].type],[particleTypes[0].type])
- minDistL = system.analysis.min_dist([particleTypes[1].type],[particleTypes[1].type])
- minDistSL = system.analysis.min_dist([particleTypes[0].type],[particleTypes[1].type])
- print(" - {:.2f}, {:.2f}, {:.2f}".format(minDistS,minDistL,minDistSL),end='\r')
- cap += min(minDistS,minDistL,minDistSL)
- system.force_cap=cap
- system.integrator.run(10)
- system.force_cap=0 #turn off force cap
- #print("adding magnetostatics to system...")
- p3m = magnetostatics.DipolarP3M(prefactor=1, accuracy=1E-4)
- system.actors.add(p3m)
- ################### Energy Equilibration start ###################
- print("Energy Equilibration ...")
- system.thermostat.set_langevin(kT=temperature, gamma=gamma)
- if settings["vtf"]:
- fpVtf = open('trajectoryEquilibration_{}.vtf'.format(datetime.datetime.now()), mode='w+t')
- _writevsf(system,fpVtf)
- energy = system.analysis.energy()
- energyOld = abs(energy['total'])
- for i in range(1,nStepsEquil*iStepsPerConfigEquil):
- if settings["vtf"]:
- _writevcf(system,fpVtf)
- system.integrator.run(1)
- if i%iStepsPerConfigEquil==0:
- temp_measured = energy["kinetic"] / (1.5 * nParticles)
- energy = system.analysis.energy()
- energyNew = abs(energy['total'])
- relativeChange = abs(energyNew-energyOld)/energyOld
- print(" - t={0:.1f}, E={1:.2f},T={2:.4f},dE={3:.3f}".format(system.time, energyNew, temp_measured,relativeChange),end='\r')
- if relativeChange < 0.03 and energy['total']<0: #if energy change is small enough it's time for analysis
- print("\n - Old Energy {} New Energy {}".format(energyOld,energyNew))
- print(" - Temp Equilibration: break condition reached!")
- break
- energyOld=energyNew
- if settings["vtf"]:
- fpVtf.close()
- ################### Energy Equilibration end ###################
- if settings["densityAnalysis"]:
- cs.run_for_all_pairs()
- fpDensity.write("{0:f}, {1:f}, {2:d}, {3:f}\n".format(particleTypes[0].density, particleTypes[1].density, len(cs.clusters),averageClusterSize(cs.clusters)))
- print(len(cs.clusters))
- if settings["dipoleAnalysis"]:
- cs.run_for_all_pairs()
- fpDipole.write("{0:f}, {1:f}, {2:d}, {3:f}\n".format(particleTypes[0].dipoleMoment,particleTypes[1].dipoleMoment,len(cs.clusters),averageClusterSize(cs.clusters)))
- # Integration
- if settings["vtf"]:
- fpVtf = open('trajectory_{}.vtf'.format(datetime.datetime.now()), mode='w+t')
- _writevsf(system,fpVtf)
- print("\nrunning simulation...")
- system.time = 0.0
- for i in range(nConfigs):
- print(" - {} out of {} configurations done".format(i+1, nConfigs), end='\r')
- system.integrator.run(iStepsPerConfigAna)
- if settings["radialDistribution"]: #only averaging here
- system.analysis.append()
- if settings["vtf"]:
- _writevcf(system,fpVtf)
- if settings["vtf"]:
- fpVtf.close()
- system.time_step = timeStep
- ################### Velocity autocorrelation start ###################
- if settings["autocorrelation"]:
- velObs = ParticleVelocities(ids=(0,))
- cVel = Correlator(obs1=velObs, delta_N=1, corr_operation="scalar_product", tau_max=20.,tau_lin=16, compress1="discard1")
- system.auto_update_accumulators.add(cVel)
- system.integrator.run(1000)
- cVel.finalize()
- print(cVel.result())
- #print(cVel.result().reshape([-1, 1]))
- plt.ylim([0,2])
- plt.plot(cVel.result()[:,0],cVel.result()[:,2],'bo')
- plt.xlabel('$t$', fontsize=20)
- plt.ylabel('$velocity autocorrelation$', fontsize=20)
- plt.show()
- ################### Velocity autocorrelation end ###################
- ################### Radial distribution start ###################
- if settings["radialDistribution"]:
- bins = 100
- rMin = 0.0
- rMax = system.box_l[0]/4.0
- r,rdfss = system.analysis.rdf(rdf_type='<rdf>',
- type_list_a=[particleTypes[0].type],
- type_list_b=[particleTypes[0].type],
- r_min=rMin,
- r_max=rMax,
- r_bins=bins)
- r,rdfsl = system.analysis.rdf(rdf_type='<rdf>',
- type_list_a=[particleTypes[0].type],
- type_list_b=[particleTypes[1].type],
- r_min=rMin, r_max=rMax, r_bins=bins)
- r,rdfll = system.analysis.rdf(rdf_type='<rdf>',
- type_list_a=[particleTypes[1].type],
- type_list_b=[particleTypes[1].type],
- r_min=rMin, r_max=rMax, r_bins=bins)
- plt.figure(figsize=(10,6), dpi=80)
- plt.plot(r[:],rdfss[:], label='Small')
- plt.plot(r[:],rdfsl[:], label='SmallLarge')
- plt.plot(r[:],rdfll[:], label='Large')
- plt.xlabel('$r$', fontsize=20)
- plt.ylabel('$g(r)$', fontsize=20)
- plt.legend(fontsize=20)
- plt.show()
- ################### Radial distribution end ###################
- ################### Structure factor start ###################
- if settings["structureFactor"]:
- qs,ss = system.analysis.structure_factor(sf_types=[particleTypes[0].type],sf_order=60)
- param, param_cov = curve_fit(func, qs, ss)
- yss = (param[0]*np.exp(-param[1] * qs) + param[2]*(np.sin(param[3]*qs)) + param[4])
- ql,sl = system.analysis.structure_factor(sf_types=[particleTypes[1].type],sf_order=60)
- param, param_cov = curve_fit(func, ql, sl)
- ysl = (param[0]*np.exp(-param[1] * ql) + param[2]*(np.sin(param[3]*ql)) + param[4])
- qsl,ssl = system.analysis.structure_factor(sf_types=[particleTypes[0].type,particleTypes[1].type],sf_order=60)
- param, param_cov = curve_fit(func, qsl, ssl)
- yssl = (param[0]*np.exp(-param[1] * qsl) + param[2]*(np.sin(param[3]*qsl)) + param[4])
- fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
- axs[0, 0].plot(qs[:],ss[:],'bx', alpha=0.5)
- #plt.plot(qs[:],ss[:],'bx', label='Small', alpha=0.5)
- axs[0, 0].plot(qs[:], yss[:], 'b-')
- axs[0, 0].set_title('Small')
- axs[0, 1].plot(ql[:],sl[:],'gx', alpha=0.5)
- axs[0, 1].plot(ql[:], ysl[:], 'g-')
- axs[0, 1].set_title('Large')
- axs[1, 0].plot(qsl[:],ssl[:],'rx', alpha=0.5)
- axs[1, 0].plot(qsl[:], yssl[:], 'r-')
- axs[1, 0].set_title('Small & Large')
- axs[1, 1].plot(qs[:], yss[:], 'b-', label='S fit')
- axs[1, 1].plot(ql[:], ysl[:], 'g-', label='L fit')
- axs[1, 1].plot(qsl[:], yssl[:], 'r-', label='S&L fit')
- axs[1, 1].legend(loc="upper right")
- axs[1, 1].set_title('All fits')
- for ax in axs.flat:
- ax.set(xlabel='$q$', ylabel='$S(q)$')
- for ax in axs.flat:
- ax.label_outer()
- #axs[1,1].
- #axs[1,1].
- plt.show()
- ################### Structure factor end ###################
- if settings["dipoleAnalysis"]:
- if(iterateSmall):
- particleTypes[0].dipoleMoment += dMoment/nCycles
- if(iterateLarge):
- particleTypes[1].dipoleMoment += dMoment/nCycles
- if settings["densityAnalysis"]:
- if(iterateSmall):
- particleTypes[0].density += dDensity/nCycles
- particleTypes[0].n = int(particleTypes[0].density*boxVolume/volumeSmall)
- if(iterateLarge):
- particleTypes[1].density += dDensity/nCycles
- particleTypes[1].n = int(particleTypes[1].density*boxVolume/volumeLarge)
- if settings["densityAnalysis"]:
- fpDensity.write("\n\n\nSystem Parameters:\nTemperature: {0:f}\n".format(temperature))
- for p in particleTypes:
- fpDensity.write(str(p)+'\n')
- fpDensity.close()
- elif settings["dipoleAnalysis"]:
- fpDipole.write("\n\n\nSystem Parameters:\n")
- for p in particleTypes:
- fpDipole.write(str(p)+'\n')
- fpDipole.close()
- # Analysis
- print("\n\nANALYSIS:")
- cs.run_for_all_pairs()
- print(" #Clusters: {:d}".format(len(cs.clusters)))
- max_size = 0;
- nSmallInCluster = 0
- nLargeInCluster = 0
- for c in cs.clusters:
- print(" cluster id: {}".format(c[0]))
- nSmall = 0
- nLarge = 0
- for p in c[1].particles():
- if p.type == particleTypes[0].type:
- nSmall+=1
- elif p.type == particleTypes[1].type:
- nLarge+=1
- nSmallInCluster+=nSmall
- nLargeInCluster+=nLarge
- print(" nSmall in cluster: {} \n nLarge in cluster: {}".format(nSmall,nLarge))
- if max_size<c[1].size():
- max_size = c[1].size()
- fd = c[1].fractal_dimension(dr=0.1)[0]
- if fd == fd: # if fd is not nan
- print(" Fractal dimension:",fd)
- print(" biggest cluster: {:d}".format(max_size))
- print(" {}/{} small particles in cluster".format(nSmallInCluster,particleTypes[0].n))
- print(" {}/{} large particles in cluster".format(nLargeInCluster,particleTypes[1].n))
- if __name__ == "__main__":
- main()
- #backup code
- #system.time_step = timeStep
- ################### Velocity autocorrelation start ###################
- #velObs = espressomd.observables.ParticleVelocities(ids=(0,))
- #accumulator = espressomd.accumulators.TimeSeries(obs=velObs, delta_N=1)
- #system.auto_update_accumulators.add(accumulator)
- #system.integrator.run(300000)
- #print(accumulator.time_series())
- #acf = tidynamics.acf(accumulator.time_series())
- #print(acf)
- #fig = plt.figure()
- #ax = fig.gca()
- #ax.set_xticks(np.arange(0, 1000, 100))
- #ax.set_yticks(np.arange(min(acf), max(acf), 0.5))
- #plt.plot(acf)
- #plt.grid()
- #plt.show()
- #plt.plot(acf) # Plot list. x-values assumed to be [0, 1, 2, 3]
- #plt.show() # Optional when using IPython interpreter
- #vector_autocorrelate(accumulator.time_series())
- ################### Velocity autocorrelation end ###################
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement