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 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_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_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 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 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)
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
else: atoms = AtomsReader(args.input_file)[-1] atoms.set_calculator(qm_pot) if args.restart: #delete certain keys so they don't cause problem in write_xyz. del_keys = ['force','forces', 'forces0'] array_keys = atoms.arrays.keys() prop_keys = atoms.properties.keys() for key in del_keys: if key in array_keys: del(atoms.arrays[key]) #thermalize atoms if not args.restart: 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)) def write_slab(a=atoms): write_xyz('surf_traj.xyz', a, append=True) dynamics.attach(print_context, interval=1) dynamics.attach(write_slab, interval=1) dynamics.run(nsteps)
dynamics = VelocityVerlet(atoms, params.timestep) check_force_error = False if not params.classical: qmmm_pot.set(calc_weights=True) dynamics.state_label = 'D' else: print 'Initializing LOTF Dynamics' dynamics = LOTFDynamics(atoms, params.timestep, params.extrapolate_steps, check_force_error=check_force_error) system_timer('init_dynamics') #Function to update the QM region at the beginning of each extrapolation cycle if not check_force_error: if params.extrapolate_steps == 1: if not params.classical: dynamics.attach(update_qm_region, 1, dynamics.atoms) else: # choose appropriate update function for defects or crack. # or grainboundary. print 'Setting Update Function' if geom =='disloc': dynamics.set_qm_update_func(update_qm_region) elif geom =='crack': dynamics.set_qm_update_func(update_qm_region_crack) else: print 'No geometry chosen', 1/0 if check_force_error: pred_corr_logfile = open(os.path.join(params.rundir, 'pred-corr-error.txt'), 'w') dynamics.attach(log_pred_corr_errors, 1, dynamics, pred_corr_logfile)
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()
atoms.set_calculator(qmmm_pot) #Otherwise it will recover temperature from the previous run. #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,
# 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)
pot = Potential('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 trajectory = AtomsWriter('{0}.traj.xyz'.format(input_file)) print 'Running Crack Simulation'
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))) 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)
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
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))) 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) def atom_straining(atoms): crack_pos = find_crack_tip_stress_field(atoms, calc=mm_pot) # keep straining until the crack tip has advanced to tip_move_tol if not atoms.info['is_cracked'] and (crack_pos[0] - orig_crack_pos[0]) < tip_move_tol: strain_atoms.apply_strain(atoms) elif not atoms.info['is_cracked']: atoms.info['is_cracked'] = True dynamics.attach(atom_straining, 1, atoms) # Save frames to the trajectory every `traj_interval` time steps
def run_md(atoms, id): # Read settings settings = read_settings_file() # Use KIM for potentials from OpenKIM use_kim = True # 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']) traj = Trajectory('ar.traj', 'w', atoms) dyn.attach(traj.write, interval=1000) # Identity number given as func. parameter to keep track of properties # Number of decimals for most calculated properties decimals = settings['decimals'] # Calculation and writing of properties properties.initialize_properties_file(atoms, id, decimals) dyn.attach(properties.calc_properties, 100, old_atoms, atoms, id, decimals) # 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=1000) logger() dyn.run(settings['max_steps']) return atoms
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() ############################################################################### # To check the correctness of this dynamics, we use pytest to test if it is on
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)
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 trajectory = AtomsWriter('{0}.traj.xyz'.format(input_file))
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()
log_format = ('%(label)-4s%(time)12.1f%(temperature)12.6f'+ '%(strain)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'] = get_temperature(atoms) atoms.info['strain'] = get_strain(atoms) # FIXME no local virial in TS, need another way to track the crack atoms.info['crack_pos_x'] = 0. atoms.info['d_crack_pos_x'] = 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) # 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)
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))) atoms.info['strain'] = get_strain(atoms) atoms.info['G'] = get_energy_release_rate(atoms) / (units.J / units.m**2) 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 enough and apply strain if it has not def check_if_crack_advanced(atoms): crack_pos = find_tip_stress_field(atoms) # strain if crack has not advanced more than tip_move_tol if crack_pos[0] - orig_crack_pos[0] < params.tip_move_tol: strain_atoms.apply_strain(atoms) dynamics.attach(check_if_crack_advanced, 1, atoms) # Save frames to the trajectory every `traj_interval` time steps trajectory = NetCDFTrajectory(params.traj_file, mode='w')
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))) 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) 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) trajectory = AtomsWriter(traj_file) dynamics.attach(trajectory, traj_interval, atoms) dynamics.run(nsteps)
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
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))) atoms.info['strain'] = get_strain(atoms) atoms.info['G'] = get_energy_release_rate(atoms) / (units.J / units.m**2) 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)
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()
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)
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)