def plotMeanSquaredDisplacement(particles, t, N, eps, chartName, plotDiffusionConstant=False, filename="meanSquaredDisplamcent"): msd, diffusion_constant = MDFunctions.ComputeMeanSquaredDisplacement( t, particles) msd, yLabel = MDFunctions.SigmaToAngstrom(msd) t, xLabel = MDFunctions.ArgonTimeToSeconds(t) plt.title(chartName) plt.plot(t, msd, label=f'Mean squared displacement') plt.xlabel(xLabel) plt.ylabel(f"Mean sq. disp {yLabel}") plt.legend() plt.savefig(f'./fig/{filename}.jpg') plt.show() if plotDiffusionConstant: plt.title("Diffusion constant") plt.plot(t, diffusion_constant, label=f'Diffusion constant') plt.xlabel(xLabel) plt.ylabel('D') plt.legend() plt.savefig(f'{filename}_diffusionConstant.jpg') plt.show()
def Task4b_iv_avg(): print("TASK : Task4b_iv_avg") maxTime = 0.7 t, N, T = SetTime(maxTime, increments) vac = [] sampling = 5 for i in range(0, sampling): particles = MDGenerators.PopulateCreateCrystalStructure( 4, "Ar", 1.7, N, constants.mass, 190) MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) vag, diffu_coeff = MDFunctions.ComputeVelocityAutoCorrelation( t, particles) vac.append(vag) avgVag = vac[0] for i in range(0, sampling): avgVag += vac[i] avgVag[0] /= sampling chartName = f"Avg Vel AUtocorrelation {sampling}" MDPlot.plot([avgVag], t, N, chartName, ["vac"], "time (s)", "4biv_avg") MDFileWriter.WriteXYZFile(particles, "4b_ii", N) MDFileWriter.WriteLastFrame(particles, "4b_iiii_lastFrame", N)
def Task2FasterCompare2(): print("TASK : Task2FasterCompare2") maxTime = 0.7 t, N, T = SetTime(maxTime, increments) v0 = np.array([0, 0, 0]) particles = [ MDParticle.Particle('left', 'Ar', np.array([0.0, 0.0, 0.0]), v0, N, constants.mass), MDParticle.Particle('right', 'Ar', np.array([1.5, 0.0, 0.0]), v0, N, constants.mass) ] #particles = [MDParticle.Particle('left', 'Ar', np.array([0.0,0.0,0.0] ), v0, N, constants.mass)] MDFunctions.MoveToCentreOfBox(particles) MDSolver.solve(MDSolver.velocityVerlet, particles, T, N) #MDSolver.solve(MDSolver.eulerCromer, particles, T, N) MDPlot.plotAllEnergies(particles, t, "Test slow", "testSlow") MDFileWriter.WriteXYZFile(particles, "twoparticlesVelVerSlow", N, 50) particles = [ MDParticle.Particle('left', 'Ar', np.array([0.0, 0.0, 0.0]), v0, N, constants.mass), MDParticle.Particle('right', 'Ar', np.array([1.5, 0.0, 0.0]), v0, N, constants.mass) ] #particles = [MDParticle.Particle('left', 'Ar', np.array([0.0,0.0,0.0] ), v0, N, constants.mass)] MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, T, N) MDPlot.plotAllEnergies(particles, t, "Test fast", "testFast") MDFileWriter.WriteXYZFile(particles, "twoparticlesVelVerFast", N, 50)
def plotShiftedPotentialDiff(minDist, maxDist, chartName, filename="plotPotentialDiff"): shift = MDFunctions.LennardJonesPotential(3, constants.eps, constants.sig) series = np.linspace(2.8, 3.1, 100) pot = MDFunctions.LennardJonesPotential(series, constants.eps, constants.sig, 0) pot2 = MDFunctions.LennardJonesPotential(series, constants.eps, constants.sig, shift) diff = pot - pot2 plt.subplot(1, 1, 1) plt.title(chartName) plt.plot(series, pot, label=f'Non shifted') plt.plot(series, pot2, label=f'Shifted') plt.plot(series, diff, label=f'Difference between shifted and non shifted') plt.xlabel('distance (sigmas)') plt.ylabel('force') plt.legend() plt.savefig(f'./fig/{filename}.jpg') plt.show()
def Task3d_ii(): print("TASK : Task3d_i") maxTime = 5 #should be 3 t, N, T = SetTime(maxTime, increments) nthFrame = 10 dist = 1.7 v0 = np.array([0, 0, 0]) particles = [ MDParticle.Particle('left', 'Ar', np.array([0., 0., 0.]), v0, N, constants.mass), MDParticle.Particle('right', 'Ar', np.array([dist, 0.0, 0.0]), v0, N, constants.mass) ] MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) MDFunctions.MoveToCentreOfBox(particles) MDPlot.plotAllEnergies(particles, t, "Total Energy (Velocity Verlet) 1.5 sigma", "3dii_energy_two") MDFileWriter.WriteXYZFile(particles, "3dii_two", N) particles = MDGenerators.PopulateCreateCrystalStructure( 1, "AR", dist, N, constants.mass) MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) MDPlot.plotAllEnergies( particles, t, "Total Energy (Velocity Verlet) 4 particles, random", "3dii_energy_four") MDFileWriter.WriteXYZFile(particles, "3dii_four", N, nthFrame)
def plotVelocityAutoCorrelation(particles, t, N, chartName, includeDiffusionCoefficientSubPlot=False, filename="velocityAutoCorrelation"): vac, diffusion_coefficcient = MDFunctions.ComputeVelocityAutoCorrelation( t, particles) t, timeUnits = MDFunctions.ArgonTimeToSeconds(t) plt.subplot(1, 1, 1) plt.title(f"{chartName} Velocity correlation") plt.plot(t, vac, label=f'Velocity auto correlation') plt.xlabel(f"time ({timeUnits})") plt.ylabel('Vel. Autocorrelation') plt.legend() plt.savefig(f'{filename}_velcorr.jpg') plt.show() if includeDiffusionCoefficientSubPlot: plt.subplot(2, 1, 1) plt.title(f"{chartName} Diffusion Coefficient") plt.plot(t, diffusion_coefficcient, label=f'Diffusion coefficient') plt.xlabel('time(s)') plt.ylabel('Diffusion coefficient') plt.legend() plt.savefig(f'{filename}_diffcoeff.jpg') plt.show()
def plotTemperature(particles, t, N, chartName, filename="plotTemperature"): tPrime = MDFunctions.ComputeTemperatureReduced(N, particles) tKelvin = MDFunctions.ArgonTPrimeToKelvin(tPrime) tToSeconds, xLabel = MDFunctions.ArgonTimeToSeconds(t) plt.title(chartName) plt.plot(tToSeconds, tKelvin, label=f'Temperature (K)') plt.xlabel(xLabel) plt.ylabel('Kelvin (K)') plt.legend() plt.savefig(f'./fig/{filename}.jpg') plt.show()
def Task3b_ii(): print("TASK : Task3b_ii") maxTime = 5 t, N, T = SetTime(maxTime, increments) v0 = np.array([0, 0, 0]) print("Simulating four atom") ## Create particless particles = [ MDParticle.Particle('one', 'Ar', np.array([1., 0.0, 0.]), v0, N, constants.mass), MDParticle.Particle('two', 'Ar', np.array([0., 1., 0.]), v0, N, constants.mass), MDParticle.Particle('three', 'Ar', np.array([-1., 0., 0.]), v0, N, constants.mass), MDParticle.Particle('four', 'Ar', np.array([0., -1., 0.]), v0, N, constants.mass) ] MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, T, N) MDPlot.plotAllEnergies(particles, t, "Total Energy (Velocity Verlet)(fast) 1.0 sigma", "allEnergies15velocityVerlet15fast") MDFileWriter.WriteXYZFile(particles, "fourparticlesVelVer1Fast", N)
def Task4_di_read(t, filename): num_bins = 10 bin_edges = np.linspace(0, 5, num_bins + 1) bin_centres = 0.5 * (bin_edges[1:] + bin_edges[:-1]) V = constants.box**3 #Read the file prepared by the previous particles, maxTindex = MDFileWriter.ReadEverything(filename, N) #Convert x-axis units from sigma to Ångstrøm bin_centres = MDFunctions.SigmaToAngstrom(bin_centres) if t is None: t = maxTindex elif t > maxTindex: raise Exception( "Trying to read out rdf from frame {t} which only simulated {maxTindex} frames" ) tInSeconds = MDFunctions.ArgonTimeToSeconds(t) count = len(particles) x = np.array([[0., 0., 0.] for i in range(count)]) # Velocity j = 0 counter = 0 for j in range(0, count): x[counter] = particles[j].x[t] counter += 1 #x = np.where(x > 0) #Bin the distance counts data = MDFunctions.rdf(bin_edges, x, V) chartName = f"Ar N={count} RDF after {tInSeconds[0]:11.6} {tInSeconds[1]}" # def barchart(data, xlabels, chartName, filename = "barChart"): MDPlot.barchart(data, bin_centres, "RDF", chartName, f"RDF_{filename}") strLabels = [] for lb in bin_centres[0]: strLabels.append(f"{lb:11.1f}")
def plotPotential(minDist, maxDist, chartName, filename="plotPotential"): series = np.linspace(minDist, maxDist, 100) pot = MDFunctions.LennardJonesPotential(series, constants.eps, constants.sig) shiftedPot = MDFunctions.LennardJonesPotential(series, constants.eps, constants.sig, constants.cutOffRange) #plt.subplot(1,1,1) plt.title(chartName) plt.plot(series, pot, label=f'Unmodified') plt.plot(series, shiftedPot, label=f'Shifted') plt.xlabel('distance (sigmas)') plt.ylabel('force') plt.legend() plt.savefig(f'./fig/{filename}.jpg') plt.show()
def Task4b_simAndWrite(): print("TASK : Task4b_ii_write") maxTime = 1.5 t, N, T = SetTime(maxTime, increments) particles = MDGenerators.PopulateCreateCrystalStructure( 4, "Ar", 1.7, N, constants.mass, 190) MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) MDFileWriter.WriteEverything(particles, "4b_ii_everything", N)
def Task4d_i_write(nGrid, sigmaDistance, initTemperature, filename): print("TASK : Task4b_ii_write+ ") maxTime = 2 t, N, T = SetTime(maxTime, increments) particles = MDGenerators.PopulateCreateCrystalStructure( nGrid, "Ar", sigmaDistance, N, constants.mass, initTemperature) MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) MDFileWriter.WriteEverything(particles, filename, N)
def Task3d_i(): print("TASK : Task3d_i") maxTime = 3 #should be 3 t, N, T = SetTime(maxTime, increments) nthFrame = 10 particles = MDGenerators.PopulateCreateCrystalStructure( 4, "AR", 1.7, N, constants.mass) MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) MDPlot.plotAllEnergies( particles, t, "Total Energy (Velocity Verlet) 256 particles, random", "3d_ii") MDFileWriter.WriteXYZFile(particles, "256_random", N, nthFrame)
def Task4a_iii_fast(): print("TASK : Task4a_iii") maxTime = 10 t, N, T = SetTime(maxTime, increments) t_initial = 190 particles = MDGenerators.PopulateCreateCrystalStructure( 3, "Ar", 1.7, N, constants.mass, t_initial) MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) #temp = MDFunctions.ComputeTemperatureReduced(N-1, particles, constants.eps) #print(f"AT time {maxTime} temperature is {temp} kelvin") chartName = f"4a) iii Temp ({t_initial} K) (fast)" MDPlot.plotTemperature(particles, t, N, chartName, "4a_iii_fast")
def Task3e_ii(): print("TASK : Task3e_ii") maxTime = 1 #should be 3 nthFrame = 1 t, N, T = SetTime(maxTime, increments) particles = MDGenerators.PopulateCreateCrystalStructure( 2, "AR", 1.7, N, constants.mass) MDFunctions.MoveToCentreOfBox(particles) #MDFileWriter.WriteXYZFile(particles, "108_initial", N, nthFrame) #MDSolver.solve(MDSolver.velocityVerlet, particles, T, N) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) MDFileWriter.WriteXYZFile(particles, "108_initial", N, nthFrame)
def createParticles(count, atomType, avgDistanceSigma, N, mass, temperature=None): particles = [] x0 = [0, 0, 0] if temperature is not None: v0 = MDFunctions.CreateRandomVelocityFromTemperature( count, temperature) else: v0 = np.array([[0., 0., 0.] for i in range(N)]) # Velocity xPositions = MDFunctions.getPositionInBox(count) # v0speedVector = MDFunctions.getRandomNormalizedDirection() for i in range(0, count): particle = MDParticle.Particle(i, atomType, xPositions[i], v0[i], N, mass) particles.append(particle) return particles
def Task4c_ii(): print("TASK : Task4c_ii") maxTime = 0.7 t, N, T = SetTime(maxTime, increments) particles = MDGenerators.PopulateCreateCrystalStructure( 6, "Ar", 1.7, N, constants.mass, 190) MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) MDPlot.plotMeanSquaredDisplacement(particles, t, N, constants.eps, "4c) i - Mean squared displacement", True, "4c_ii") MDFileWriter.WriteXYZFile(particles, "4c_ii", N) MDFileWriter.WriteLastFrame(particles, "4c_ii_lastFrame", N)
def Task4b_v(): print("TASK : Task4b_v") maxTime = 0.7 t, N, T = SetTime(maxTime, increments) particles = MDGenerators.PopulateCreateCrystalStructure( 4, "Ar", 1.7, N, constants.mass, 190) MDFunctions.MoveToCentreOfBox(particles) MDSolver.solveFaster(MDSolver.velocityVerletFast2, particles, maxTime, N) MDPlot.plotVelocityAutoCorrelation(particles, t, N, "4b) ii - Vel.Corr / Diff.coeff ", "4b_v") MDFileWriter.WriteXYZFile(particles, "4b_v", N) MDFileWriter.WriteLastFrame(particles, "4b_v_lastFrame", N)
def plotDistanceBetween(t, chartName, p1, p2, filename="two-particle-distance"): N = len(t) dist = np.zeros(N) distanceVectors = np.subtract(p1.x, p2.x) for i in range(N): dist[i] = MDFunctions.getDistance(p1.x[i], p2.x[i]) #plt.subplot(3,1,1) plt.title(chartName) plt.plot(t, dist, label=f'x(t) ') plt.xlabel('time(s)') plt.ylabel('distance (sigmas)') plt.legend() plt.savefig(f'./fig/{filename}.jpg')
def eulerCromer(p, n, dt, particles, eps, sig): scaleBy = 24 acc_vec = np.array([0.0, 0.0, 0.0]) pot = 0. for op in particles: if op is p: continue distvec = np.subtract(p.x[n], op.x[n]) dist = np.sqrt(distvec[0]**2 + distvec[1]**2 + distvec[2]**2) forcescalar = 2 * (dist**-12) - dist**-6 acc_vec += forcescalar * (distvec / dist**2.0) pot += MDFunctions.LennardJonesPotential(dist, eps, sig) p.p[n + 1] = pot p.a[n + 1] = scaleBy * acc_vec p.v[n + 1] = p.v[n] + dt * p.a[n + 1] p.x[n + 1] = p.x[n] + dt * p.v[n + 1] return p
def plotAllEnergies(particles, t, chartName, filename="allEnergies"): kinetic = np.zeros(len(t)) potential = np.zeros(len(t)) total = np.zeros(len(t)) for i in range(0, len(t) - 1): for p in particles: kinetic[i] += (MDFunctions.getLength(p.v[i])**2) / 2 potential[i] += p.p[i] / 2 total = np.add(kinetic, potential) plt.title(chartName) plt.plot(t, total, label=f'Total ') plt.plot(t, potential, label=f'Potential') plt.plot(t, kinetic, label=f'Kinetic') plt.xlabel('time(s)') plt.ylabel('energy') plt.legend() plt.savefig(f'./fig/{filename}.jpg') plt.show()
def PopulateCreateCrystalStructure(n, periodicCode, distance, N, mass, temperature=None): print( f"Computes {n}x{n}x{n} tetrahedral crystal lattice with cell size {distance}" ) faceCenteredCubicLattice = np.array([ np.array([0, 0, 0]), # corner np.array([0.5, 0.5, 0]), # floor np.array([0.5, 0, 0.5]), # hither wall, np.array([0, 0.5, 0.5]) # tither wall ]) particles = [] if temperature is not None: v0 = MDFunctions.CreateRandomVelocityFromTemperature( 4 * n**3, temperature) else: v0 = np.array([[0., 0., 0.] for i in range(4 * n**3)]) # Velocity index = 0 for i in range(n): for j in range(n): for k in range(n): cellPos = np.array([i, j, k]) * distance for lstr in faceCenteredCubicLattice: particles.append( MDParticle.Particle(f"{i}-{j}-{k}", periodicCode, distance * lstr + cellPos, v0[index], N, mass)) index += 1 print(f"Done popluating, created {index} particles") density = mass * 4 / distance**3 print(f"Density of this structure is {density}") return particles
def euler(p, n, dt, particles, eps, sig): scaleBy = 24 acc_vec = np.array([0.0, 0.0, 0.0]) pot = 0. #for op in particles: plen = len(particles) for op in particles: if op is p: continue distvec = np.subtract(p.x[n], op.x[n]) dist = np.sqrt(distvec[0]**2 + distvec[1]**2 + distvec[2]**2) # pointTo = np.linalg.norm(distvec) forcescalar = 2 * (dist**-12) - dist**-6 acc_vec = forcescalar * (distvec / dist**2) pot = MDFunctions.LennardJonesPotential(dist, eps, sig) #Initial particle p.p[n + 1] += pot p.a[n + 1] += scaleBy * acc_vec p.v[n + 1] += p.v[n] + dt * p.a[n + 1] p.x[n + 1] += p.x[n] + dt * p.v[n] p.swap(n + 1)
def Task2c_iv(): print("TASK : Task2c_iv") maxTime = 5 t, N, T = SetTime(maxTime, increments) v0 = np.array([0, 0, 0]) particles = [ MDParticle.Particle('left', 'Ar', np.array([0., 0., 0.]), v0, N, constants.mass), MDParticle.Particle('right', 'Ar', np.array([1.5, 0.0, 0.0]), v0, N, constants.mass) ] MDFunctions.MoveToCentreOfBox(particles) MDSolver.solve(MDSolver.euler, particles, T, N) MDPlot.plotAllEnergies(particles, t, "Total Energy (Euler) 1.5 sigma", "2civ_allEnergiesEuler15") MDFileWriter.WriteXYZFile(particles, "twoparticlesEuler15", N) particles = [ MDParticle.Particle('left', 'Ar', np.array([0., 0., 0.]), v0, N, constants.mass), MDParticle.Particle('right', 'Ar', np.array([1.5, 0.0, 0.0]), v0, N, constants.mass) ] MDFunctions.MoveToCentreOfBox(particles) MDSolver.solve(MDSolver.eulerCromer, particles, T, N) MDPlot.plotAllEnergies(particles, t, "Total Energy (Euler Cromer) 1.5 sigma", "2civ_allEnergiesEulerCromer15") MDFileWriter.WriteXYZFile(particles, "twoparticlesEulerCromer15", N) particles = [ MDParticle.Particle('left', 'Ar', np.array([0., 0., 0.]), v0, N, constants.mass), MDParticle.Particle('right', 'Ar', np.array([1.5, 0.0, 0.0]), v0, N, constants.mass) ] MDFunctions.MoveToCentreOfBox(particles) MDSolver.solve(MDSolver.velocityVerlet, particles, T, N) MDPlot.plotAllEnergies(particles, t, "Total Energy (Velocity Verlet) 1.5 sigma", "2civ_allEnergiesVelocityVerlet15") MDFileWriter.WriteXYZFile(particles, "twoparticlesVelVer15", N) particles = [ MDParticle.Particle('left', 'Ar', np.array([0.0, 0.0, 0.0]), v0, N, constants.mass), MDParticle.Particle('right', 'Ar', np.array([0.95, 0.0, 0.0]), v0, N, constants.mass) ] MDFunctions.MoveToCentreOfBox(particles) MDSolver.solve(MDSolver.eulerCromer, particles, T, N) MDPlot.plotAllEnergies(particles, t, "Total Energy (Euler) 0.95 sigma", "2civ_allEnergiesEuler095") MDFileWriter.WriteXYZFile(particles, "twoparticlesEuler095", N) particles = [ MDParticle.Particle('left', 'Ar', np.array([0.0, 0.0, 0.0]), v0, N, constants.mass), MDParticle.Particle('right', 'Ar', np.array([0.95, 0.0, 0.0]), v0, N, constants.mass) ] MDFunctions.MoveToCentreOfBox(particles) MDFileWriter.WriteXYZFile(particles, "twoparticlesEulerCromer095", N) MDPlot.plotAllEnergies(particles, t, "Total Energy (Euler Cromer) 0.95 sigma", "2civ_allEnergiesEulerCromer095") MDFileWriter.WriteXYZFile(particles, "twoparticlesEulerCromer095", N) particles = [ MDParticle.Particle('left', 'Ar', np.array([0.0, 0.0, 0.0]), v0, N, constants.mass), MDParticle.Particle('right', 'Ar', np.array([0.95, 0.0, 0.0]), v0, N, constants.mass) ] MDFunctions.MoveToCentreOfBox(particles) MDSolver.solve(MDSolver.velocityVerlet, particles, T, N) MDPlot.plotAllEnergies(particles, t, "Total Energy (Velocity Verlet) 0.95 sigma", "2civ_allEnergiesVelocityVerlet095") MDFileWriter.WriteXYZFile(particles, "twoparticlesVelVer095", N)