def init_md(self, name, time_step=0.5, temp_init=300, temp_bath=None, reset=False, interval=1): """ Initialize an ase molecular dynamics trajectory. The logfile needs to be specifies, so that old trajectories are not overwritten. This functionality can be used to subsequently carry out equilibration and production. Args: name (str): Basic name of logfile and trajectory time_step (float): Time step in fs (default=0.5) temp_init (float): Initial temperature of the system in K (default is 300) temp_bath (float): Carry out Langevin NVT dynamics at the specified temperature. If set to None, NVE dynamics are performed instead (default=None) reset (bool): Whether dynamics should be restarted with new initial conditions (default=False) interval (int): Data is stored every interval steps (default=1) """ # If a previous dynamics run has been performed, don't reinitialize velocities unless explicitely requested # via restart=True if not self.dynamics or reset: self._init_velocities(temp_init=temp_init) # Set up dynamics if temp_bath is None: self.dynamics = VelocityVerlet(self.molecule, time_step * units.fs) else: self.dynamics = Langevin(self.molecule, time_step * units.fs, temp_bath * units.kB, 0.01) # Create monitors for logfile and a trajectory file logfile = os.path.join(self.working_dir, "%s.log" % name) trajfile = os.path.join(self.working_dir, "%s.traj" % name) logger = MDLogger(self.dynamics, self.molecule, logfile, stress=False, peratom=False, header=True, mode='a') trajectory = Trajectory(trajfile, 'w', self.molecule) # Attach monitors to trajectory self.dynamics.attach(logger, interval=interval) self.dynamics.attach(trajectory.write, interval=interval)
def _molecular_dynamics(self, step, N): """Performs a molecular dynamics simulation, until mdmin is exceeded. If resuming, the file number (md%05i) is expected.""" mincount = 0 energies, oldpositions = [], [] thermalized = False if not thermalized: self.MaxwellBoltzmannDistribution(N, temp=self.temperature * kB, force_temp=True) traj = io.Trajectory('md.traj', 'a', self.atoms) dyn = VelocityVerlet(self.atoms, dt=self.timestep * units.fs) log = MDLogger(dyn, self.atoms, 'md.log', header=True, stress=False, peratom=False) dyn.attach(log, interval=1) dyn.attach(traj, interval=1) os.remove('md.log') os.remove('md.traj') while mincount < self.mdmin: dyn.run(1) energies.append(self.atoms.get_potential_energy()) passedmin = self.passedminimum(energies) if passedmin: mincount += 1 oldpositions.append(self.atoms.positions.copy()) # Reset atoms to minimum point. self.atoms.positions = oldpositions[passedmin[0]]
def _molecular_dynamics(self, resume=None): """Performs a molecular dynamics simulation, until mdmin is exceeded. If resuming, the file number (md%05i) is expected.""" self._log('msg', 'Molecular dynamics: md%05i' % self._counter) mincount = 0 energies, oldpositions = [], [] thermalized = False if resume: self._log('msg', 'Resuming MD from md%05i.traj' % resume) if os.path.getsize('md%05i.traj' % resume) == 0: self._log( 'msg', 'md%05i.traj is empty. Resuming from ' 'qn%05i.traj.' % (resume, resume - 1)) atoms = io.read('qn%05i.traj' % (resume - 1), index=-1) else: images = io.Trajectory('md%05i.traj' % resume, 'r') for atoms in images: energies.append(atoms.get_potential_energy()) oldpositions.append(atoms.positions.copy()) passedmin = self._passedminimum(energies) if passedmin: mincount += 1 self._atoms.set_momenta(atoms.get_momenta()) thermalized = True self._atoms.positions = atoms.get_positions() self._log('msg', 'Starting MD with %i existing energies.' % len(energies)) if not thermalized: MaxwellBoltzmannDistribution(self._atoms, temp=self._temperature * units.kB, force_temp=True) traj = io.Trajectory('md%05i.traj' % self._counter, 'a', self._atoms) self._constrain() dyn = NPT(self._atoms, timestep=self._timestep * units.fs, temperature=self._temperature * units.kB, externalstress=self._externalstress, ttime=self._ttime * units.fs, pfactor=self._pfactor * units.fs**2) # dyn = NPTber(self._atoms, timestep=self._timestep * units.fs, temperature=self._temperature, fixcm=True, pressure=self._pressure, taut=self._taut * units.fs, taup=self._taup * units.fs, compressibility=self._compressibility) log = MDLogger(dyn, self._atoms, 'md%05i.log' % self._counter, header=True, stress=False, peratom=False) dyn.attach(log, interval=1) dyn.attach(traj, interval=1) while mincount < self._mdmin: # self._constrain() dyn.run(1) # del self._atoms.constraints energies.append(self._atoms.get_potential_energy()) passedmin = self._passedminimum(energies) if passedmin: mincount += 1 oldpositions.append(self._atoms.positions.copy()) # Reset atoms to minimum point. self._atoms.positions = oldpositions[passedmin[0]]
def __init__(self, atoms, timestep, trajectory, logfile=None, loginterval=1): Dynamics.__init__(self, atoms, logfile=None, trajectory=trajectory) self.dt = timestep # Store data locally except on parallel simulations self._localdata = not getattr(atoms, "parallel", False) if logfile: self.attach(MDLogger(dyn=self, atoms=atoms, logfile=logfile), interval=loginterval)
def create_system(self, name, time_step=1.0, temp=300, temp_init=None, restart=False, store=1, nvt=False, friction=0.001): """ Parameters ----------- name : str Name for output files. time_step : float, optional Time step in fs for simulation. temp : float, optional Temperature in K for NVT simulation. temp_init : float, optional Optional different temperature for initialization than thermostate set at. restart : bool, optional Determines whether simulation is restarted or not, determines whether new velocities are initialized. store : int, optional Frequency at which output is written to log files. nvt : bool, optional Determines whether to run NVT simulation, default is False. friction : float, optional friction coefficient in fs^-1 for Langevin integrator """ if temp_init is None: temp_init = temp if not self.md or restart: MaxwellBoltzmannDistribution(self.mol, temp_init * units.kB) if not nvt: self.md = VelocityVerlet(self.mol, time_step * units.fs) else: self.md = Langevin(self.mol, time_step * units.fs, temp * units.kB, friction / units.fs) logfile = os.path.join(self.tmp, "{}.log".format(name)) trajfile = os.path.join(self.tmp, "{}.traj".format(name)) logger = MDLogger(self.md, self.mol, logfile, stress=False, peratom=False, header=True, mode="a") trajectory = Trajectory(trajfile, "w", self.mol) self.md.attach(logger, interval=store) self.md.attach(trajectory.write, interval=store)
def _molecular_dynamics(self, N, resume=None): """Performs a molecular dynamics simulation, until mdmin is exceeded. If resuming, the file number (md%05i) is expected.""" self._log('msg', 'Molecular dynamics: md%05i' % self._counter) mincount = 0 energies, oldpositions = [], [] thermalized = False if resume: self._log('msg', 'Resuming MD from md%05i.traj' % resume) if os.path.getsize('md.traj') == 0: self._log('msg', 'md%05i.traj is empty. Resuming from ' 'qn%05i.traj.' % (resume, resume - 1)) atoms = io.read('qn.traj', index=-1) else: images = io.Trajectory('md.traj' % resume, 'r') for atoms in images: energies.append(atoms.get_potential_energy()) oldpositions.append(atoms.positions.copy()) passedmin = self._passedminimum(energies) if passedmin: mincount += 1 self._atoms.set_momenta(atoms.get_momenta()) thermalized = True self._atoms.positions = atoms.get_positions() self._log('msg', 'Starting MD with %i existing energies.' % len(energies)) if not thermalized: self.MaxwellBoltzmannDistribution(self._atoms, N, temp=self._temperature * units.kB, force_temp=True) if (self._counter > 1): os.remove('md.log') os.remove('md.traj') traj = io.Trajectory('md.traj', 'a', self._atoms) dyn = VelocityVerlet(self._atoms, dt=self._timestep * units.fs) log = MDLogger(dyn, self._atoms, 'md.log', header=True, stress=False, peratom=False) dyn.attach(log, interval=1) dyn.attach(traj, interval=1) while mincount < self._mdmin: dyn.run(1) energies.append(self._atoms.get_potential_energy()) passedmin = self._passedminimum(energies) if passedmin: mincount += 1 oldpositions.append(self._atoms.positions.copy()) # Reset atoms to minimum point. self._atoms.positions = oldpositions[passedmin[0]]
def MD(self): """Molecular Dynamic""" from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase import units from ase.md import MDLogger from ase.io.trajectory import PickleTrajectory from ase.md.langevin import Langevin from ase.md.verlet import VelocityVerlet dyndrivers = { 'Langevin': Langevin, 'None': VelocityVerlet, } useAsap = False mol = self.mol temperature = self.definedParams['temperature'] init_temperature = self.definedParams['init_temperature'] time_step = self.definedParams['time_step'] nstep = self.definedParams['nstep'] nprint = self.definedParams['nprint'] thermostat = self.definedParams['thermostat'] prop_file = os.path.join(self.definedParams['workdir'], self.definedParams['output_prefix'] + '.out') traj_file = os.path.join(self.definedParams['workdir'], self.definedParams['output_prefix'] + '.traj') MaxwellBoltzmannDistribution(mol, init_temperature * units.kB) if thermostat == 'None': dyn = VelocityVerlet(mol, time_step * units.fs) elif thermostat == 'Langevin': dyn = Langevin(mol, time_step * units.fs, temperature * units.kB, 0.01) else: raise ImplementationError( method, 'Thermostat is not implemented in the MD function') #Function to print the potential, kinetic and total energy traj = PickleTrajectory(traj_file, "a", mol) dyn.attach(MDLogger(dyn, mol, prop_file), interval=nprint) dyn.attach(traj.write, interval=nprint) dyn.run(nstep) traj.close()
def md_calculation(fcp_file): from ase import units from ase.io.trajectory import Trajectory from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase.md.langevin import Langevin from ase.md import MDLogger if 'fcc' in fcp_file: ref_cell = read(ref_fcc) P = np.array([[-1, 1, 1], [1, -1, 1], [1, 1, -1]]) P *= 3 atoms = make_supercell(ref_cell, P) else: raise ValueError("Unknown phase") fcp = ForceConstantPotential.read(fcp_file) fcs = fcp.get_force_constants(atoms) calc = ForceConstantCalculator(fcs) atoms.set_calculator(calc) temperature = 200 number_of_MD_steps = 100 time_step = 5 # in fs dump_interval = 10 traj_file = "data/md_" + fcp_file.split('.')[0] + '{}.traj'.format( temperature) log_file = "data/md_log_{}.log".format(temperature) dyn = Langevin(atoms, time_step * units.fs, temperature * units.kB, 0.02) logger = MDLogger(dyn, atoms, log_file, header=True, stress=False, peratom=True, mode='w') traj_writer = Trajectory(traj_file, 'w', atoms) dyn.attach(logger, interval=dump_interval) dyn.attach(traj_writer.write, interval=dump_interval) # run MD MaxwellBoltzmannDistribution(atoms, temperature * units.kB) dyn.run(number_of_MD_steps)
Driver_MDRestartFrequency=5, Driver_Velocities_='', Driver_Velocities_empty='<<+ "velocities.txt"', Driver_Steps=500, Driver_KeepStationary='Yes', Driver_TimeStep=8.26, Driver_Thermostat_='Berendsen', Driver_Thermostat_Temperature=0.00339845142, # 800 deg Celcius # Driver_Thermostat_Temperature=0.0, # 0 deg Kelvin Driver_Thermostat_CouplingStrength=0.01) write_dftb_velocities(test, 'velocities.txt') os.system('rm md.log.* md.out* geo_end*xyz') test.set_calculator(calculator_NVE) dyn = VelocityVerlet(test, 0.000 * fs) # fs time step. dyn.attach(MDLogger(dyn, test, 'md.log.NVE', header=True, stress=False, peratom=False, mode='w'), interval=1) dyn.run(1) # run NVE ensemble using DFTB's own driver test = read('geo_end.gen') write('test.afterNVE.xyz', test) read_dftb_velocities(test, filename='geo_end.xyz') write_dftb_velocities(test, 'velocities.txt') os.system('mv md.out md.out.NVE') os.system('mv geo_end.xyz geo_end_NVE.xyz') test.set_calculator(calculator_NVT) os.system('rm md.log.NVT') dyn.attach(MDLogger(dyn, test, 'md.log.NVT', header=True, stress=False, peratom=False, mode='w'), interval=1) dyn.run(1) # run NVT ensemble using DFTB's own driver
calc = GAP(rcut=6.0) nsw, pstress, tebeg, potim, _ = read_incar() my_atoms = read('POSCAR', format='vasp') my_atoms.set_calculator(calc) """ for NVT """ #print(tebeg,'tebeg') dyn = NVTBerendsen(my_atoms, timestep=potim * fs, temperature=tebeg, taut=0.5 * 1000 * fs, trajectory='ase.traj') dyn.attach(MDLogger(dyn, my_atoms, 'OUTCAR', header=True, stress=True, pstress=pstress, peratom=False, mode="w"), interval=1) dyn.run(steps=nsw) atoms_lat = my_atoms.cell atoms_pos = my_atoms.positions atoms_symbols = my_atoms.get_chemical_symbols() element, ele = get_ele_dict(atoms_symbols) write_contcar(element, ele, atoms_lat, atoms_pos)
Driver_KeepStationary='Yes', Driver_TimeStep=8.26, Driver_Thermostat_='Berendsen', #Driver_Thermostat_Temperature = 0.00339845142, # 800 deg Celcius Driver_Thermostat_Temperature=0.0, # 0 deg Kelvin Driver_Thermostat_CouplingStrength=0.01, ) write_dftb_velocities(test, 'velocities.txt') os.system("rm md.log.* md.out* geo_end*xyz") test.set_calculator(calculator_NVE) dyn = VelocityVerlet(test, 0.000 * fs) # fs time step. dyn.attach(MDLogger(dyn, test, 'md.log.NVE', header=True, stress=False, peratom=False, mode="w"), interval=1) dyn.run(1) # run NVE ensemble using DFTB's own driver test = read('geo_end.gen') write('test.afterNVE.xyz', test) read_dftb_velocities(test, filename='geo_end.xyz') write_dftb_velocities(test, 'velocities.txt') os.system("mv md.out md.out.NVE") os.system("mv geo_end.xyz geo_end_NVE.xyz") test.set_calculator(calculator_NVT)
si.set_calculator(calc) # geometry optimization si = optimize(si, box=True) print('equlirum cell para: ', si.get_cell()[0][0]) print('equlirum energy: ', si.get_potential_energy()) print('equlirum stress', -si.get_stress() / units.GPa) # Build the 2*2*2 supercell atoms = si * 2 atoms.set_calculator(calc) print(atoms) # NVT MD simulation dyn = NVTBerendsen(atoms, p.time_step * units.fs, p.temperature, taut=p.taut * units.fs) MaxwellBoltzmannDistribution(atoms, p.temperature * units.kB) dyn.attach(MDLogger(dyn, atoms, 'md.log', header=True, stress=False, mode="w"), interval=p.save_interval) traj = Trajectory('md.traj', 'w', atoms) dyn.attach(traj.write, interval=p.save_interval) dyn.run(p.run_step)
from ase.build import graphene_nanoribbon from ase.visualize import view from ase import units from ase.md.verlet import VelocityVerlet from ase.calculators.emt import EMT from ase.md.langevin import Langevin from ase.md import MDLogger from ase.md.npt import NPT import numpy as np gnrb = graphene_nanoribbon(20, 20, type="armchair", saturated=True, vacuum=3.5) view(gnrb) gnrb.set_calculator(EMT()) dyn = VelocityVerlet(gnrb, dt=5.0 * units.fs) # dyn = Langevin(gnrb, 5 * units.fs, units.kB * 123, 0.002) stress = 2 # dyn = NPT(gnrb, 5*units.fs, 300*units.kB, stress, 25*units.fs, 75*units.fs) dyn.attach(MDLogger(dyn, gnrb, 'md2.log', header=True, stress=False, peratom=True, mode="w"), interval=1) dyn.run(100) # view(gnrb)