def md(gen='poscar.gen', index=0, totstep=100): atoms = read(gen, index=index) atoms.calc = IRFF(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) # dyn = BFGS(atoms) dyn = VelocityVerlet(atoms, 0.1 * units.fs) # 5 fs time step. def printenergy(a=atoms): """Function to print the potential, kinetic and total energy""" natom = len(a) epot = a.get_potential_energy() / natom ekin = a.get_kinetic_energy() / natom T = ekin / (1.5 * units.kB) try: assert T <= 8000.0, 'Temperature goes too high!' except: print('Temperature goes too high, stop at step %d.' % dyn.nsteps) dyn.max_steps = dyn.nsteps - 1 # print(a.get_forces()) print('Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (epot, ekin, T, epot + ekin)) traj = Trajectory('md.traj', 'w', atoms) dyn = VelocityVerlet(atoms, 0.1 * units.fs) # 5 fs time step. dyn.attach(printenergy, interval=1) dyn.attach(traj.write, interval=1) dyn.run(totstep)
def run(self): MaxwellBoltzmannDistribution(self.atoms, self.intT * units.kB) self.dyn = VelocityVerlet(self.atoms, self.time_step * units.fs, trajectory='md.traj') def printenergy(a=self.atoms): epot_ = a.get_potential_energy() r = a.calc.r.numpy() i_ = np.where(np.logical_and(r < self.rtole * self.ro, r > 0.0001)) n = len(i_[0]) self.Epot.append(epot_) self.epot = epot_ / self.natom self.ekin = a.get_kinetic_energy() / self.natom self.T = self.ekin / (1.5 * units.kB) self.step = self.dyn.nsteps print('Step %d Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (self.step, self.epot, self.ekin, self.T, self.epot + self.ekin)) try: assert n == 0 and self.T < self.Tmax, 'Atoms too closed!' except: for _ in i_: print('atoms pair', _) print('Atoms too closed or temperature too high, stop at %d.' % self.step) self.dyn.max_steps = self.dyn.nsteps - 1 # traj = Trajectory('md.traj', 'w', self.atoms) self.dyn.attach(printenergy, interval=1) # self.dyn.attach(traj.write,interval=1) self.dyn.run(self.totstep)
def integrate_atoms( self, atoms, traj_file, n_steps, save_interval, steps=0, timestep=5.0, traj_dir="trajs", convert=False, ): if not os.path.exists(traj_dir): os.mkdir(traj_dir) traj_file = os.path.join(traj_dir, traj_file) if not os.path.exists(traj_file): traj = Trajectory(traj_file, "w") print("Creating trajectory {}...".format(traj_file)) dyn = VelocityVerlet(atoms, timestep=timestep * units.fs) count = n_steps // save_interval for i in range(count): dyn.run(save_interval) energy = atoms.get_total_energy() forces = atoms.get_forces() traj.write(atoms) steps += save_interval print("Steps: {}, total energy: {}".format(steps, energy)) else: print("Trajectory {} already exists!".format(traj_file)) if convert: self.convert_trajectory(traj_file) return steps, traj_file
def test_rattle(): i = LJInteractions({('O', 'O'): (epsilon0, sigma0)}) for calc in [ TIP3P(), SimpleQMMM([0, 1, 2], TIP3P(), TIP3P(), TIP3P()), EIQMMM([0, 1, 2], TIP3P(), TIP3P(), i) ]: dimer = s22('Water_dimer') for m in [0, 3]: dimer.set_angle(m + 1, m, m + 2, angleHOH) dimer.set_distance(m, m + 1, rOH, fix=0) dimer.set_distance(m, m + 2, rOH, fix=0) fixOH1 = [(3 * i, 3 * i + 1) for i in range(2)] fixOH2 = [(3 * i, 3 * i + 2) for i in range(2)] fixHH = [(3 * i + 1, 3 * i + 2) for i in range(2)] dimer.set_constraint(FixBondLengths(fixOH1 + fixOH2 + fixHH)) dimer.calc = calc e = dimer.get_potential_energy() md = VelocityVerlet(dimer, 8.0 * units.fs, trajectory=calc.name + '.traj', logfile=calc.name + '.log', loginterval=5) md.run(25) de = dimer.get_potential_energy() - e assert abs(de - -0.028) < 0.001
def ase_md_playground(): geom = AnaPot.get_geom((0.52, 1.80, 0), atoms=("H", )) atoms = geom.as_ase_atoms() # ase_calc = FakeASE(geom.calculator) # from ase.optimize import BFGS # dyn = BFGS(atoms) # dyn.run(fmax=0.05) import ase from ase import units from ase.io.trajectory import Trajectory from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase.md.verlet import VelocityVerlet MaxwellBoltzmannDistribution(atoms, 300 * units.kB) momenta = atoms.get_momenta() momenta[0, 2] = 0. # Zero 3rd dimension atoms.set_momenta(momenta) dyn = VelocityVerlet(atoms, .005 * units.fs) # 5 fs time step. def printenergy(a): """Function to print the potential, kinetic and total energy""" epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) print('Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin)) # Now run the dynamics printenergy(atoms) traj_fn = 'asemd.traj' traj = Trajectory(traj_fn, 'w', atoms) dyn.attach(traj.write, interval=5) # dyn.attach(bumms().bimms, interval=1) dyn.run(10000) printenergy(atoms) traj.close() traj = ase.io.read(traj_fn+"@:")#, "r") pos = [a.get_positions() for a in traj] from pysisyphus.constants import BOHR2ANG pos = np.array(pos) / BOHR2ANG calc = geom.calculator calc.plot() ax = calc.ax ax.plot(*pos[:,0,:2].T) plt.show()
def test_rattle_linear(): """Test RATTLE and QM/MM for rigid linear acetonitrile.""" import numpy as np from ase import Atoms from ase.calculators.acn import (ACN, m_me, r_cn, r_mec, sigma_me, sigma_c, sigma_n, epsilon_me, epsilon_c, epsilon_n) from ase.calculators.qmmm import SimpleQMMM, EIQMMM, LJInteractionsGeneral from ase.md.verlet import VelocityVerlet from ase.constraints import FixLinearTriatomic import ase.units as units sigma = np.array([sigma_me, sigma_c, sigma_n]) epsilon = np.array([epsilon_me, epsilon_c, epsilon_n]) i = LJInteractionsGeneral(sigma, epsilon, sigma, epsilon, 3) for calc in [ ACN(), SimpleQMMM([0, 1, 2], ACN(), ACN(), ACN()), EIQMMM([0, 1, 2], ACN(), ACN(), i) ]: dimer = Atoms('CCNCCN', [(-r_mec, 0, 0), (0, 0, 0), (r_cn, 0, 0), (r_mec, 3.7, 0), (0, 3.7, 0), (-r_cn, 3.7, 0)]) masses = dimer.get_masses() masses[::3] = m_me dimer.set_masses(masses) fixd = FixLinearTriatomic(triples=[(0, 1, 2), (3, 4, 5)]) dimer.set_constraint(fixd) dimer.calc = calc d1 = dimer[:3].get_all_distances() d2 = dimer[3:].get_all_distances() e = dimer.get_potential_energy() md = VelocityVerlet(dimer, 2.0 * units.fs, trajectory=calc.name + '.traj', logfile=calc.name + '.log', loginterval=20) md.run(100) de = dimer.get_potential_energy() - e assert np.all(abs(dimer[:3].get_all_distances() - d1) < 1e-10) assert np.all(abs(dimer[3:].get_all_distances() - d2) < 1e-10) assert abs(de - -0.005) < 0.001
def maketraj(atoms, t, nstep): e = [atoms.get_potential_energy()] print "Shape of force:", atoms.get_forces().shape dyn = VelocityVerlet(atoms, 5 * units.fs) for i in range(nstep): dyn.run(10) energy = atoms.get_potential_energy() e.append(energy) if ismaster: print "Energy: ", energy if t is not None: t.write() return e
def test_apply_strain(self): calc = TersoffScr(**Tersoff_PRB_39_5566_Si_C__Scr) timestep = 1.0 * units.fs atoms = ase.io.read('cryst_rot_mod.xyz') atoms.set_calculator(calc) # constraints top = atoms.positions[:, 1].max() bottom = atoms.positions[:, 1].min() fixed_mask = ((abs(atoms.positions[:, 1] - top) < 1.0) | (abs(atoms.positions[:, 1] - bottom) < 1.0)) fix_atoms = FixAtoms(mask=fixed_mask) # strain orig_height = (atoms.positions[:, 1].max() - atoms.positions[:, 1].min()) delta_strain = timestep * 1e-5 * (1 / units.fs) rigid_constraints = False strain_atoms = ConstantStrainRate(orig_height, delta_strain) atoms.set_constraint(fix_atoms) # dynamics np.random.seed(0) simulation_temperature = 300 * units.kB MaxwellBoltzmannDistribution(atoms, 2.0 * simulation_temperature) dynamics = VelocityVerlet(atoms, timestep) def apply_strain(atoms, ConstantStrainRate, rigid_constraints): ConstantStrainRate.apply_strain(atoms, rigid_constraints) dynamics.attach(apply_strain, 1, atoms, strain_atoms, rigid_constraints) dynamics.run(100) # tests if rigid_constraints == True: answer = 0 temp_answer = 238.2066417638124 else: answer = 0.013228150080099255 temp_answer = 236.76904696481486 newpos = atoms.get_positions() current_height = newpos[:, 1].max() - newpos[:, 1].min() diff_height = (current_height - orig_height) self.assertAlmostEqual(diff_height, answer) temperature = (atoms.get_kinetic_energy() / (1.5 * units.kB * len(atoms))) self.assertAlmostEqual(temperature, temp_answer)
def test_md(cp2k_factory): calc = cp2k_factory.calc(label='test_H2_MD') positions = [(0, 0, 0), (0, 0, 0.7245595)] atoms = Atoms('HH', positions=positions, calculator=calc) atoms.center(vacuum=2.0) MaxwellBoltzmannDistribution(atoms, temperature_K=0.5 * 300, force_temp=True) energy_start = atoms.get_potential_energy() + atoms.get_kinetic_energy() with VelocityVerlet(atoms, 0.5 * units.fs) as dyn: dyn.run(20) energy_end = atoms.get_potential_energy() + atoms.get_kinetic_energy() assert abs(energy_start - energy_end) < 1e-4
def set_lattice_params(self, md='NVE', **kwargs): #self.lattice_model.set(**kwargs) self.lattice_temperature = kwargs['lattice_temperature'] self.lattice_time_step = kwargs['lattice_time_step'] self.lattice_friction = kwargs['lattice_friction'] if md == 'Langevin': self._lattice_dyn = Langevin(self.atoms, self.lattice_time_step, self.lattice_temperature, self.lattice_friction, trajectory='LattHist.traj') elif md == 'NVE': self._lattice_dyn = VelocityVerlet(self.atoms, dt=self.lattice_time_step, trajectory='LattHist.traj')
def constant_energy(nuclear_charges, coordinates, dump=None, calculator=None): """ """ if calculator is None: # LOAD AND SET MODEL parameters = {} parameters["offset"] = -97084.83100465109 parameters["sigma"] = 10.0 alphas = np.load(FILENAME_ALPHAS) X = np.load(FILENAME_REPRESENTATIONS) Q = np.load(FILENAME_CHARGES) alphas = np.array(alphas, order="F") X = np.array(X, order="F") calculator = QMLCalculator(parameters, X, Q, alphas) molecule = ase.Atoms(nuclear_charges, coordinates) molecule.set_calculator(calculator) # Set the momenta corresponding to T=300K MaxwellBoltzmannDistribution(molecule, 200 * units.kB) # We want to run MD with constant energy using the VelocityVerlet algorithm. dyn = VelocityVerlet(molecule, 1 * units.fs) # 5 fs time step. # if dump is not None: # traj = Trajectory(dump, 'w', molecule) # dyn.attach(traj.write, interval=5) def printenergy(a=molecule, t=None): # store a reference to atoms in the definition. """Function to print the potential, kinetic and total energy.""" epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) print('pEpot = %.2feV Ekin = %.2feV (T=%3.0fK) ' 'Etot = %.4feV t=%.4f' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin, t)) for i in range(10): start = time.time() dyn.run(0) end = time.time() printenergy(t=end - start) return
def test_gfn2xtb_velocityverlet(): """Perform molecular dynamics with GFN2-xTB and Velocity Verlet Integrator""" thr = 1.0e-5 atoms = Atoms( symbols="NHCHC2H3OC2H3ONHCH3", positions=np.array([ [1.40704587284727, -1.26605342016611, -1.93713466561923], [1.85007200612454, -0.46824072777417, -1.50918242392545], [-0.03362432532150, -1.39269245193812, -1.74003582081606], [-0.56857009928108, -1.01764444489068, -2.61263467107342], [-0.44096297340282, -2.84337808903410, -1.48899734014499], [-0.47991761226058, -0.55230954385212, -0.55520222968656], [-1.51566045903090, -2.89187354810876, -1.32273881320610], [-0.18116520746778, -3.45187805987944, -2.34920431470368], [0.06989722340461, -3.23298998903001, -0.60872832703814], [-1.56668253918793, 0.00552120970194, -0.52884675001441], [1.99245341064342, -1.73097165236442, -3.08869239114486], [3.42884244212567, -1.30660069291348, -3.28712665743189], [3.87721962540768, -0.88843123009431, -2.38921453037869], [3.46548545761151, -0.56495308290988, -4.08311788302584], [4.00253374168514, -2.16970938132208, -3.61210068365649], [1.40187968630565, -2.43826111827818, -3.89034127398078], [0.40869198386066, -0.49101709352090, 0.47992424955574], [1.15591901335007, -1.16524842262351, 0.48740266650199], [0.00723492494701, 0.11692276177442, 1.73426297572793], [0.88822128447468, 0.28499001838229, 2.34645658013686], [-0.47231557768357, 1.06737634000561, 1.52286682546986], [-0.70199987915174, -0.50485938116399, 2.28058247845421], ]), ) calc = XTB(method="GFN2-xTB", cache_api=False) atoms.set_calculator(calc) dyn = VelocityVerlet(atoms, timestep=1.0 * fs) dyn.run(20) assert approx(atoms.get_potential_energy(), thr) == -896.9772346260584 assert approx(atoms.get_kinetic_energy(), thr) == 0.022411127028842362 atoms.calc.set(cache_api=True) dyn.run(20) assert approx(atoms.get_potential_energy(), thr) == -896.9913862530841 assert approx(atoms.get_kinetic_energy(), thr) == 0.036580471363852810
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 serve_md(nuclear_charges, coordinates, calculator=None, temp=None): """ """ if calculator is None: parameters = {} parameters["offset"] = -97084.83100465109 parameters["sigma"] = 10.0 alphas = np.load(FILENAME_ALPHAS) X = np.load(FILENAME_REPRESENTATIONS) Q = np.load(FILENAME_CHARGES, allow_pickle=True) alphas = np.array(alphas, order="F") X = np.array(X, order="F") calculator = QMLCalculator(parameters, X, Q, alphas) # SET MOLECULE molecule = ase.Atoms(nuclear_charges, coordinates) molecule.set_calculator(calculator) # SET ASE MD # Set the momenta corresponding to T=300K MaxwellBoltzmannDistribution(molecule, 200 * units.kB) time = 0.5 if temp is None: # We want to run MD with constant energy using the VelocityVerlet algorithm. dyn = VelocityVerlet(molecule, time * units.fs) # 1 fs time step. else: dyn = NVTBerendsen(molecule, time*units.fs, temp, time*units.fs, fixcm=False) # SET AND SERVE NARUPA MD imd = ASEImdServer(dyn) while True: imd.run(10) print("") dump_xyz(molecule, tmpdir + "snapshot.xyz") return
def run(self): self.dyn = VelocityVerlet(self.atoms, self.time_step * units.fs, trajectory='md.traj') def printenergy(a=self.atoms): epot_ = a.get_potential_energy() r = a.calc.r.detach().numpy() i_ = np.where(np.logical_and(r < self.rtole * self.ro, r > 0.0001)) n = len(i_[0]) if len(self.Epot) == 0: dE_ = 0.0 else: dE_ = abs(epot_ - self.Epot[-1]) self.Epot.append(epot_) self.epot = epot_ / self.natom self.ekin = a.get_kinetic_energy() / self.natom self.T = self.ekin / (1.5 * units.kB) self.step = self.dyn.nsteps print('Step %d Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (self.step, self.epot, self.ekin, self.T, self.epot + self.ekin)) try: if self.CheckDE: assert n == 0 and dE_ < self.dEstop, 'Atoms too closed or Delta E too high!' else: assert n == 0 and self.T < self.Tmax, 'Atoms too closed or Temperature goes too high!' except: # for _ in i_: # print('atoms pair',_) print( 'Atoms too closed or Temperature goes too high, stop at %d.' % self.step) self.dyn.max_steps = self.dyn.nsteps - 1 # traj = Trajectory('md.traj', 'w', self.atoms) self.dyn.attach(printenergy, interval=1) # self.dyn.attach(traj.write,interval=1) self.dyn.run(self.totstep)
def test_md(cp2k_factory): calc = cp2k_factory.calc(label='test_H2_MD') positions = [(0, 0, 0), (0, 0, 0.7245595)] atoms = Atoms('HH', positions=positions, calculator=calc) atoms.center(vacuum=2.0) # Run MD MaxwellBoltzmannDistribution(atoms, 0.5 * 300 * units.kB, force_temp=True) energy_start = atoms.get_potential_energy() + atoms.get_kinetic_energy() dyn = VelocityVerlet(atoms, 0.5 * units.fs) #def print_md(): # energy = atoms.get_potential_energy() + atoms.get_kinetic_energy() # print("MD total-energy: %.10feV" % energy) #dyn.attach(print_md, interval=1) dyn.run(20) energy_end = atoms.get_potential_energy() + atoms.get_kinetic_energy() assert energy_start - energy_end < 1e-4 print('passed test "H2_MD"')
def get_ANN_energy(input_file): (structure_file, T, dt, md_steps, print_steps, trajectory_file, potentials) = parse_input(input_file) # atomic structure atoms = ase.io.read(structure_file, format='vasp') # ANN calculator calc = ANNCalculator(potentials) atoms.set_calculator(calc) # initialize velocities MaxwellBoltzmannDistribution(atoms, temp=T * units.kB) # initialize MD md = VelocityVerlet(atoms, dt * units.fs, trajectory=trajectory_file) print("# {:5s} {:15s} {:15s} {:7s} {:15s}".format("step", "E_pot", "E_kin", "T", "E_tot")) printenergy(0, atoms) istep = 0 for i in range(int(md_steps / print_steps)): md.run(steps=print_steps) istep += print_steps printenergy(istep, atoms)
def run_md(): # Use Asap for a huge performance increase if it is installed use_asap = True if use_asap: from asap3 import EMT size = 10 else: from ase.calculators.emt import EMT size = 3 # Set up a crystal atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], symbol="Cu", size=(size, size, size), pbc=True) # Describe the interatomic interactions with the Effective Medium Theory atoms.calc = EMT() # Set the momenta corresponding to T=300K MaxwellBoltzmannDistribution(atoms, 300 * units.kB) # We want to run MD with constant energy using the VelocityVerlet algorithm. dyn = VelocityVerlet(atoms, 5 * units.fs) # 5 fs time step. traj = Trajectory('cu.traj', 'w', atoms) dyn.attach(traj.write, interval=10) def printenergy(a=atoms): # store a reference to atoms in the definition. epot, ekin = calcenergy(a) print('Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin)) # Now run the dynamics dyn.attach(printenergy, interval=10) printenergy() dyn.run(200)
def main(): if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable('$ASE_CP2K_COMMAND not defined') calc = CP2K(label='test_H2_MD') positions = [(0, 0, 0), (0, 0, 0.7245595)] atoms = Atoms('HH', positions=positions, calculator=calc) atoms.center(vacuum=2.0) # Run MD MaxwellBoltzmannDistribution(atoms, 0.5 * 300 * units.kB, force_temp=True) energy_start = atoms.get_potential_energy() + atoms.get_kinetic_energy() dyn = VelocityVerlet(atoms, 0.5 * units.fs) #def print_md(): # energy = atoms.get_potential_energy() + atoms.get_kinetic_energy() # print("MD total-energy: %.10feV" % energy) #dyn.attach(print_md, interval=1) dyn.run(20) energy_end = atoms.get_potential_energy() + atoms.get_kinetic_energy() assert energy_start - energy_end < 1e-4 print('passed test "H2_MD"')
def run_md_Morse(Morse_parameters, A0, steps=10000, trajectory="md.traj"): hbar_fs = (ase.units._hbar / ase.units._e) * 1.E15 D, a, R0, frequency = Morse_parameters[0:4] r0 = R0 calculator = MorsePotential2(a=a, D=D, r0=r0) #calculator = MorsePotential(rho0=6.0, epsilon=2.0, r0=1.0) period = (hbar_fs / frequency) / (2 * pi) pos = 1 * (r0 + A0) atoms = Atoms("HH", positions=[[0, 0, 0], [pos, 0, 0]], masses=[1.0, 1.0]) constr = FixAtoms(indices=[0]) atoms.set_constraint(constr) atoms.set_calculator(calculator) # def V(d): # atoms.set_positions([[0,0,0],[d,0,0]]) # return atoms.get_potential_energy() # r_plot = linspace(-4.0,4.0,1000) # V_plot = array([V(d) for d in r_plot]) # plt.plot(r_plot,V_plot) # plt.show() dynamics = VelocityVerlet(atoms, dt=(period / 20.) * ase.units.fs, trajectory=trajectory) dynamics.run(20000)
def learn_pes_by_tempering(atoms, gp, cutoff, ttime, calculator=None, model=None, dt=2., ediff=0.01, volatile=None, target_temperature=1000., stages=1, equilibration=5, rescale_velocities=1.05, pressure=None, stress_equilibration=5, rescale_cell=1.01, eps='random', algorithm='fastfast', name='model', overwrite=True, traj='tempering.traj', logfile='leapfrog.log'): """ pressure (hydrostatic): defined in units of Pascal and is equal to -(trace of stress tensor)/3 eps: if 'random', strain *= a random number [0, 1) if a positive float, strain *= 1-e^(-|dp/p|/eps) i.e. eps ~ relative p fluctuations else, no action """ assert rescale_velocities > 1 and rescale_cell > 1 if pressure is not None: warnings.warn('rescaling cell is not robust!') if model is not None: if type(model) == str: model = PosteriorPotentialFromFolder(model) if gp is None: gp = model.gp if atoms.get_velocities() is None: t = target_temperature MaxwellBoltzmannDistribution(atoms, t * units.kB) Stationary(atoms) ZeroRotation(atoms) dyn = VelocityVerlet(atoms, dt * units.fs, trajectory=traj) dyn = Leapfrog(dyn, gp, cutoff, calculator=calculator, model=model, ediff=ediff, volatile=volatile, algorithm=algorithm, logfile=logfile) t = 0 T = '{} (instant)'.format(atoms.get_temperature()) checkpoints = np.linspace(0, ttime, stages + 1)[1:] for k, target_t in enumerate(checkpoints): print('stage: {}, time: {}, target time: {}, (temperature={})'.format( k, t, target_t, T)) while t < target_t: spu, e, T, s = dyn.run_updates(equilibration) t += spu * equilibration * dt dyn.rescale_velocities( rescale_velocities if T < target_temperature else 1. / rescale_velocities) if pressure is not None: spu, e, T, s = dyn.run_updates(stress_equilibration) t += spu * stress_equilibration * dt p = -s[:3].mean() / units.Pascal # figure out strain dp = p - pressure strain = (rescale_cell if dp > 0 else 1. / rescale_cell) - 1 if eps is 'random': strain *= np.random.uniform() elif type(eps) == float and eps > 0 and abs(p) > 0: strain *= 1 - np.exp(-np.abs(dp / p) / eps) # apply strain dyn.strain_atoms(np.eye(3) * strain) if k == stages - 1: dyn.model.to_folder(name, info='temperature: {}'.format(T), overwrite=overwrite) else: dyn.model.to_folder('{}_{}'.format(name, k), info='temperature: {}'.format(T), overwrite=overwrite) return dyn.get_atoms(), dyn.model
def train_pes_by_tempering(atoms, gp, cutoff, ttime, calculator=None, model=None, dt=2., ediff=0.01, volatile=None, target_temperature=1000., stages=1, equilibration=5, rescale_velocities=1.05, pressure=None, stress_equilibration=5, rescale_cell=1.01, randomize=True, algorithm='fastfast', name='model', overwrite=True, traj='tempering.traj', logfile='leapfrog.log'): assert rescale_velocities > 1 and rescale_cell > 1 if model is not None: if type(model) == str: model = PosteriorPotentialFromFolder(model) if gp is None: gp = model.gp if atoms.get_velocities() is None: t = target_temperature MaxwellBoltzmannDistribution(atoms, t * units.kB) Stationary(atoms) ZeroRotation(atoms) dyn = VelocityVerlet(atoms, dt * units.fs, trajectory=traj) dyn = Leapfrog(dyn, gp, cutoff, calculator=calculator, model=model, ediff=ediff, volatile=volatile, algorithm=algorithm, logfile=logfile) t = 0 T = '{} (instant)'.format(atoms.get_temperature()) checkpoints = np.linspace(0, ttime, stages + 1)[1:] for k, target_t in enumerate(checkpoints): print('stage: {}, time: {}, target time: {}, (temperature={})'.format( k, t, target_t, T)) while t < target_t: spu, e, T, s = dyn.run_updates(equilibration) t += spu * equilibration * dt dyn.rescale_velocities( rescale_velocities if T < target_temperature else 1. / rescale_velocities) if pressure is not None: spu, e, T, s = dyn.run_updates(stress_equilibration) t += spu * stress_equilibration * dt p = -s[:3].mean() / units.Pascal # figure out factor dp = p - pressure factor = (rescale_cell if dp > 0 else 1. / rescale_cell) if randomize: factor = 1 + np.random.uniform(0, 1) * (factor - 1) # apply rescaling dyn.rescale_cell(factor) if k == stages - 1: dyn.model.to_folder(name, info='temperature: {}'.format(T), overwrite=overwrite) else: dyn.model.to_folder('{}_{}'.format(name, k), info='temperature: {}'.format(T), overwrite=overwrite) return dyn.get_atoms(), dyn.model
strain_atoms = ConstantStrainRate(orig_height, params.strain_rate * params.timestep) atoms.set_constraint([fix_atoms, strain_atoms]) atoms.set_calculator(params.calc) # ********* Setup and run MD *********** # Set the initial temperature to 2*simT: it will then equilibriate to # simT, by the virial theorem MaxwellBoltzmannDistribution(atoms, 2.0 * params.sim_T) # Initialise the dynamical system dynamics = VelocityVerlet(atoms, params.timestep) # Print some information every time step def printstatus(): if dynamics.nsteps == 1: print """ State Time/fs Temp/K Strain G/(J/m^2) CrackPos/A D(CrackPos)/A ---------------------------------------------------------------------------------""" log_format = ( '%(label)-4s%(time)12.1f%(temperature)12.6f' + '%(strain)12.5f%(G)12.4f%(crack_pos_x)12.2f (%(d_crack_pos_x)+5.2f)' ) atoms.info['label'] = 'D' # Label for the status line
# Describe the interatomic interactions with the Effective Medium Theory atoms.set_calculator(EMT()) # Do a quick relaxation of the cluster qn = QuasiNewton(atoms) qn.run(0.001, 10) # Set the momenta corresponding to T=1200K MaxwellBoltzmannDistribution(atoms, 1200 * units.kB) Stationary(atoms) # zero linear momentum ZeroRotation(atoms) # zero angular momentum # We want to run MD using the VelocityVerlet algorithm. # Save trajectory: dyn = VelocityVerlet(atoms, 5 * units.fs, trajectory='moldyn4.traj') def printenergy(a=atoms): # store a reference to atoms in the definition. """Function to print the potential, kinetic and total energy.""" epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) print('Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin)) dyn.attach(printenergy, interval=10) # Now run the dynamics printenergy() dyn.run(2000)
dimer = Atoms('CCNCCN', [(-r_mec, 0, 0), (0, 0, 0), (r_cn, 0, 0), (r_mec, 3.7, 0), (0, 3.7, 0), (-r_cn, 3.7, 0)]) masses = dimer.get_masses() masses[::3] = m_me dimer.set_masses(masses) fixd = FixLinearTriatomic(triples=[(0, 1, 2), (3, 4, 5)]) dimer.set_constraint(fixd) dimer.calc = calc d1 = dimer[:3].get_all_distances() d2 = dimer[3:].get_all_distances() e = dimer.get_potential_energy() md = VelocityVerlet(dimer, 2.0 * units.fs, trajectory=calc.name + '.traj', logfile=calc.name + '.log', loginterval=20) md.run(100) de = dimer.get_potential_energy() - e assert np.all(abs(dimer[:3].get_all_distances() - d1) < 1e-10) assert np.all(abs(dimer[3:].get_all_distances() - d2) < 1e-10) assert abs(de - -0.005) < 0.001
# *** Milestone 3.1 -- exit early - we don't want to run the classical MD! *** import sys sys.exit(0) # **** no changes compared to run_crack_classical.py below here yet **** # ********* Setup and run MD *********** # Set the initial temperature to 2*simT: it will then equilibriate to # simT, by the virial theorem MaxwellBoltzmannDistribution(atoms, 2.0*sim_T) # Initialise the dynamical system dynamics = VelocityVerlet(atoms, timestep) # Print some information every time step def printstatus(): if dynamics.nsteps == 1: print """ State Time/fs Temp/K Strain G/(J/m^2) CrackPos/A D(CrackPos)/A ---------------------------------------------------------------------------------""" log_format = ('%(label)-4s%(time)12.1f%(temperature)12.6f'+ '%(strain)12.5f%(G)12.4f%(crack_pos_x)12.2f (%(d_crack_pos_x)+5.2f)') atoms.info['label'] = 'D' # Label for the status line atoms.info['time'] = dynamics.get_time()/units.fs atoms.info['temperature'] = (atoms.get_kinetic_energy() / (1.5*units.kB*len(atoms)))
X2 = [] Y2 = [] Z2 = [] def dump_positions(): (x1, y1, z1), (x2, y2, z2) = planets.get_positions() X1.append(x1) Y1.append(y1) Z1.append(z1) X2.append(x2) Y2.append(y2) Z2.append(z2) dyn = VelocityVerlet(planets, timestep=0.01 * fs) dyn.attach(dump_positions) dyn.run(20000) ############################################################################### # Now let's plot the trajectory to see what we get: if __name__ == '__main__': plt.clf() plt.plot(X1, Y1, label='C') plt.plot(X2, Y2, label='H') plt.legend() plt.axes().set_aspect('equal') plt.show() ###############################################################################
def learn_pes_by_anealing(atoms, gp, cutoff, calculator=None, model=None, dt=2., ediff=0.01, volatile=None, target_temperature=1000., stages=1, equilibration=5, rescale_velocities=1.05, algorithm='fastfast', name='model', overwrite=True, traj='anealing.traj', logfile='leapfrog.log'): assert rescale_velocities > 1 if model is not None: if type(model) == str: model = PosteriorPotentialFromFolder(model) if gp is None: gp = model.gp if atoms.get_velocities() is None: t = target_temperature / stages MaxwellBoltzmannDistribution(atoms, t * units.kB) Stationary(atoms) ZeroRotation(atoms) dyn = VelocityVerlet(atoms, dt * units.fs, trajectory=traj) dyn = Leapfrog(dyn, gp, cutoff, calculator=calculator, model=model, ediff=ediff, volatile=volatile, algorithm=algorithm, logfile=logfile) # initial equilibration while dyn.volatile(): _, e, t, s = dyn.run_updates(1) _, e, t, s = dyn.run_updates(equilibration) temperatures = np.linspace(t, target_temperature, stages + 1)[1:] heating = t < target_temperature cooling = not heating for k, target_t in enumerate(temperatures): print( 'stage: {}, temperature: {}, target temperature: {}, ({})'.format( k, t, target_t, 'heating' if heating else 'cooling')) while (heating and t < target_t) or (cooling and t > target_t): dyn.rescale_velocities(rescale_velocities if heating else 1. / rescale_velocities) _, e, t, s = dyn.run_updates(equilibration) if k == stages - 1: dyn.model.to_folder(name, info='temperature: {}'.format(t), overwrite=overwrite) else: dyn.model.to_folder('{}_{}'.format(name, k), info='temperature: {}'.format(t), overwrite=overwrite) return dyn.get_atoms(), dyn.model
size = 3 # Set up a crystal atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], symbol="Cu", size=(size, size, size), pbc=True) # Describe the interatomic interactions with the Effective Medium Theory atoms.calc = EMT() # Set the momenta corresponding to T=300K MaxwellBoltzmannDistribution(atoms, 300 * units.kB) # We want to run MD with constant energy using the VelocityVerlet algorithm. dyn = VelocityVerlet(atoms, 5 * units.fs) # 5 fs time step. def printenergy(a=atoms): # store a reference to atoms in the definition. """Function to print the potential, kinetic and total energy.""" epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) print('Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin)) # Now run the dynamics dyn.attach(printenergy, interval=10) printenergy() dyn.run(200)
'IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot) defect.set_calculator(pot) else: print 'No potential chosen', 1 / 0 print 'Finding initial dislocation core positions...' try: defect.params['core'] except KeyError: defect.params['core'] = np.array([98.0, 98.0, 1.49]) defect = set_quantum(defect, params.n_core) MaxwellBoltzmannDistribution(defect, 2.0 * sim_T) if dyn_type == 'eam': dynamics = VelocityVerlet(defect, timestep) dynamics.attach(pass_print_context(defect, dynamics)) elif dyn_type == 'LOTF': defect.info['core'] = np.array([98.0, 98.0, 1.49]) print 'Initializing LOTFDynamics' verbosity_push(PRINT_VERBOSE) dynamics = LOTFDynamics(defect, timestep, params.extrapolate_steps, check_force_error=False) dynamics.set_qm_update_func(update_qm_region) dynamics.attach(pass_print_context(defect, dynamics)) dynamics.attach(traj_writer, print_interval, defect) else: print 'No dyn_type chosen', 1 / 0