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 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 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 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 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 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 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() dyn = VelocityVerlet(atoms, 0.5 * units.fs) dyn.run(20) energy_end = atoms.get_potential_energy() + atoms.get_kinetic_energy() assert abs(energy_start - energy_end) < 1e-4
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 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 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 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 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)
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 test = read('geo_end.gen')
def run_md(atoms, id, settings_fn): """The function does Molecular Dyanamic simulation (MD) on a material, given by argument atoms. Parameters: atoms (obj): an atoms object defined by class in ase. This is the material which MD will run on. id (int): an identifying number for the material. Returns: obj:atoms object defined in ase, is returned. """ # Read settings settings = read_settings_file(settings_fn) initial_unitcell_atoms = copy.deepcopy(atoms) # Scale atoms object, cubic size = settings['supercell_size'] atoms = atoms * size * (1, 1, 1) # atoms = atoms * (size,size,size) #print(atoms.get_chemical_symbols()) N = len(atoms.get_chemical_symbols()) # Use KIM for potentials from OpenKIM use_kim = settings['use_kim'] # Use Asap for a huge performance increase if it is installed use_asap = True # Create a copy of the initial atoms object for future reference old_atoms = copy.deepcopy(atoms) # Describe the interatomic interactions with OpenKIM potential if use_kim: # use KIM potential atoms.calc = KIM( "LJ_ElliottAkerson_2015_Universal__MO_959249795837_003") else: # otherwise, default to asap3 LennardJones atoms.calc = LennardJones([18], [0.010323], [3.40], rCut=6.625, modified=True) # Set the momenta corresponding to temperature from settings file MaxwellBoltzmannDistribution(atoms, settings['temperature'] * units.kB) # Select integrator if settings['ensemble'] == "NVE": from ase.md.verlet import VelocityVerlet dyn = VelocityVerlet(atoms, settings['time_step'] * units.fs) elif settings['ensemble'] == "NVT": from ase.md.langevin import Langevin dyn = Langevin(atoms, settings['time_step'] * units.fs, settings['temperature'] * units.kB, settings['friction']) interval = settings['interval'] # Creates trajectory files in directory trajectory_files traj = Trajectory("trajectory_files/" + id + ".traj", 'w', atoms) dyn.attach(traj.write, interval=interval) # Number of decimals for most calculated properties. decimals = settings['decimals'] # Boolean indicating if the material is monoatomic. monoatomic = len(set(atoms.get_chemical_symbols())) == 1 # Calculation and writing of properties properties.initialize_properties_file(atoms, initial_unitcell_atoms, id, decimals, monoatomic) dyn.attach(properties.calc_properties, 100, old_atoms, atoms, id, decimals, monoatomic) # unnecessary, used for logging md runs # we should write some kind of logger for the MD def logger(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) t = ekin / (1.5 * units.kB) print('Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (epot, ekin, t, epot + ekin)) # Running the dynamics dyn.attach(logger, interval=interval) #logger() #dyn.run(settings['max_steps']) # check for thermal equilibrium counter = 0 equilibrium = False for i in range(round(settings['max_steps'] / settings['search_interval'])): # hyperparameter epot, ekin_pre, etot, t = properties.energies_and_temp(atoms) # kör steg som motsvarar säg 5 fs dyn.run(settings['search_interval']) # hyperparamter epot, ekin_post, etot, t = properties.energies_and_temp(atoms) #print(abs(ekin_pre-ekin_post) / math.sqrt(N)) #print(counter) if (abs(ekin_pre - ekin_post) / math.sqrt(N)) < settings['tolerance']: counter += 1 else: counter = 0 if counter > settings['threshold']: # hyperparameter print("reached equilibrium") equilibrium = True break if equilibrium: dyn.run(settings['max_steps']) properties.finalize_properties_file(atoms, id, decimals, monoatomic) else: properties.delete_properties_file(id) raise RuntimeError("MD did not find equilibrium") return atoms
ReportTest("Initial potential energy", epot, -301358.3, 0.5) etot = epot + atoms.get_kinetic_energy() if 0: if cpulayout: traj = ParallelNetCDFTrajectory("parallel.nc", atoms) else: traj = NetCDFTrajectory("serial.nc", atoms) traj.Add("PotentialEnergies") traj.Update() traj.Close() print "Trajectory done" dyn = VelocityVerlet(atoms, 3*units.fs) etot2 = None for i in range(5): dyn.run(15) newetot = atoms.get_potential_energy()+ atoms.get_kinetic_energy() print >>stdout, "Total energy:", newetot temp = atoms.get_kinetic_energy() / (1.5*units.kB*natoms) print >>stdout, "Temp:", temp, "K" if etot2 == None: ReportTest("Total energy (first step)", newetot, etot, 40.0) etot2=newetot else: ReportTest(("Total energy (step %d)" % (i+1,)), newetot, etot2, 20.0) print >>stdout, " *** This test completed ***" ReportTest.Summary()
from asap3 import EMT size = 10 else: 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.set_calculator(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. #Function to print the potential, kinetic and total energy def printenergy(a): 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) for i in range(20): dyn.run(10) printenergy(atoms)
#Use same random seed so that initialisations are deterministic. if not args.restart: print 'Thermalizing atoms' np.random.seed(42) MaxwellBoltzmannDistribution(atoms, 2.0*sim_T) dynamics = VelocityVerlet(atoms, timestep) def print_context(ats=atoms, dyn=dynamics): print 'steps, T', dyn.nsteps, ats.get_kinetic_energy()/(1.5*units.kB*len(ats)) print 'G', get_energy_release_rate(ats)/(units.J/units.m**2) print 'strain', get_strain(ats) dynamics.attach(print_context, interval=8) print 'Running Crack Simulation' dynamics.run(nsteps) print 'Crack Simulation Finished' elif args.lotf: crack_pos = atoms.info['CrackPos'] r_scale = 1.00894848312 mm_pot = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot, cutoff_skin=2.0) #test potential #quippy using atomic units atoms.cutoff = 3.0 atoms.set_cutoff(3.0) atoms.calc_connect() qmmm_pot = ForceMixingPotential(pot1=mm_pot, pot2=qm_pot, atoms=atoms, qm_args_str='carve_cluster=T cluster_periodic_z=T cluster_calc_connect=T '+ 'single_cluster=T cluster_vacuum=5.0 terminate=F print_clusters=F '+
(1.5*units.kB*len(atoms))) atoms.info['strain'] = get_strain(atoms) atoms.info['G'] = get_energy_release_rate(atoms)/(units.J/units.m**2) crack_pos = find_crack_tip_stress_field(atoms, calc=mm_pot) atoms.info['crack_pos_x'] = crack_pos[0] atoms.info['d_crack_pos_x'] = crack_pos[0] - orig_crack_pos[0] print log_format % atoms.info dynamics.attach(printstatus) # Check if the crack has advanced, and stop incrementing the strain if it has def check_if_cracked(atoms): crack_pos = find_crack_tip_stress_field(atoms, calc=mm_pot) # stop straining if crack has advanced more than tip_move_tol if not atoms.info['is_cracked'] and (crack_pos[0] - orig_crack_pos[0]) > tip_move_tol: atoms.info['is_cracked'] = True del atoms.constraints[atoms.constraints.index(strain_atoms)] dynamics.attach(check_if_cracked, 1, atoms) # Save frames to the trajectory every `traj_interval` time steps trajectory = AtomsWriter(traj_file) dynamics.attach(trajectory, traj_interval, atoms) # Start running! dynamics.run(nsteps)
print log_format % atoms.info dynamics.attach(printstatus) # Check if the crack has advanced, and stop incrementing the strain if it has def check_if_cracked(atoms): #crack_pos = find_tip_stress_field(atoms) # FIXME TS has no local virial crack_pos = [0.0, 0.0, 0.0] # stop straining if crack has advanced more than tip_move_tol if (not atoms.info['is_cracked'] and (crack_pos[0] - orig_crack_pos[0]) > params.tip_move_tol): atoms.info['is_cracked'] = True del atoms.constraints[atoms.constraints.index(strain_atoms)] dynamics.attach(check_if_cracked, 1, atoms) # Save frames to the trajectory every `traj_interval` time steps traj_file = open('traj_verlet_6R.xyz', 'w') trajectory_write = lambda: ase.io.extxyz.write_xyz(traj_file, atoms) dynamics.attach(trajectory_write, params.traj_interval) try: # Start running! dynamics.run(params.nsteps) finally: traj_file.close()
def test_lammpslib(): # potential_path must be set as an environment variable cmds = [ "pair_style eam/alloy", "pair_coeff * * NiAlH_jea.eam.alloy Ni H" ] nickel = bulk('Ni', cubic=True) nickel += Atom('H', position=nickel.cell.diagonal() / 2) # Bit of distortion nickel.set_cell(nickel.cell + [[0.1, 0.2, 0.4], [0.3, 0.2, 0.0], [0.1, 0.1, 0.1]], scale_atoms=True) lammps = LAMMPSlib(lmpcmds=cmds, atom_types={ 'Ni': 1, 'H': 2 }, log_file='test.log', keep_alive=True) nickel.calc = lammps E = nickel.get_potential_energy() F = nickel.get_forces() S = nickel.get_stress() print('Energy: ', E) print('Forces:', F) print('Stress: ', S) print() E = nickel.get_potential_energy() F = nickel.get_forces() S = nickel.get_stress() lammps = LAMMPSlib(lmpcmds=cmds, log_file='test.log', keep_alive=True) nickel.calc = lammps E2 = nickel.get_potential_energy() F2 = nickel.get_forces() S2 = nickel.get_stress() assert_allclose(E, E2, atol=1e-4, rtol=1e-4) assert_allclose(F, F2, atol=1e-4, rtol=1e-4) assert_allclose(S, S2, atol=1e-4, rtol=1e-4) nickel.rattle(stdev=0.2) E3 = nickel.get_potential_energy() F3 = nickel.get_forces() S3 = nickel.get_stress() print('rattled atoms') print('Energy: ', E3) print('Forces:', F3) print('Stress: ', S3) print() assert not np.allclose(E, E3) assert not np.allclose(F, F3) assert not np.allclose(S, S3) nickel += Atom('H', position=nickel.cell.diagonal() / 4) E4 = nickel.get_potential_energy() F4 = nickel.get_forces() S4 = nickel.get_stress() assert not np.allclose(E4, E3) assert not np.allclose(F4[:-1, :], F3) assert not np.allclose(S4, S3) # the example from the docstring cmds = [ "pair_style eam/alloy", "pair_coeff * * NiAlH_jea.eam.alloy Al H" ] Ni = bulk('Ni', cubic=True) H = Atom('H', position=Ni.cell.diagonal() / 2) NiH = Ni + H lammps = LAMMPSlib(lmpcmds=cmds, log_file='test.log') NiH.calc = lammps print("Energy ", NiH.get_potential_energy()) # a more complicated example, reading in a LAMMPS data file # then we run the actual test with open('lammps.data', 'w') as fd: fd.write(lammps_data_file) at = ase.io.read('lammps.data', format='lammps-data', Z_of_type={1: 26}, units='real') header = [ "units real", "atom_style full", "boundary p p p", "box tilt large", "pair_style lj/cut/coul/long 12.500", "bond_style harmonic", "angle_style harmonic", "kspace_style ewald 0.0001", "kspace_modify gewald 0.01", "read_data lammps.data" ] cmds = [] lammps = LAMMPSlib(lammps_header=header, lmpcmds=cmds, atom_types={'Fe': 1}, create_atoms=False, create_box=False, boundary=False, keep_alive=True, log_file='test.log') at.calc = lammps dyn = VelocityVerlet(at, 1 * units.fs) assert_allclose(at.get_potential_energy(), 2041.411982950972, atol=1e-4, rtol=1e-4) dyn.run(10) assert_allclose(at.get_potential_energy(), 312.4315854721744, atol=1e-4, rtol=1e-4)
class SpinLatticeModel(): def __init__(self, spin_model, lattice_model, spin_lattice_coupling, atoms=None): self._spin_model = spin_model self._lattice_model = lattice_model self._slc = spin_lattice_coupling self._spin_model.add_term(self._slc, name='slc') self._lattice_model.add_term(self._slc, name='slc') #self.atoms = copy.deepcopy(self._lattice_model.ref_atoms) if atoms is not None: self.atoms = atoms else: self.atoms = copy.deepcopy(self._lattice_model.ref_atoms) self.atoms.set_calculator(self._lattice_model) self._lattice_model.atoms = self.atoms @property def spin_model(self): return self._spin_model @property def lattice_model(self): return self._lattice_model @property def slc(self): return self._slc def set_atoms(self, atoms, copy=False): if copy: self.atoms = copy.deepcopy(atoms) else: self.atoms = atoms self.atoms.set_calculator(self._lattice_model) self._lattice_model.atoms = atoms def set_spin_params(self, **kwargs): self.spin_model.set(**kwargs) 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 make_supercell(self, sc_matrix): smaker = SupercellMaker(sc_matrix) sc_spin_model = self._spin_model.make_supercell(supercell_maker=smaker) sc_lattice_model = self._lattice_model.make_supercell( supercell_maker=smaker) sc_slc = self._slc.make_supercell(supercell_maker=smaker, sc_spin_model=sc_spin_model, sc_lattice_model=sc_lattice_model) return SpinLatticeModel(sc_spin_model, sc_lattice_model, sc_slc) #@profile def run(self, nstep=1): self._slc.S = self._spin_model.S self._slc.displacement = self._lattice_model.dx for istep in range(nstep): self._lattice_dyn.run(1) self._spin_model.run_one_step() self._slc.displacement = self._lattice_model.dx self._slc.S = self._spin_model.S
def test(temp, frict): output = file('Langevin.dat', 'w') # Make a small perturbation of the momenta atoms.set_momenta(1e-6 * np.random.random([len(atoms), 3])) print 'Initializing ...' predyn = VelocityVerlet(atoms, 0.5) predyn.run(2500) dyn = Langevin(atoms, timestep, temp, frict) print '' print ('Testing Langevin dynamics with T = %f eV and lambda = %f' % (temp, frict)) ekin = atoms.get_kinetic_energy()/len(atoms) print ekin output.write('%.8f\n' % ekin) print 'Equilibrating ...' # Initial guesses for least-squares fit a = 0.04 b = 2*frict c = temp params = (a,b,c) fitdata = [(0, 2.0 / 3.0 * ekin)] tstart = time.time() for i in xrange(1,nequil+1): dyn.run(nminor) ekin = atoms.get_kinetic_energy() / len(atoms) fitdata.append((i*nminor*timestep, 2.0/3.0 * ekin)) if usescipy and i % nequilprint == 0: (params, chisq) = leastSquaresFit(targetfunc, params, fitdata) print '%.6f T_inf = %.6f (goal: %f), tau = %.2f, k = %.6f' % \ (ekin, params[2], temp, 1.0/params[1], params[0]) output.write('%.8f\n' % ekin) tequil = time.time() - tstart print 'This took %s minutes.' % (tequil / 60) output.write('&\n') assert abs(temp-params[2]) < 0.25*temp, 'Least-squares fit is way off' assert nequil*nminor*timestep > 3.0/params[1], 'Equiliberation was too short' fitdata = np.array(fitdata) print 'Recording statistical data - this takes ten times longer!' temperatures = [] tstart = time.time() for i in xrange(1,nsteps+1): dyn.run(nminor) ekin = atoms.get_kinetic_energy() / len(atoms) temperatures.append(2.0/3.0 * ekin) if i % nprint == 0: tnow = time.time() - tstart tleft = (nsteps-i) * tnow / i print '%.6f (time left: %.1f minutes)' % (ekin, tleft/60) output.write('%.8f\n' % ekin) output.write('&\n') output.close() temperatures = np.array(temperatures) mean = sum(temperatures) / len(temperatures) print 'Mean temperature:', mean, 'eV' print print 'This test is statistical, and may in rare cases fail due to a' print 'statistical fluctuation.' print assert abs(mean - temp) <= reltol*temp, 'Deviation is too large.' print 'Mean temperature:', mean, ' in ', temp, ' +/- ', reltol*temp return fitdata, params, temperatures
def molecular_dynamics(molecule, calculator, temperature=300.0, sample_interval=10, total_time=10.0, time_step=0.1, seed=None): """ Run molecular dynamics on a structure """ if seed is not None: np.random.seed(seed) dt = time_step * ase.units.fs temp = temperature * ase.units.kB steps = int(total_time * 1000.0 / time_step) velocitydistribution.MaxwellBoltzmannDistribution(molecule, temp, force_temp=True) velocitydistribution.Stationary(molecule) velocitydistribution.ZeroRotation(molecule) print("Initial temperature from velocities %.2f" % molecule.get_temperature()) print("Performing %d steps of %f fs for a total time of %f ps" % (steps, time_step, total_time)) molecule.set_calculator(calculator) # dyn = Langevin( # molecule, # 1.0*ase.units.fs, # temp, # friction=0.001, # logfile='-', # loginterval=sample_interval # ) dyn = VelocityVerlet(molecule, dt, logfile='-', loginterval=sample_interval, trajectory='dynamics.traj') md_path = [] count_steps = 0 ave_temp = 0 def log_md_path(atoms): nonlocal md_path nonlocal count_steps nonlocal ave_temp if count_steps % sample_interval == 0: md_path.append(atoms.copy()) ave_temp += atoms.get_temperature() count_steps += 1 start_time = time.time() dyn.attach(log_md_path, 10, molecule) dyn.run(steps) end_time = time.time() print("Time to sample dynamics %.2f s" % (end_time - start_time)) #ave_temp /= len(md_path) #print("Total MD time %.2f" % (steps / 1000.0)) #print("Average Temperature during MD %.2f" % (ave_temp)) return md_path
(options, args) = parser.parse_args() def printenergy(a, it, t0): """Function to print the potential, kinetic and total energy""" epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) t_now = time() print('Step: %4d [%6.2f]: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV ' % (\ it, t_now-t0, epot, ekin, ekin / (1.5 * units.kB), epot + ekin)) return t_now ff = PyXtal_FF(model={'system': ["Si"]}, logo=False) ff.run(mode='predict', mliap=options.file) calc = PyXtalFFCalculator(ff=ff) si = bulk('Si', 'diamond', a=5.459, cubic=True) si = si * 5 print("MD simulation for ", len(si), " atoms") si.set_calculator(calc) MaxwellBoltzmannDistribution(si, 300 * units.kB) dyn = VelocityVerlet(si, 1 * units.fs) # 2 fs time step. t0 = time() for i in range(10): dyn.run(steps=1) t_now = printenergy(si, i, t0) t0 = t_now
atoms.set_pbc(False) atoms.center(vacuum=6.0) atoms.set_velocities(np.zeros_like(atoms.get_positions())) cell_c = np.sum(atoms.get_cell()**2, axis=1)**0.5 N_c = 16 * np.round(cell_c / (0.25 * 16)) calc = GPAW(gpts=N_c, nbands=1, basis='dzp', setups={'Na': '1'}, txt=name + '_gs.txt') atoms.set_calculator(calc) atoms.get_potential_energy() calc.write(name + '_gs.gpw', mode='all') del atoms, calc time.sleep(10) while not os.path.isfile(name + '_gs.gpw'): print 'Node %d waiting for file...' % world.rank time.sleep(10) world.barrier() tdcalc = GPAW(name + '_gs.gpw', txt=name + '_td.txt') tdcalc.forces.reset() #XXX debug tdcalc.initialize_positions() atoms = tdcalc.get_atoms() traj = PickleTrajectory(name + '_td.traj', 'w', atoms) verlet = VelocityVerlet(atoms, timestep * 1e-3 * fs, logfile=paropen(name + '_td.verlet', 'w'), trajectory=traj) verlet.attach(Timing(paropen(name + '_td.log', 'w')), ndiv, atoms) verlet.run(niter) traj.close()
Z_of_type = {1:26} atom_types = {'Fe':1,} at = ase.io.read('lammps.data', format='lammps-data', Z_of_type=Z_of_type, units='real') header = ["units real", "atom_style full", "boundary p p p", "box tilt large", "pair_style lj/cut/coul/long 12.500", "bond_style harmonic", "angle_style harmonic", "kspace_style ewald 0.0001", "read_data lammps.data"] cmds = [] lammps = LAMMPSlib(lammps_header=header, lmpcmds=cmds, atom_types=atom_types, create_atoms=False, create_box=False, boundary=False, keep_alive=True, log_file='test.log') at.set_calculator(lammps) dyn = VelocityVerlet(at, 1 * units.fs) energy = at.get_potential_energy() energy_ref = 2041.41198295 diff = abs((energy - energy_ref) / energy_ref) assert diff < 1e-10 dyn.run(10) energy = at.get_potential_energy() energy_ref = 312.431585607 diff = abs((energy - energy_ref) / energy_ref) assert diff < 1e-10, "%d" % energy
# pass def __repr__(self): return 'Push atoms out of the cell back to the cell' def copy(self): return ConstantForce(a=self.index, force=self.force) if __name__ == '__main__': from ase.cluster.cubic import FaceCenteredCubic from ase.calculators.emt import EMT from ase.md.verlet import VelocityVerlet from ase.units import fs from constantforce import ConstantForce atoms = FaceCenteredCubic( 'Ag', [(1, 0, 0)], [1], 4.09) atoms.center(10) atoms.pbc = True atoms.set_calculator( EMT() ) cf = ConstantForce( 10, [0,1,0] ) # y=dircted force ic = ImprisonConstraint() atoms.set_constraint( [cf, ic] ) md = VelocityVerlet( atoms, 1*fs, trajectory = 'cf_test.traj', logfile='-' ) md.run(200) #~ from ase.visualize import view #~ view(atoms)
""" # This section imports the Python packages required during this exercise. from MorseCalculator import MorsePotential from ase.io import write, read from ase import units from ase.md.verlet import VelocityVerlet # Parameters for the Morse potential for Cu D = 0.3429 r0 = 2.866 alpha = 1.3588 atoms = read('berendsen.traj', index=-1) atoms.set_calculator(MorsePotential(D=D, alpha=alpha, r0=r0)) del atoms[39] open('md.log', 'w').close() # clean current log file dyn = VelocityVerlet(atoms, dt=5 * units.fs, trajectory='md.traj', logfile='md.log') dyn.run(10000) write('md.xyz', read('md.traj@:')) # Here is some code missing!
dist = 0.001 energy += self.A / dist**self.alpha return energy def __repr__(self): return 'Repulsion potential' def copy(self): return CentralRepulsion(self, R=self.R, A=self.A, alpha=self.alpha) if __name__ == '__main__': from ase.cluster.cubic import FaceCenteredCubic from ase.calculators.emt import EMT from ase.md.verlet import VelocityVerlet from ase.units import fs atoms = FaceCenteredCubic('Ag', [(1, 0, 0)], [1], 4.09) atoms.center(10) atoms.set_calculator(EMT()) c = ConstantForce(10, [0, 1, 0]) # y=dircted force atoms.set_constraint(c) md = VelocityVerlet(atoms, 1*fs, trajectory='cf_test.traj', logfile='-') md.run(100) # from ase.visualize import view # view(atoms)
# Describe the interatomic interactions with the Effective Medium Theory atoms.set_calculator(lammps['ref']) np.random.seed(42) # Set the momenta corresponding to T=300K MaxwellBoltzmannDistribution(atoms, 1000 * units.kB) # We want to run MD with constant energy using the VelocityVerlet algorithm. dyn = VelocityVerlet(atoms, 1 * 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) delta = np.max(np.abs(a.get_forces() - lammps['our'].get_forces(a))) print('Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV d=%.3e' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin, delta)) from ase.io.trajectory import Trajectory traj = Trajectory('example.traj', 'w', atoms) dyn.attach(traj.write, interval=1) # Now run the dynamics printenergy(atoms) for i in range(100): dyn.run(1) printenergy(atoms)
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
velocities_t1 = velocities coordinates_t1 = coordinates force_up_t1 = force_up_t2 force_down_t1 = force_down_t2 force_mid_t1 = force_mid_t2 # condition to avoid hops immediately after each other if skip_next: if skip_count == 3: skip_count = 0 skip_next = False else: skip_count += 1 # if the hop was accepted if hop: # decrement j_md because we made one MD step back j_md -= 1 skip_next = True hop = False # increment global MD counter j_md += 1 """Launcher for molecular dynamics""" # run MD for n_md steps with TSH module dyn.attach(tsh, interval=1) dyn.run(n_md) # close data files df.close() #df2.close()
crack_pos = find_tip_stress_field(atoms) atoms.info['crack_pos_x'] = crack_pos[0] atoms.info['d_crack_pos_x'] = crack_pos[0] - orig_crack_pos[0] print log_format % atoms.info dynamics.attach(printstatus) # Check if the crack has advanced, and stop incrementing the strain if it has def check_if_cracked(atoms): crack_pos = find_tip_stress_field(atoms) # stop straining if crack has advanced more than tip_move_tol if (not atoms.info['is_cracked'] and (crack_pos[0] - orig_crack_pos[0]) > params.tip_move_tol): atoms.info['is_cracked'] = True del atoms.constraints[atoms.constraints.index(strain_atoms)] dynamics.attach(check_if_cracked, 1, atoms) # Save frames to the trajectory every `traj_interval` time steps trajectory = NetCDFTrajectory(params.traj_file, mode='w') dynamics.attach(trajectory.write, params.traj_interval) # Start running! dynamics.run(params.nsteps)
def update_atoms(self): pass def set_atoms(self, atoms): self.atoms = atoms self.update_atoms() if __name__ == '__main__': from ase import Atoms atoms = Atoms(symbols='CeO', cell=[2, 2, 5], positions=np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 2.4935832]])) atoms[0].charge = +4 atoms[1].charge = -2 calc = Buck({('Ce', 'O'): (1176.3, 0.381, 0.0)}) #calc = Buck( {('Ce', 'O'): (0.0, 0.149, 0.0)} ) atoms.set_calculator(calc) print('Epot = ', atoms.get_potential_energy()) print('Force = ', atoms.get_forces()) from ase.md.verlet import VelocityVerlet dyn = VelocityVerlet(atoms, dt=0.1*units.fs, trajectory='test.traj', logfile='-') dyn.run(1000) print('coodrs = ', atoms.get_positions()) from ase.visualize import view view(atoms)
else: i += 1 c = FixAtoms(indices = array) atoms.set_constraint(c) # relax with Quasi Newtonian qn = QuasiNewton(atoms, trajectory='qn.traj') qn.run(fmax=0.001) write('qn.final.xyz', atoms) # Set the momenta corresponding to T=300K MaxwellBoltzmannDistribution(atoms, 300*units.kB) print 'Removing linear momentum and angular momentum' Stationary(atoms) # zero linear momentum ZeroRotation(atoms) # zero angular momentum # We want to run MD using the VelocityVerlet algorithm. dyn = VelocityVerlet(atoms, 0.1*units.fs, trajectory='moldyn4.traj') # save trajectory. #Function to print the potential, kinetic and total energy. def printenergy(a=atoms): #store a reference to atoms in the definition. 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)
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 test = read('geo_end.gen')
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)
ZeroRotation(atoms) # zero angular momentum # We want to run MD using the VelocityVerlet algorithm. dyn = VelocityVerlet(atoms, 0.1*units.fs, trajectory='moldyn4.traj') # save trajectory. #Function to print the potential, kinetic and total energy. def printenergy(t=atoms): #store a reference to atoms in the definition. epot = t.get_potential_energy() / len(t) ekin = t.get_kinetic_energy() / len(t) print ("Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) Etot = %.3feV" % (epot, ekin, ekin/(1.5*units.kB), epot+ekin)) ETOT = ekin + epot print ETOT x_dist = atoms.get_distance(a0 = 0, a1 = 1) forces = atoms.get_forces() OP.append(x_dist) OP.append(ekin+epot) dyn.attach(printenergy, interval=10) # Now run the dynamics dyn.run(400) OP_f = [OP[i:i+2] for i in xrange(0,len(OP),2)] OP_f_text = np.savetxt('out.tmp', OP_f) # reads array and saves into a file as a string OP_f_infile = open('out.tmp','r') # open file to write string array onto OP_f_text = OP_f_infile.read() text_file.write(OP_f_text) text_file.close()