def Run_Vel_ver(eps,sigma,mass,time,dt):
	global rt
	global vt
	global at
	global E_potential
	global E_kinetic
	global T_avg

	Init.initialize()
	Init.print_init()
	

	rt=Init.r #Assigning initial values to poisitons
	vt=Init.v #Assigning initial values to velocities
	at=[[0.0]*3 for i in range(0,Init.ip)] #Initializing the acceleration varible
	sum_a=[[0.0]*3 for i in range(0,Init.ip)] #Initializing the variable to store the a(t) and a(t+dt) values
	nsteps=(int)(time/dt) #Number of steps for simulation to run

	#Initializing the energy and temperature variables

	E_potential=[0.0]*(nsteps)
	E_kinetic=[0.0]*(nsteps)
	E_total=[0.0]*(nsteps)

	at=Acceleration.Calc_a(eps,sigma,mass,rt) #Assigning initial values to acceleration
	
	E_kin=[0.0]*(nsteps)
	T=[0.0]*(nsteps)
	T_avg=0.0
	T_sum=0.0
	print('Time step | Potential Energy | Kinetic Energy| Total Energy| Temperature|Average Temperture\n')

	with open('Vel_verlet_NVE.out','w') as f:
		with open('Vel_verlet_Energy_NVE.out','w') as e:
			e.write('Time step | Potential Energy | Kinetic Energy| Total Energy| Temperature|Average Temperture\n')
			with open('VMD_pos_Vel_ver_NVE.xyz','w') as d:
				for i in range(nsteps): # Loop running in time steps
					for j in range(0,Init.ip): #Updating the positions of all the particles
						rt[j][0]=rt[j][0]+vt[j][0]*dt+0.5*(dt**2)*at[j][0]
						rt[j][1]=rt[j][1]+vt[j][1]*dt+0.5*(dt**2)*at[j][1]
						rt[j][2]=rt[j][2]+vt[j][2]*dt+0.5*(dt**2)*at[j][2]
						
					x=Acceleration.Calc_a(eps,sigma,mass,rt) #Updating the acceleration
					
		
					for l in range(0, Init.ip): #Calculating the sum of a(t) and a(t+delta(t)) to be used in velocity calculation
						sum_a[l][0]=at[l][0]+x[l][0]
						sum_a[l][1]=at[l][1]+x[l][1]
						sum_a[l][2]=at[l][2]+x[l][2]
					at=x
					for n in range(0, Init.ip): # Updating the velocity
						vt[n][0]=vt[n][0]+0.5* dt * (sum_a[n][0])
						vt[n][1]=vt[n][1]+0.5* dt * (sum_a[n][1])
						vt[n][2]=vt[n][2]+0.5*dt * (sum_a[n][2]) 
					E_potential[i]=LJ.Calc_LJ(eps,sigma,rt)[3]
					E_kinetic[i]=Kinetic_Energy.Calc_KE(eps,sigma,mass,vt)	
					E_total[i]=E_potential[i]+E_kinetic[i]
					T[i]=(E_kinetic[i]*2)/(3*Init.ip)
					T_sum+=T[i]
					T_avg=T_sum/(i+1) #Calculating the running average of the temperature
					print('%f %f %f %f %f %f\n' % (i*dt, E_potential[i], E_kinetic[i], E_total[i], T[i], T_avg))
					e.write('%f %20.6f %20.6f %20.6f %20.6f %20.6f\n' % (i*dt,E_potential[i],E_kinetic[i],E_total[i], T[i], T_avg))
					f.write('Time step: %f, rx ry rz vx vy vz \n' % (i*dt))
					d.write("%d\nInitial Conditions\n" % (Init.N))					
					for p in range (0, Init.ip):
						f.write('{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f}\n'.format(rt[p][0],rt[p][1],rt[p][2],vt[p][0],vt[p][1],vt[p][2],at[p][0],at[p][1],at[p][2]))
						d.write('%s%8.3f%8.3f%8.3f\n' % (Init.Atom_Type,rt[p][0], rt[p][1], rt[p][2]))
			d.close()		
		e.close()
	f.close()
	pylab.plot(E_potential,label='Potential Energy')
	pylab.plot(E_kinetic,label='Kinetic Energy')
	pylab.plot(E_total, label='Total Energy')
	pylab.xlabel('Time')
	pylab.ylabel('Energy')
	pylab.title('Energy Plots, N=%d, L=%f' % ((Init.ip), Init.L))
	pylab.savefig('N=%dL=%f_Vel_verlet.png' % ((Init.ip), Init.L))
	pylab.legend()
	pylab.show()
Beispiel #2
0
def Run_Leap_Frog(eps,sigma,mass,time,dt,Tn,tau):
	global rt
	global vt
	global at
	global E_potential
	global E_kinetic

	Init.initialize()
	Init.print_init()

	rt=Init.r #Assigning inital values to positions
	vt=Init.v #Assigning initial values to velocity
	at=[[0.0]*3 for i in range(0,Init.ip)]
	sum_a=[[0.0]*3 for i in range(0,Init.ip)]
	dth=dt*0.5
	nsteps=(int)(time/dt)
	
	E_potential=[0.0]*nsteps
	E_kinetic=[0.0]*nsteps
	E_total=[0.0]*nsteps
	E_sum=0.0
	E_avg=0.0

	at=Acceleration.Calc_a(eps,sigma,mass,rt) #Assigning initial values to accelration
	E_kin=[0.0]*(nsteps)
	T=[0.0]*(nsteps)
	
	print('Time step | Potential Energy | Kinetic Energy| Total Energy|Average Total Energy | Temperature\n')
				
	at=Acceleration.Calc_a(eps,sigma,mass,rt) #Assigning initial values to acceleration
	
	with open('Leap_Frog.out','w') as f, open('Leap_Frog_Energy.out','w') as e, open('VMD_pos_leapfrog.xyz','w') as d:
				e.write('Time step | Potential Energy | Kinetic Energy| Total Energy|Average Total Energy | Temperature\n')
				for i in range(nsteps):
					for j in range(0,Init.ip): #Updating the positions
						vt[j][0]=vt[j][0]+dth*at[j][0]
						vt[j][1]=vt[j][1]+dth*at[j][1]
						vt[j][2]=vt[j][2]+dth*at[j][2]
						rt[j][0]=rt[j][0]+dt*vt[j][0]
						rt[j][1]=rt[j][1]+dt*vt[j][1]
						rt[j][2]=rt[j][2]+dt*vt[j][2]
							
					x=Acceleration.Calc_a(eps,sigma,mass,rt) #Updating the acceleration
					at=x
					for n in range(0, Init.ip): # Updating the velocity
						vt[n]=[vt[n][o]+at[n][o]*dth for o in range(0,3)]
					#Applying the Brendson Thermostat
					E_kin[i]=Kinetic_Energy.Calc_KE(eps,sigma,mass,vt)
					T[i]=(E_kin[i]*2)/(3*Init.ip)
					lam=math.sqrt(1+(dt/tau)*((Tn/T[i])-1))
					#Applying velocity rescaling
					for s in range(0,Init.ip):
						vt[s][0]=vt[s][0]*lam
						vt[s][1]=vt[s][1]*lam
						vt[s][2]=vt[s][2]*lam
					#Updating the energies
					E_potential[i]=LJ.Calc_LJ(eps,sigma,rt)[3]
					E_kinetic[i]=Kinetic_Energy.Calc_KE(eps,sigma,mass,vt)	
					E_total[i]=E_potential[i]+E_kinetic[i]
					E_sum+=E_total[i]
					E_avg=E_sum/(i+1) #Calculating the running average for energy
					print ('%f %f %f %f %f %f\n' % (i*dt, E_potential[i], E_kinetic[i], E_total[i], E_avg,T[i]))
					e.write(' %f %f %f %f %f %f\n' % (i*dt,E_potential[i],E_kinetic[i],E_total[i],E_avg,T[i]))
					f.write('Time step: %f, rx ry rz vx vy vz \n' % (i*dt))
					d.write("%d\nInitial Conditions\n" % (Init.N))					
					for p in range (0, Init.ip):
						f.write('{:d},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f}\n'.format(p, rt[p][0],rt[p][1],rt[p][2],vt[p][0],vt[p][1],vt[p][2],at[p][0],at[p][1],at[p][2]))
						d.write('%s%8.3f%8.3f%8.3f\n' % (Init.Atom_Type,rt[p][0], rt[p][1], rt[p][2]))
				d.close()		
				e.close()
				f.close()
	plt.plot(E_potential,label='Potential Energy')
	plt.plot(E_kinetic,label='Kinetic Energy')
	plt.plot(E_total, label='Total Energy')
	plt.xlabel('Time')
	plt.ylabel('Energy')
	plt.title('Energy plot, N=%d, L=%f' % (Init.ip, Init.L))
	plt.savefig('N=%dL=%f_Energy_LF_NVT.png' % (Init.ip, Init.L))
	plt.show()
	
	plt.plot(T, label='Temperature')
	plt.xlabel('Time')
	plt.ylabel('Temperature')
	plt.title('Energy plot, N=%d, L=%f' % (Init.ip, Init.L))
	plt.savefig('N=%dL=%f_Temperature_LF_NVT.png' % (Init.ip, Init.L))
	plt.legend()
	plt.show()
    def SimulateEvent(self):
        #Initialization of module
        Score = Scoring(self.EventName, self.Year)
        """
        #Check platform and open file for saving calculated data     
        cwd = os.getcwd()
        if('Windows' in platform.platform()):
            file = cwd + "/Results/"+ str(self.simulation_name)+".txt"
        else:
            cwd = cwd.replace('\\', '/')
            file = cwd + "/Results/" + str(self.simulation_name)+".txt"
        
        if(self.Counter == 1): #if Counter == 1 the file gets opened and the old data will get overwritten
            f = open(file, 'w')
            f.write('Event&Year|Track|Car|Parameter|Event|Scored Time in s|Scored EnergyConsumption in kWh|Scores|\n')
        else:   #for all other values of Counter the data will get appended to the old ones
            f = open(file, 'a')
        """
        #Points = []

        ds = 0.5  #length of each track segment

        #Go through Tracks
        for counterTracks in self.tracks:
            #Go through Vehicles
            for counterVehicles in self.Vehicles:
                #wWrite Header to file

                if ('AutoX' in counterTracks):
                    cwd = os.getcwd()  #open file with
                    if ('Windows' in platform.platform()):
                        file = cwd + '\\CSV\\'
                        #VehicleParameters.xlsx'
                    else:
                        cwd = cwd.replace('\\', '/')
                        file = cwd + '/CSV/'
                    cfile = open(
                        os.getcwd() + "\\tracks\\" + self.track_name + "\\" +
                        counterTracks, 'r')

                    curvature = []
                    #Load Curvature from file into list and make it to an array
                    for row in cfile:
                        new = np.array(row.split(','))
                        value1 = float(new[0])
                        curvature.append(value1)

                    curvature = np.array(curvature)

                    track = Track(curvature, ds)
                    # Initialize Lap Simulation
                    LS = lts.LapSim(counterVehicles, track)
                    LS.max_laps = 2
                    # Run Lap Simulation
                    LS.speed_profile()
                elif ('Endurance' in counterTracks):
                    cwd = os.getcwd()
                    if ('Windows' in platform.platform()):
                        file = cwd + '\\CSV\\'
                        # VehicleParameters.xlsx
                    else:
                        cwd = cwd.replace('\\', '/')
                        file = cwd + '/CSV/'
                    cfile = open(
                        os.getcwd() + "/tracks/" + self.track_name + "\\" +
                        counterTracks, 'r')

                    curvature = []
                    #Load Curvature from file into list and make it to an array
                    for row in cfile:
                        new = np.array(row.split(','))
                        value1 = float(new[0])
                        curvature.append(value1)
                    curvature = np.array(curvature)

                    track = Track(curvature, ds)
                    # Initialize Lap Simulation
                    LS = lts.LapSim(counterVehicles, track)
                    LS.max_laps = 2
                    # Run Lap Simulation
                    LS.speed_profile()
                elif ('Efficiency' in counterTracks):
                    cwd = os.getcwd()
                    if ('Windows' in platform.platform()):
                        file = cwd + '\\CSV\\'  #VehicleParameters.xlsx'
                    else:
                        cwd = cwd.replace('\\', '/')
                        file = cwd + '/CSV/'
                    cfile = open(
                        os.getcwd() + "/tracks/" + self.track_name + "\\" +
                        counterTracks, 'r')

                    curvature = []
                    #Load Curvature from file into List and make it to an Array
                    for row in cfile:
                        new = np.array(row.split(','))
                        value1 = float(new[0])
                        curvature.append(value1)
                    curvature = np.array(curvature)

                    track = Track(curvature, ds)
                    # Initialize Lap Simulation
                    LS = lts.LapSim(counterVehicles, track)
                    LS.max_laps = 2
                    # Run Lap Simulation
                    LS.speed_profile()
                elif ('Skidpad' in counterTracks):
                    curvature = []
                    FzgWidth = 1.3  #Average of all 4 in 2015 and 2016 (look datasheet GDrive) in m
                    Radius = FzgWidth / 2 + 15.25 / 2
                    SkidpadCurvature = 1 / Radius  #k=1/R
                    i = 1
                    range = 2 * math.pi * Radius
                    while i <= round(range / ds):
                        curvature.append(SkidpadCurvature)
                        i += 1
                    curvature = np.array(curvature)

                    track = Track(curvature, ds)
                    # Initialize Lap Simulation
                    LS = lts.LapSim(counterVehicles, track)
                    LS.max_laps = 2
                    # Run Lap Simulation
                    LS.speed_profile()

                #Calculate Event Points
                if ('Skidpad' in counterTracks):
                    Tyour = LS.lapTime
                    Tmin = 4.920
                    if (Tmin > Tyour
                        ):  #set Tyour as Tmin if it is faster than fix Tmin
                        Tmin = Tyour
                    SkidpadScoring = Score.Calc_Skidpad(Tmin, Tyour)
                    if (isinstance(SkidpadScoring, string_types) == True
                        ):  #if points are a string set points on 0
                        SkidpadScoring = 0
                        self.result_file.cell(row=self.counter,
                                              column=9).value = str(Tyour)
                        #Points.append('Skidpad: %s s, Score: %d' %(Tyour, SkidpadScoring))
                        #f.write('Skidpad|%f|-|%d|\n' %(Tyour, SkidpadScoring))
                    elif (isinstance(SkidpadScoring, string_types) == False
                          ):  #if points are not a string, go on
                        #Points.append('Skidpad: %s s, Score: %d' %(Tyour, SkidpadScoring))
                        self.result_file.cell(row=self.counter,
                                              column=9).value = str(Tyour)
                        #f.write('Skidpad|%f|-|%d|\n' %(Tyour, SkidpadScoring))
                    print('Skidpad ' + str(self.Counter) + ' of ' +
                          str(self.revision) + ' completed.')
                elif ('Accel' in counterTracks):
                    Accel = Acceleration.Acceleration(
                        counterVehicles
                    )  #initialize class for accel calculation
                    Tyour = Accel.AccelTime()
                    #Tyour = LS.lapTime
                    Tmin = 3.109
                    if (Tmin > Tyour
                        ):  #set Tyour as Tmin if it is faster than fix Tmin
                        Tmin = Tyour
                    AccelScoring = Score.Calc_Acceleration(Tmin, Tyour)
                    if (isinstance(AccelScoring, string_types) == True
                        ):  #if points are a string set points on 0
                        AccelScoring = 0
                        self.result_file.cell(row=self.counter,
                                              column=11).value = str(Tyour)
                        #Points.append('Acceleration: %s s, Score: %d' %(Tyour, AccelScoring))
                        #f.write('Acceleration|%f|-|%d|\n' %(Tyour, AccelScoring))
                    elif (isinstance(AccelScoring, string_types) == False
                          ):  #if points are not a string, go on
                        #Points.append('Acceleration: %s s, Score: %d' %(Tyour, AccelScoring))
                        self.result_file.cell(row=self.counter,
                                              column=11).value = str(Tyour)
                        #f.write('Acceleration|%f|-|%d|\n' %(Tyour, AccelScoring))
                    print('Acceleration ' + str(self.Counter) + ' of ' +
                          str(self.revision) + ' completed.')
                elif ('AutoX' in counterTracks):
                    Tyour = LS.lapTime
                    Tmin = 56.083
                    if (Tmin > Tyour):
                        Tmin = Tyour
                    AutoXScoring = Score.Calc_AutoX(Tmin, Tyour)
                    if (isinstance(AutoXScoring, string_types) == True
                        ):  #if points are a string set points on 0
                        AutoXScoring = 0
                        self.result_file.cell(row=self.counter,
                                              column=3).value = str(Tyour)
                        #Points.append('AutoX: %s s, Score: %d' %(Tyour, AutoXScoring))
                        #f.write('AutoX|%f|-|%d|\n' %(Tyour/60, AutoXScoring))
                    elif (isinstance(AutoXScoring, string_types) == False
                          ):  #if points are not a string, go on
                        #Points.append('AutoX: %s s, Score: %d' %(Tyour, AutoXScoring))
                        self.result_file.cell(row=self.counter,
                                              column=3).value = str(Tyour)
                        #f.write('AutoX|%f|-|%d|\n' %(Tyour/60, AutoXScoring))
                    print('AutoX ' + str(self.Counter) + ' of ' +
                          str(self.revision) + ' completed.')
                elif ('Endurance' in counterTracks):
                    if (self.EventName == 'FSG'
                        ):  #calculate Tyour depending on the event
                        Tyour = LS.lapTime * 18
                    elif (self.EventName == 'FSA'):
                        if (self.Year == 2016):
                            Tyour = LS.lapTime * 20
                        elif (self.Year == 2015):
                            Tyour = LS.lapTime * 22
                    elif (self.EventName == 'FSAE'):
                        if (self.Year == 2016):
                            Tyour = LS.lapTime * 20
                        elif (self.Year == 2015):
                            Tyour = LS.lapTime * 22
                    Tmin = 1363.556
                    if (Tmin > Tyour
                        ):  #set Tyour as Tmin if it is faster than fix Tmin
                        Tmin = Tyour
                    EnduranceScoring = Score.Calc_Endurance(Tmin, Tyour)
                    if (isinstance(EnduranceScoring, string_types) == True
                        ):  #if points are a string set points on 0
                        EnduranceScoring = 0
                        self.result_file.cell(row=self.counter,
                                              column=7).value = str(Tyour)
                        #Points.append('Endurance: %s s, Score: %d' %(Tyour, EnduranceScoring))
                        #f.write('Endurance|%f|-|%d|\n' %(Tyour/60, EnduranceScoring))
                    elif (isinstance(EnduranceScoring, string_types) == False
                          ):  #if points are not a string, go on
                        #Points.append('Endurance: %s s, Score: %d' %(Tyour, EnduranceScoring))
                        self.result_file.cell(row=self.counter,
                                              column=7).value = str(Tyour)
                        #f.write('Endurance|%f|-|%d|\n' %(Tyour/60, EnduranceScoring))
                    print('Endurance ' + str(self.Counter) + ' of ' +
                          str(self.revision) + ' completed.')
                elif ('Efficiency' in counterTracks):
                    if (self.EventName == 'FSG'
                        ):  #calculate Tyour depending on the event
                        Tyour = LS.lapTime * 18
                        EyourTotal = LS.UsedEnergy / 1000 / 3600 * 18
                    elif (self.EventName == 'FSA'):
                        if (self.Year == 2016):
                            Tyour = LS.lapTime * 20
                            EyourTotal = LS.UsedEnergy / 1000 / 3600 * 20
                        elif (self.Year == 2015):
                            Tyour = LS.lapTime * 22
                            EyourTotal = LS.UsedEnergy / 1000 / 3600 * 22
                    elif (self.EventName == 'FSAE'):
                        if (self.Year == 2016):
                            Tyour = LS.lapTime * 20
                            EyourTotal = LS.UsedEnergy / 1000 / 3600 * 20
                        elif (self.Year == 2015):
                            Tyour = LS.lapTime * 22
                            EyourTotal = LS.UsedEnergy / 1000 / 3600 * 22
                    Tmin = 1363.556
                    if (Tmin > Tyour
                        ):  #set Tyour as Tmin if it is faster than fix Tmin
                        Tmin = Tyour
                    Emin = 0.242
                    Eff_fac_min = 0.1
                    Eff_fac_max = 0.89

                    #Energy consumption per lap
                    Eyour = LS.UsedEnergy / 1000 / 3600  #divide with 1000 and 3600 for unity [kWh]
                    if (Emin > Eyour
                        ):  #set Eyour as Emin if it is smaller than fix Emin
                        Emin = Eyour

                    #Eyour = 0.378   # per lap
                    EfficiencyScoring = Score.Calc_Efficiency(
                        Tmin, Emin, Eff_fac_min, Eff_fac_max, Tyour, Eyour)
                    if (isinstance(EfficiencyScoring, string_types) == True
                        ):  #if points are a string set points on 0
                        EfficiencyScoring = 0
                        self.result_file.cell(row=self.counter,
                                              column=5).value = str(Tyour)
                        #Points.append('Efficiency: %s s, Energy: %f kWh, Score: %d' %(Tyour, EyourTotal, EfficiencyScoring))
                        #f.write('Efficiency|%f|%f|%d|\n' %(Tyour/60, EyourTotal, EfficiencyScoring))
                    elif (isinstance(EfficiencyScoring, string_types) == False
                          ):  #if points are not a string, go on
                        #Points.append('Efficiency: %s s, Energy: %f kWh, Score: %d' %(Tyour, EyourTotal, EfficiencyScoring))
                        self.result_file.cell(row=self.counter,
                                              column=5).value = str(Tyour)
                        #f.write('Efficiency|%f|%f|%d|\n' %(Tyour/60, EyourTotal, EfficiencyScoring))
                    print('Efficiency ' + str(self.Counter) + ' of ' +
                          str(self.revision) + ' completed.')

        # #should delete console, but it's not working because Python IDLE don't support console cleaning
        # if (os.name == 'nt'):
        #     os.system('cls')
        # else:
        #     os.system('clear')

        #Calculate all points of each event
        Overall = SkidpadScoring + AccelScoring + EnduranceScoring + AutoXScoring + EfficiencyScoring
        #Points.append('Overall Score: %d' %(Overall))
        self.result_file.cell(row=self.counter,
                              column=2).value = str(AutoXScoring)
        self.result_file.cell(row=self.counter,
                              column=4).value = str(EfficiencyScoring)
        self.result_file.cell(row=self.counter,
                              column=6).value = str(EnduranceScoring)
        self.result_file.cell(row=self.counter,
                              column=8).value = str(SkidpadScoring)
        self.result_file.cell(row=self.counter,
                              column=10).value = str(AccelScoring)
        self.result_file.cell(row=self.counter, column=12).value = str(Overall)
Beispiel #4
0
def Run_Langevin(eps,sigma,mass,time,dt,Tn):
       global rt
       global vt
       global at
       global E_potential
       global E_kinetic

#Initialization

       Init.initialize()
       Init.print_init()


       rt=Init.r #Assigning initial values to poisitons
       vt=Init.v #Assigning initial values to velocities

       at=[[0.0]*3 for i in range(0,Init.ip)]
       sum_a=[[0.0]*3 for i in range(0,Init.ip)]
       nsteps=(int)(time/dt)
       

       E_potential=[0.0]*(nsteps)
       E_kinetic=[0.0]*(nsteps)
       E_total=[0.0]*(nsteps)

       at=Acceleration.Calc_a(eps,sigma,mass,rt) #Assigning initial values to accelration
       E_kin=[0.0]*(nsteps)
       T=[0.0]*(nsteps)
       E_sum=0.0
       E_avg=0.0
       gamma=1.0
       #E_k=Kinetic_Energy.Calc_KE(eps,sigma,mass,vt)
       #T0=(E_k*2)/(3*Init.ip)
       sig=np.sqrt(2*gamma*Tn)
       print('Time step | Potential Energy | Kinetic Energy| Total Energy| Average Total Energy| Temperature\n')

	
       with open('Vel_verlet_NVT.out','w') as f, open('Vel_verlet_Energy_NVT.out','w') as e:
                       e.write('Time step | Potential Energy | Kinetic Energy| Total Energy| Average Total Energy| Temperature\n')
                       with open('VMD_pos_NVT.xyz','w') as d:
                               	for i in range(nsteps): # Loop running in time steps

					for j in range(0,Init.ip): #Updating the positions of all the particles
                                       		rt[j][0]=rt[j][0]+vt[j][0]*dt+0.5*(dt**2)*(at[j][0]-gamma*vt[j][0])+sig*dW3(dt)
                                       		rt[j][1]=rt[j][1]+vt[j][1]*dt+0.5*(dt**2)*(at[j][1]-gamma*vt[j][1])+sig*dW3(dt)
                                       		rt[j][2]=rt[j][2]+vt[j][2]*dt+0.5*(dt**2)*(at[j][2]-gamma*vt[j][2])+sig*dW3(dt)

#Storing the updated forces for the next step 
                                	atu=Acceleration.Calc_a(eps,sigma,mass,rt) 

#Calculating the sum of a(t) and a(t+delta(t)) to be used in velocity calculation

                                 	for m in range(0, Init.ip):
                                        	sum_a[m][0]=at[m][0]+atu[m][0]
                                        	sum_a[m][1]=at[m][1]+atu[m][1]
                                        	sum_a[m][2]=at[m][2]+atu[m][2]
#Updating the velocity   

	                         	for n in range(0, Init.ip): # Updating the velocity
                                       		vt[n][0]=vt[n][0]+0.5*dt*(sum_a[n][0])-(gamma*vt[n][0]*dt)+sig*dW1(dt)-gamma*(0.5*(dt**2)*(at[n][0]-gamma*vt[n][0])+sig*dW3(dt))
                                       		vt[n][1]=vt[n][1]+0.5*dt*(sum_a[n][1])-(gamma*vt[n][1]*dt)+sig*dW1(dt)-gamma*(0.5*(dt**2)*(at[n][1]-gamma*vt[n][1])+sig*dW3(dt))
						vt[n][2]=vt[n][2]+0.5*dt*(sum_a[n][2])-(gamma*vt[n][2]*dt)+sig*dW1(dt)-gamma*(0.5*(dt**2)*(at[n][2]-gamma*vt[n][2])+sig*dW3(dt))
                                 	at=atu
#Updating the energies
                                 	E_potential[i]=LJ.Calc_LJ(eps,sigma,rt)[3]
                                 	E_kinetic[i]=Kinetic_Energy.Calc_KE(eps,sigma,mass,vt)
                                 	E_total[i]=E_potential[i]+E_kinetic[i]
					T[i]=(E_kinetic[i]*2)/(3*Init.ip)
                                 	E_sum+=E_total[i]
                                 	E_avg=E_sum/(i+1)
                                 	print('%f %f %f %f %f %f\n' % (i*dt, E_potential[i], E_kinetic[i], E_total[i],E_avg,T[i]))
                                       	e.write('%f %f %f %f %f %f\n' % (i*dt,E_potential[i],E_kinetic[i],E_total[i],E_avg,T[i]))
                                       	f.write('Time step: %f, rx ry rz vx vy vz \n' % (i*dt))
                                       	d.write("%d\nInitial Conditions\n" % (Init.N))
                                       	for p in range (0, Init.ip):
                                               f.write('{:<20.6f}\t{:<20.6f}\t{:<20.6f}\t{:<20.6f}\t{:<20.6f}\t{:<20.6f}\t{:<20.6f}\t{:<20.6f}\t{:<20.6f}\n'.format(rt[p][0],rt[p][1],rt[p][2],vt[p][0],vt[p][1]    ,vt[p][2],at[p][0],at[p][1],at[p][2]))
                                               d.write('%s%8.3f%8.3f%8.3f\n' % (Init.Atom_Type,rt[p][0], rt[p][1], rt[p][2]))
                       d.close()
       e.close()
       f.close()
       pylab.plot(E_potential,label='Potential Energy')
       pylab.plot(E_kinetic,label='Kinetic Energy')
       pylab.plot(E_total, label='Total Energy')
       pylab.xlabel('Time')
       pylab.ylabel('Energy')
       pylab.title('Energy plots, N=%d, L=%f' % (Init.ip, Init.L))
       pylab.legend()
       pylab.show()
       pylab.savefig('N=%dL=%f_VerVer_NVT.png' % (Init.ip, Init.L))
 
       pylab.plot(T, label='Temperature')
       pylab.xlabel('Time')
       pylab.ylabel('Temperature')
       pylab.title('Temperature plot, N-%d, L=%f' % (Init.ip, Init.L))
       pylab.legend()
       pylab.show()
       pylab.savefig('N=%dL=%f_VelVer_NVT.png' % (Init.ip, Init.L))
Beispiel #5
0
 def initRigidBody(self):
     mObj = Mass(self._mass)
     g = Acceleration(0.0, -0.1, 0.0)
     self._g = g
     self._gravity = g._ay
Beispiel #6
0
def Run_DPD(eps, sigma, mass, time, dt, Tn):
    global rt
    global vt
    global at
    global E_potential
    global E_kinetic

    #Initialization
    Init.initialize()
    Init.print_init()

    rt = Init.r
    vt = Init.v

    at = [[0.0] * 3 for i in range(0, Init.ip)]
    nsteps = (int)(time / dt)

    E_potential = [0.0] * (nsteps)
    E_kinetic = [0.0] * (nsteps)
    E_total = [0.0] * (nsteps)
    T = [0.0] * nsteps

    gamma = 1.0
    sig = np.sqrt(2 * gamma * Tn)

    at = Acceleration.Calc_a(eps, sigma, mass, rt, vt, sig, gamma, dt)

    E_sum = 0.0
    E_avg = 0.0

    print(
        'Time step | Potential Energy | Kinetic Energy | Total Energy | Average Total Energy | Temperature\n'
    )

    with open('DPD_NVT.out', 'w') as f:
        with open('DPD_Energy_NVT.out', 'w') as e:
            e.write(
                'Time step | Potential Energy | Kinetic Energy | Total Energy | Average Total Energy | Temperature\n'
            )
            with open('VMD_pos_NVT.xyz', 'w') as d:
                for i in range(nsteps):
                    for j in range(0, Init.ip):
                        vt[j][0] = vt[j][0] + 0.5 * dt * at[j][0]
                        vt[j][1] = vt[j][1] + 0.5 * dt * at[j][1]
                        vt[j][2] = vt[j][2] + 0.5 * dt * at[j][2]
                        rt[j][0] = rt[j][0] + dt * vt[j][0]
                        rt[j][1] = rt[j][1] + dt * vt[j][1]
                        rt[j][2] = rt[j][2] + dt * vt[j][2]

                    at = Acceleration.Calc_a(eps, sigma, mass, rt, vt, sig,
                                             gamma, dt)
                    for s in range(0, Init.ip):
                        vt[s][0] = vt[s][0] + 0.5 * dt * at[s][0]
                        vt[s][1] = vt[s][1] + 0.5 * dt * at[s][1]
                        vt[s][2] = vt[s][2] + 0.5 * dt * at[s][2]

                    #at=Acceleration.Calc_a(eps,sigma,mass,rt,vt,sig,gamma,dt)

                    E_potential[i] = LJ.Calc_LJ(eps, sigma, rt, vt, sig, gamma,
                                                dt)[3]
                    E_kinetic[i] = Kinetic_Energy.Calc_KE(eps, sigma, mass, vt)
                    T[i] = (E_kinetic[i] * 2) / (3 * Init.ip)
                    E_total[i] = E_potential[i] + E_kinetic[i]
                    E_sum += E_total[i]
                    E_avg = E_sum / (i + 1)
                    print('%f %f %f %f %f %f\n' %
                          (i * dt, E_potential[i], E_kinetic[i], E_total[i],
                           E_avg, T[i]))
                    e.write('%f %f %f %f %f %f\n' %
                            (i * dt, E_potential[i], E_kinetic[i], E_total[i],
                             E_avg, T[i]))
                    f.write('Time step: %f, rx ry rz vx vy vz \n' % (i * dt))
                    d.write("%d\nInitial Conditions\n" % (Init.N))
                    for p in range(0, Init.ip):
                        f.write(
                            '{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f}\n'
                            .format(rt[p][0], rt[p][1], rt[p][2], vt[p][0],
                                    vt[p][1], vt[p][2], at[p][0], at[p][1],
                                    at[p][2]))
                        d.write('%s%8.3f%8.3f%8.3f\n' %
                                (Init.Atom_Type, rt[p][0], rt[p][1], rt[p][2]))
            d.close()
        e.close()
    f.close()
    pylab.plot(E_potential, label='Potential Energy')
    pylab.plot(E_kinetic, label='Kinetic Energy')
    pylab.plot(E_total, label='Total Energy')
    pylab.xlabel('Time')
    pylab.ylabel('Energy')
    pylab.title('Energy plots, N=%d, L=%f' % (Init.ip, Init.L))
    pylab.legend()
    pylab.show()
    pylab.savefig('N=%dL=%f_DPD_NVT.png' % (Init.ip, Init.L))

    pylab.plot(T, label='Temperature')
    pylab.xlabel('Time')
    pylab.ylabel('Temperature')
    pylab.title('Temperature plot, N-%d, L=%f' % (Init.ip, Init.L))
    pylab.legend()
    pylab.show()
    pylab.savefig('N=%dL=%f_DPD_NVT.png' % (Init.ip, Init.L))
Beispiel #7
0
def Run_Vel_ver(eps,sigma,mass,time,dt,tau,Tn):
	global rt
	global vt
	global at
	global E_potential
	global E_kinetic

	#Initialization
	Init.initialize()
	Init.print_init()

	
	rt=Init.r #Assigning initial values to poisitons
	vt=Init.v #Assigning initial values to velocities

	at=[[0.0]*3 for i in range(0,Init.ip)]
	sum_a=[[0.0]*3 for i in range(0,Init.ip)]
	nsteps=(int)(time/dt)

	E_potential=[0.0]*(nsteps)
	E_kinetic=[0.0]*(nsteps)
	E_total=[0.0]*(nsteps)

	at=Acceleration.Calc_a(eps,sigma,mass,rt) #Assigning initial values to accelration
	E_kin=[0.0]*(nsteps)
	T=[0.0]*(nsteps)
	E_sum=0.0
	E_avg=0.0
	print('Time setp | Potential Energy | Kinetic Energy| Total Energy| Average Total Energy| Temperature\n')

	with open('Vel_verlet_NVT.out','w') as f:
		with open('Vel_verlet_Energy_NVT.out','w') as e:
			e.write('Time setp | Potential Energy | Kinetic Energy| Total Energy| Average Total Energy| Temperature\n')
			with open('VMD_pos_NVT.xyz','w') as d:
				for i in range(nsteps): # Loop running in time steps
					for j in range(0,Init.ip): #Updating the positions of all the particles
						rt[j][0]=rt[j][0]+vt[j][0]*dt+0.5*(dt**2)*at[j][0]

						rt[j][1]=rt[j][1]+vt[j][1]*dt+0.5*(dt**2)*at[j][1]

						rt[j][2]=rt[j][2]+vt[j][2]*dt+0.5*(dt**2)*at[j][2]
	
					atu=Acceleration.Calc_a(eps,sigma,mass,rt) #Updating the acceleration

					
					#Calculating the sum of a(t) and a(t+delta(t)) to be used in velocity calculation

					for m in range(0, Init.ip):
						sum_a[m][0]=at[m][0]+atu[m][0]
						sum_a[m][1]=at[m][1]+atu[m][1]
						sum_a[m][2]=at[m][2]+atu[m][2]

					
					
					for n in range(0, Init.ip): # Updating the velocity
						vt[n][0]=vt[n][0]+(0.5* dt) * (sum_a[n][0])
						vt[n][1]=vt[n][1]+(0.5* dt) * (sum_a[n][1])
						vt[n][2]=vt[n][2]+(0.5* dt) * (sum_a[n][2]) 
					at=atu
					#Applying the Brendson Thermostat
					E_kin[i]=Kinetic_Energy.Calc_KE(eps,sigma,mass,vt)
					T[i]=(E_kin[i]*2)/(3*Init.ip)
					lam=math.sqrt(1+(dt/tau)*((Tn/T[i])-1))
					#Applying velocity rescaling
					for s in range(0,Init.ip):
						vt[s][0]=vt[s][0]*lam
						vt[s][1]=vt[s][1]*lam
						vt[s][2]=vt[s][2]*lam
					#Updating the energies
					E_potential[i]=LJ.Calc_LJ(eps,sigma,rt)[3]
					E_kinetic[i]=Kinetic_Energy.Calc_KE(eps,sigma,mass,vt)
					E_total[i]=E_potential[i]+E_kinetic[i]
					E_sum+=E_total[i]
					E_avg=E_sum/(i+1)
					print('%f %f %f %f %f %f\n' % (i*dt, E_potential[i], E_kinetic[i], E_total[i],E_avg,T[i]))
					e.write('%f %f %f %f %f %f\n' % (i*dt,E_potential[i],E_kinetic[i],E_total[i],E_avg,T[i]))
					f.write('Time step: %f, rx ry rz vx vy vz \n' % (i*dt))
					d.write("%d\nInitial Conditions\n" % (Init.N))					
					for p in range (0, Init.ip):
						f.write('{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f},{:<20.6f}\n'.format(rt[p][0],rt[p][1],rt[p][2],vt[p][0],vt[p][1],vt[p][2],at[p][0],at[p][1],at[p][2]))
						d.write('%s%8.3f%8.3f%8.3f\n' % (Init.Atom_Type,rt[p][0], rt[p][1], rt[p][2]))
			d.close()		
		e.close()
	f.close()
	pylab.plot(E_potential,label='Potential Energy')
	pylab.plot(E_kinetic,label='Kinetic Energy')
	pylab.plot(E_total, label='Total Energy')
	pylab.xlabel('Time')
	pylab.ylabel('Energy')
	pylab.title('Energy plots, N=%d, L=%f' % (Init.ip, Init.L))
	pylab.legend()
	pylab.show()
	pylab.savefig('N=%dL=%f_VerVer_NVT.png' % (Init.ip, Init.L))

	pylab.plot(T, label='Temperature')
	pylab.xlabel('Time')
	pylab.ylabel('Temperature')
	pylab.title('Temperature plot, N-%d, L=%f' % (Init.ip, Init.L))
	pylab.legend()
	pylab.show()
	pylab.savefig('N=%dL=%f_VelVer_NVT.png' % (Init.ip, Init.L))