def init_dynamics(self, Nm, V, L, dt, T): self.L = L # Generate the box of junk self.__generategarbagebox__(Nm, L, T) # Make mol self.mol = Atoms(symbols=self.S, positions=self.X) # Set box and PBC self.mol.set_cell(([[L, 0, 0], [0, L, 0], [0, 0, L]])) self.mol.set_pbc((True, True, True)) # Set ANI calculator # Set ANI calculator self.mol.set_calculator(ANIENS(self.aens)) #self.mol.set_calculator(ANI(False)) #self.mol.calc.setnc(self.ncl[0]) # Give molecules random velocity acc_idx = 0 vel = np.empty_like(self.X) for n in self.Na: rv = np.random.uniform(-V, V, size=(3)) for k in range(n): vel[acc_idx + k, :] = rv acc_idx += n #print(vel) self.mol.set_velocities(vel) # Declare Dyn self.dyn = Langevin(self.mol, dt * units.fs, T * units.kB, 0.1)
def init_dynamics(self, Nm, Nembed, V, L, dt, T): self.L = L # Generate the box of junk self.__generategarbagebox__(Nm, Nembed, L, T) # Make mol self.mol = Atoms(symbols=self.S, positions=self.X) # Set box and PBC self.mol.set_cell(([[L, 0, 0], [0, L, 0], [0, 0, L]])) self.mol.set_pbc((True, True, True)) # Set ANI calculator self.mol.set_calculator(ANIENS(self.aens)) # Open MD output #self.mdcrd = open(xyzfile, 'w') # Open MD output #self.traj = open(trjfile, 'w') # Set the velocities corresponding to a boltzmann dist @ T/4.0 MaxwellBoltzmannDistribution(self.mol, 300.0 * units.kB) # Declare Dyn self.dyn = Langevin(self.mol, dt * units.fs, T * units.kB, 0.1)
def smash_it(system): """Run a simple NVT molecular dynamics simulation for 0.1 ps at 200 k using the effective medium theory on a supplied system. Parameters ---------- system : `ase.Atoms` The system that is to be simulated. Returns ------- traj : `list` [`ase.Atoms`] A list of `ase.Atoms` objects comprising the system's trajectory. """ # Tell the system to use the EMT calculator system.set_calculator(EMT()) # Set up the NVT simulation using the Langevin thermostat dyn = Langevin(system, 0.01 * units.fs, 200 * units.kB, 0.002) # Create a list to hold the trajectory & a function to populate it traj = [] def update_traj(a=system): traj.append(a.copy()) # Attach the trajectory populator dyn.attach(update_traj, interval=10) # Run the molecular dynamics simulation from 10000 steps dyn.run(10000) # Return the trajectory return traj
def md(molecule, model, device, output, nsteps, temperature, step, friction): start = time.time() mm = Mol2(molecule) pos = mm.get_coordinates() labels = ''.join(mm.get_symbols()) device = torch.device(device) if model.lower() == 'ani1x': model = torchani.models.ANI1x() elif model.lower() == 'ani1ccx': model = torchani.models.ANI1ccx() else: print("unknwon model {:s}".format(model)) sys.exit(1) assert isinstance(model, torchani.models.ANI1x) or isinstance(model, torchani.models.ANI1ccx) atom_group = Atoms(symbols=labels, positions=pos, calculator=model.ase()) print("step {:12d}\tenergy {:12.4f}".format(0, atom_group.get_total_energy())) dyn = Langevin(atom_group, 1*units.fs, temperature*units.kB, friction) for i in range(nsteps): dyn.run(step) print("step {:12d}\tenergy {:12.4f}".format((i + 1)*step, atom_group.get_total_energy())) mm.coordinates = atom_group.get_positions() if output is not None: mm.write(output + '_{:06d}.mol2'.format(i)) print("time {:12.4f}".format(time.time() - start)) sys.exit(0)
def testForceAgainstDefaultNeighborList(self): atoms = Diamond(symbol="C", pbc=False) builtin = torchani.neurochem.Builtins() calculator = torchani.ase.Calculator(builtin.species, builtin.aev_computer, builtin.models, builtin.energy_shifter) default_neighborlist_calculator = torchani.ase.Calculator( builtin.species, builtin.aev_computer, builtin.models, builtin.energy_shifter, True) atoms.set_calculator(calculator) dyn = Langevin(atoms, 5 * units.fs, 50 * units.kB, 0.002) def test_energy(a=atoms): a = a.copy() a.set_calculator(calculator) e1 = a.get_potential_energy() a.set_calculator(default_neighborlist_calculator) e2 = a.get_potential_energy() self.assertLess(abs(e1 - e2), tol) dyn.attach(test_energy, interval=1) dyn.run(500)
def run_md(self, f, Tmax, steps, n_steps, nmfile=None, displacement=0, min_steps=0, sig=0.34, t=0.1, nm=0, record=False): X, S, Na, cm = hdt.readxyz2(f) if nmfile != None: mode=self.get_mode(nmfile, Na, mn=nm) X=X+mode*np.random.uniform(-displacement,displacement) X=X[0] mol=Atoms(symbols=S, positions=X) mol.set_calculator(ANIENS(self.net,sdmx=20000000.0)) f=os.path.basename(f) T_eff = float(random.randrange(5, Tmax, 1)) # random T (random velocities) from 0K to TK minstep_eff = float(random.randrange(1, min_steps, 1)) # random T (random velocities) from 0K to TK dyn = Langevin(mol, t * units.fs, T_eff * units.kB, 0.01) MaxwellBoltzmannDistribution(mol, T_eff * units.kB) # steps=10000 #10000=1picosecond #Max number of steps to run # n_steps = 1 #Number of steps to run for before checking the standard deviation hsdt_Na=[] evkcal=hdt.evtokcal if record==True: #Records the coordinates at every step of the dynamics fname = f + '_record_' + str(T_eff) + 'K' + '.xyz' #name of file to store coodinated in def printenergy(name=fname, a=mol): """Function to print the potential, kinetic and total energy.""" fil= open(name,'a') Na=a.get_number_of_atoms() c = a.get_positions(wrap=True) fil.write('%s \n comment \n' %Na) for j, i in zip(a, c): fil.write(str(j.symbol) + ' ' + str(i[0]) + ' ' + str(i[1]) + ' ' + str(i[2]) + '\n') fil.close() dyn.attach(printenergy, interval=1) e=mol.get_potential_energy() #Calculate the energy of the molecule. Must be done to get the standard deviation s=mol.calc.stddev stddev = 0 tot_steps = 0 failed = False while (tot_steps <= steps): if stddev > sig and tot_steps > minstep_eff: #Check the standard deviation self.hstd.append(stddev) c = mol.get_positions() s = mol.get_chemical_symbols() Na=mol.get_number_of_atoms() self.Na_train.append(Na) self.coor_train.append(c) self.S_train.append(s) failed=True break else: #if the standard deviation is low, run dynamics, then check it again tot_steps = tot_steps + n_steps dyn.run(n_steps) stddev = evkcal*mol.calc.stddev c = mol.get_positions() s = mol.get_chemical_symbols() e=mol.get_potential_energy() #print("{0:.2f}".format(tot_steps*t),':',"{0:.2f}".format(stddev),':',"{0:.2f}".format(evkcal*e)) return c, s, tot_steps*t, stddev, failed, T_eff
def langevin_dynamics(atoms, dt, tem, friction, trajectory, loginterval, append): dyn = Langevin(atoms, dt * units.fs, temperature_K=tem, friction=friction, rng=np.random, trajectory=trajectory, append_trajectory=append, loginterval=loginterval) return dyn
def testWithNumericalForceWithPBCEnabled(self): # Run a Langevin thermostat dynamic for 100 steps and after the dynamic # check once that the numerical and analytical force agree to a given # relative tolerance atoms = Diamond(symbol="C", pbc=True) calculator = self.model.ase() atoms.set_calculator(calculator) dyn = Langevin(atoms, 5 * units.fs, 30000000 * units.kB, 0.002) dyn.run(100) f = atoms.get_forces() fn = get_numeric_force(atoms, 0.001) self.assertEqual(f, fn, rtol=0.1, atol=0.1)
def testWithNumericalForceWithPBCEnabled(self): atoms = Diamond(symbol="C", pbc=True) calculator = torchani.models.ANI1x().ase() atoms.set_calculator(calculator) dyn = Langevin(atoms, 5 * units.fs, 30000000 * units.kB, 0.002) dyn.run(100) f = torch.from_numpy(atoms.get_forces()) fn = get_numeric_force(atoms, 0.001) df = (f - fn).abs().max() avgf = f.abs().mean() if avgf > 0: self.assertLess(df / avgf, 0.1)
def hyster_study(edge, folder=None): if folder == None: folder = os.getcwd() print folder for fileC in os.listdir(folder): if fileC[-6:] == '.simul': fileC = folder + fileC _, length, _, _, v, T, dt, fric, dtheta, \ thresZ, interval, deltaY, theta, M, edge = read_simul_params_file(fileC) mdfile = fileC[:-6] + '.traj' traj = PickleTrajectory(mdfile, 'r') atoms_init = traj[0] constraints, _, twist, rend_b, rend_t = get_constraints(atoms_init, edge, \ bond, None, key = 'twist_p') #constraints, _, rend_b, rend_t = get_constraints(atoms_init, edge, \ # bond, None, key = 'twist_p') atoms = traj[-1] atoms.set_constraint(constraints) vels = (traj[-2].positions - traj[-1].positions) / (interval * dt) atoms.set_velocities(vels) calc = LAMMPS(parameters=get_lammps_params()) atoms.set_calculator(calc) view(atoms) dyn = Langevin(atoms, dt * units.fs, T * units.kB, fric) twist.set_angle(theta) dyn.run(10 * interval) view(atoms) traj_new = PickleTrajectory(fileC[:-6] + '_hyst.traj', 'w', atoms) mdlogf = fileC[:-6] + '_hyst.log' do_dynamics(mdlogf, atoms, dyn, rend_b, rend_t, v, dt, deltaY, \ theta, dtheta, length, thresZ, \ interval, traj_new, M, twist) mdhystf = fileC[:-6] + '_hyst.traj' logfile = fileC[:-6] + '.log' append_files(logfile, mdlogf, logfile[:-4] + '_comp.log') call([ 'ase-gui', mdfile, mdhystf, '-o', logfile[:-4] + '_comp.traj' ])
def __run_rand_dyn__(self, mid, T1, T2, dt, Nc, Ns, dS): # Setup calculator mol = self.mols[0].copy() # Setup PBC if active if self.pbc: mol.set_cell(([[self.pbl, 0, 0], [0, self.pbl, 0], [0, 0, self.pbl]])) mol.set_pbc((self.pbc, self.pbc, self.pbc)) # Setup calculator mol.set_calculator(ANIENS(self.aens)) #mol.set_calculator(ANI(False)) #mol.calc.setnc(self.ncl[0]) # Set chemical symbols spc = mol.get_chemical_symbols() # Set the velocities corresponding to a boltzmann dist @ T/4.0 MaxwellBoltzmannDistribution(mol, T1 * units.kB) # Set the thermostat dyn = Langevin(mol, dt * units.fs, T1 * units.kB, 0.02) dT = (T2 - T1)/Nc #print('Running...') for i in range(Nc): # Set steps temperature dyn.set_temperature((T1 + dT*i) * units.kB) # Do Ns steps of dynamics dyn.run(Ns) # Return sigma sigma = hdt.evtokcal * mol.calc.stddev ekin = mol.get_kinetic_energy() / len(mol) # Check for dynamics failure if sigma > dS: self.Nbad += 1 self.X.append(mol.get_positions()) #print('Step:', dyn.get_number_of_steps(), 'Sig:', sigma, 'Temp:', # str(ekin / (1.5 * units.kB)) + '(' + str(T1 + dT * i) + ')') return True,dyn.get_number_of_steps() return False,dyn.get_number_of_steps()
def _testForce(self, pbc): atoms = Diamond(symbol="C", pbc=pbc) builtin = torchani.neurochem.Builtins() calculator = torchani.ase.Calculator( builtin.species, builtin.aev_computer, builtin.models, builtin.energy_shifter) atoms.set_calculator(calculator) dyn = Langevin(atoms, 5 * units.fs, 30000000 * units.kB, 0.002) dyn.run(100) f = torch.from_numpy(atoms.get_forces()) fn = get_numeric_force(atoms, 0.001) df = (f - fn).abs().max() avgf = f.abs().mean() if avgf > 0: self.assertLess(df / avgf, 0.1)
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 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_static(self): """ Static run function, which uses the ASEAdapter to connect the pyiron interactive reference job with the Langevin thermostat implemented in ASE, by setting the ASEAdapter as a replacement of the ASE atoms object. """ self.status.running = True self.ref_job_initialize() aseadapter = AseAdapter(self.ref_job, self._fast_mode) langevin = Langevin(atoms=aseadapter, timestep=self.input['time_step'] * units.fs, temperature=self.input['temperature'] * units.kB, friction=self.input['friction'], fixcm=True) langevin.run(self.input['ionic_steps']) self.status.collect = True aseadapter.interactive_close() self._finish_job()
def get_dynamics(atoms, mcfm_pot, T=300): # ------ Set up logfiles traj_interval = 10 thermoPrintstatus_log = open("log_thermoPrintstatus.log", "w") outputTrajectory = open("log_trajectory.xyz", "w") mcfmError_log = open("log_mcfmError.log", "w") # ------ Let optimiser use the base potential and relax the per atom energies mcfm_pot.qm_cluster.flagging_module.ema_parameter = 0.1 mcfm_pot.qm_cluster.flagging_module.qm_flag_potential_energies =\ np.ones((len(atoms), 2), dtype=float) * 1001 # ------ Minimize positions opt = FIRE(atoms) optimTrajectory = open("log_optimizationTrajectory.xyz", "w") opt.attach(trajectory_writer, 1, atoms, optimTrajectory, writeResults=True) opt.run(fmax=0.05, steps=1000) # ------ Define ASE dyamics sim_T = T * units.kB MaxwellBoltzmannDistribution(atoms, 2 * sim_T) timestep = 5e-1 * units.fs friction = 1e-2 dynamics = Langevin(atoms, timestep, sim_T, friction, fixcm=False) dynamics.attach(mcfm_thermo_printstatus, 100, 100, dynamics, atoms, mcfm_pot, logfile=thermoPrintstatus_log) dynamics.attach(trajectory_writer, traj_interval, atoms, outputTrajectory, writeResults=False) dynamics.attach(mcfm_error_logger, 100, 100, dynamics, atoms, mcfm_pot, logfile=mcfmError_log) return dynamics
def run_md(atoms, md_temperature = 1000*kB, md_step_size = 1*fs, md_steps=100, md_interval=100, friction=0.02): natoms=atoms.get_number_of_atoms() #atoms.set_calculator(self.opt_calculator) atoms_md = [] e_log = [] atoms_md.append(atoms.copy()) MaxwellBoltzmannDistribution(atoms=atoms, temp=md_temperature) dyn = Langevin(atoms, md_step_size, md_temperature, friction) def md_log(atoms=atoms): atoms_md.append(atoms.copy()) epot=atoms.get_potential_energy() ekin=atoms.get_kinetic_energy() temp = ekin / (1.5 * kB * natoms) e_log.append([epot, ekin, temp]) traj = Trajectory('Au_md.traj', 'w', atoms) # Output MD trajectory before it is treatment dyn.attach(traj.write, interval=10) dyn.attach(md_log, interval=md_interval) dyn.run(md_steps) return atoms_md, e_log
def md_calculation(fcp_file): from ase import units from ase.io.trajectory import Trajectory from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase.md.langevin import Langevin from ase.md import MDLogger if 'fcc' in fcp_file: ref_cell = read(ref_fcc) P = np.array([[-1, 1, 1], [1, -1, 1], [1, 1, -1]]) P *= 3 atoms = make_supercell(ref_cell, P) else: raise ValueError("Unknown phase") fcp = ForceConstantPotential.read(fcp_file) fcs = fcp.get_force_constants(atoms) calc = ForceConstantCalculator(fcs) atoms.set_calculator(calc) temperature = 200 number_of_MD_steps = 100 time_step = 5 # in fs dump_interval = 10 traj_file = "data/md_" + fcp_file.split('.')[0] + '{}.traj'.format( temperature) log_file = "data/md_log_{}.log".format(temperature) dyn = Langevin(atoms, time_step * units.fs, temperature * units.kB, 0.02) logger = MDLogger(dyn, atoms, log_file, header=True, stress=False, peratom=True, mode='w') traj_writer = Trajectory(traj_file, 'w', atoms) dyn.attach(logger, interval=dump_interval) dyn.attach(traj_writer.write, interval=dump_interval) # run MD MaxwellBoltzmannDistribution(atoms, temperature * units.kB) dyn.run(number_of_MD_steps)
def test_usage(self): atoms = fcc111('Al', size=(4, 4, 9), orthogonal=True) atoms.set_pbc(True) atoms.center(axis=2, vacuum=10.0) z = atoms.positions[:, 2] top_mask = z > z[115] - 0.1 bottom_mask = z < z[19] + 0.1 calc = EMT() atoms.calc = calc damping = pc.AutoDamping(C11=500 * GPa, p_c=0.2) Pdir = 2 vdir = 0 P = 5 * GPa v = 100.0 * m / s dt = 1.0 * fs T = 400.0 t_langevin = 75 * fs gamma_langevin = 1. / t_langevin slider = pc.SlideWithNormalPressureCuboidCell(top_mask, bottom_mask, Pdir, P, vdir, v, damping) atoms.set_constraint(slider) MaxwellBoltzmannDistribution(atoms, 2 * kB * T) atoms.arrays['momenta'][top_mask, :] = 0 atoms.arrays['momenta'][bottom_mask, :] = 0 handle = StringIO() beginning = handle.tell() temps = np.zeros((len(atoms), 3)) temps[slider.middle_mask, slider.Tdir] = kB * T gammas = np.zeros((len(atoms), 3)) gammas[slider.middle_mask, slider.Tdir] = gamma_langevin integrator = Langevin(atoms, dt, temps, gammas, fixcm=False) logger = pc.SlideLogger(handle, atoms, slider, integrator) logger.write_header() logger() images = [] integrator.attach(logger) integrator.attach(lambda: images.append(atoms.copy())) integrator.run(50) handle.seek(beginning) pc.SlideLog(handle) handle.close()
def MD(): old_stdout = sys.stdout sys.stdout = mystdout = StringIO() orig_stdout = sys.stdout f = open('out.txt', 'w') sys.stdout = f #f = open('out_' + str(temp) + '.txt', 'w') #sys.stdout = f Tmin = 1000 Tmax = 15000 a0 = 5.43 N = 1 atoms = Diamond(symbol='Si', latticeconstant=a0) atoms *= (N, N, N) atoms.set_calculator(model.calculator) MaxwellBoltzmannDistribution(atoms, Tmin * units.kB) ###is this allowed? Stationary(atoms) # zero linear momentum ZeroRotation(atoms) def printenergy(a=atoms): epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) print(ekin) traj = Trajectory('Si.traj', 'w', atoms) for temp in np.linspace(Tmin, Tmax, 5): dyn = Langevin(atoms, 5 * units.fs, units.kB * temp, 0.002) dyn.attach(traj.write, interval=1) dyn.attach(printenergy, interval=1) dyn.run(100) sys.stdout = orig_stdout f.close()
def shearDyn(width, ratio, edge, save=False, force_dir_update=True): atoms, L, W, length_int, b_idxs = create_stucture(ratio, width, edge, key='rib+base') view(atoms) # FIXES constraints, add_LJ, rend_b, rend_t = get_constraints( atoms, edge, bond, b_idxs) # END FIXES # CALCULATOR LAMMPS calc = LAMMPS(parameters=get_lammps_params()) atoms.set_calculator(calc) # END CALCULATOR # TRAJECTORY add = '' if force_dir_update: add = '_ff' mdfile, mdlogfile, mdrelax, simulfile = get_fileName('LJ', edge + add, width, \ length_int, int(T), taito) if save: traj = PickleTrajectory(mdfile, 'w', atoms) else: traj = None #data = np.zeros((M/interval, 5)) # RELAX atoms.set_constraint(add_LJ) dyn = BFGS(atoms, trajectory=mdrelax) dyn.run(fmax=0.05) # FIX AFTER RELAXATION atoms.set_constraint(constraints) # DYNAMICS dyn = Langevin(atoms, dt * units.fs, T * units.kB, fric) n = 0 header = '#t [fs], shift y [Angstrom], Rad, epot_tot [eV], ekin_tot [eV], etot_tot [eV] \n' write_line_own(mdlogfile, header, 'w') if T != 0: # put initial MaxwellBoltzmann velocity distribution mbd(atoms, T * units.kB) deltaY = 0. eta = 1.1 # ratio between the lengths of the streched and compressed side of the ribbon. r = L / W # length to width ratio. deltaYMax = W / 2. * (eta + 1) / (eta - 1) * (1 - np.cos(2 * r * (eta - 1) / (eta + 1))) # Estimate for the required shift dy = v * dt M = deltaYMax / dy interval = int(M / 1000) kink_formed = False dir_vec = np.array([0., 1., 0.]) i, m = 0, 0 print 'width = %i, length = %i' % (width, length_int) while m <= int(M / 30): if tau < i * dt: deltaY += dy * dir_vec[1] for ind in rend_b: atoms[ind].position[:] += dy * dir_vec dyn.run(1) if i % interval == 0: epot, ekin = saveAndPrint(atoms, traj, False)[:2] R = get_R(L, deltaY) if force_dir_update: dir_vec = get_dir(atoms, rend_b, rend_t) data = [i * dt, deltaY, R, epot, ekin, epot + ekin] if save: stringi = '' for k, d in enumerate(data): if k == 0: stringi += '%.2f ' % d elif k == 1 or k == 2: stringi += '%.4f ' % d else: stringi += '%.12f ' % d write_line_own(mdlogfile, stringi + '\n', 'a') n += 1 if thres_Z < np.max(atoms.positions[:, 2]) and m == 0: idxs = np.where(thres_Z < atoms.positions[:, 2]) write_line_own(mdlogfile, '# Kink! at idxs %s' % str(idxs) + '\n', 'a') print ' kink formed! ' kink_formed = True if save and T != 0 and i * dt == tau: write_line_own(mdlogfile, '# Thermalization complete. ' + '\n', 'a') if i % int(M / 100) == 0: print str(i / int(M / 100)) + ' ~ % done' if kink_formed: m += 1 i += 1 make_simul_param_file(simulfile, W, L, width, length_int, v, dy, T, \ dt, fric, thres_Z, interval, deltaY, M, edge)
from ase.md.langevin import Langevin from ase import Atoms from ase import units ccc = MyCalc(forces) atoms = Atoms( mol.element.tolist(), mol.coords.squeeze(), masses=mol.masses.tolist(), charges=mol.charge.tolist(), pbc=True, cell=mol.box.flatten(), calculator=ccc, ) dyn = Langevin(atoms, 2 * units.fs, units.kB * 300, 0.002) # dyn.run(1000) 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) for i in range(20): dyn.run(10)
bottom_mask = np.loadtxt("bottom_mask.txt").astype(bool) top_mask = np.loadtxt("top_mask.txt").astype(bool) damp = pc.AutoDamping(C11, p_c) slider = pc.SlideWithNormalPressureCuboidCell(top_mask, bottom_mask, Pdir, P, vdir, v, damp) atoms.set_constraint(slider) calc = ASE_CALCULATOR_OBJECT # put a specific calculator here atoms.set_calculator(calc) temps = np.zeros((len(atoms), 3)) temps[slider.middle_mask, slider.Tdir] = kB * T gammas = np.zeros((len(atoms), 3)) gammas[slider.middle_mask, slider.Tdir] = gamma_langevin integrator = Langevin(atoms, dt, temps, gammas, fixcm=False) trajectory = Trajectory('slide.traj', 'a', atoms) # append with open('log_slide.txt', 'r', encoding='utf-8') as log_handle: step_offset = pc.SlideLog(log_handle).step[-1] log_handle = open('log_slide.txt', 'a', 1, encoding='utf-8') # line buffered append logger = pc.SlideLogger(log_handle, atoms, slider, integrator, step_offset) integrator.attach(logger) integrator.attach(trajectory) integrator.run(steps_integrate) log_handle.close() trajectory.close()
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.659, cubic=True) si = si * 5 print("MD simulation for ", len(si), " atoms") si.set_calculator(calc) MaxwellBoltzmannDistribution(si, 1000 * units.kB) dyn = Langevin(si, timestep=5 * units.fs, temperature_K=1000, friction=0.02) #dyn = VelocityVerlet(si, 5*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
# Now let's set the calculator for ``atoms``: atoms.set_calculator(calculator) # Now let's minimize the structure: print("Begin minimizing...") opt = BFGS(atoms) opt.run(fmax=0.001) print() # Now create a callback function that print interesting physical quantities: def printenergy(a=atoms): """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)) # We want to run MD with constant energy using the Langevin algorithm # with a time step of 1 fs, the temperature 300K and the friction # coefficient to 0.02 atomic units. dyn = Langevin(atoms, 1 * units.fs, 300 * units.kB, 0.2) dyn.attach(printenergy, interval=50) # Now run the dynamics: print("Beginning dynamics...") printenergy() dyn.run(500)
D = 0.3429 r0 = 2.866 alpha = 1.3588 atoms = FaceCenteredCubic(latticeconstant=1.5, symbol='Cu', pbc=False, size=(3,3,3)) atoms.center(vacuum=100) atoms.set_calculator(MorsePotential(D=D, alpha=alpha, r0=r0)) dyn = FIRE(atoms, trajectory='relax.traj') dyn.run(fmax=0.01) write('relax.xyz', read('relax.traj@:')) # uncomment this line for Task 2 open('langevin.log', 'w').close() # clean current log file # dyn = VelocityVerlet(atoms, dt=1 * units.fs, # trajectory='md.traj', logfile='md.log') # dyn.run(1000) # write('md.xyz', read('md.traj@:')) dyn = Langevin(atoms, timestep= 5*units.fs, temperature = 2500*units.kB, friction = 0.005, trajectory='langevin.traj', logfile='langevin.log') dyn.run(4000) write('langevin.xyz', read('langevin.traj@:')) # uncomment this line for Task 3
def shearDyn(params_set, pot_key, save=False): bond = params_set['bond'] T = params_set['T'] taito = params_set['taito'] dt, fric = params_set['dt'], params_set['fric'] tau = params_set['tau'] vmax = params_set['vmax'] vMAX = params_set['vMAX'] thres_Z = params_set['thresZ'] width = params_set['width'] ratio = params_set['ratio'] edge = params_set['edge'] atoms, L, W, length_int, b_idxs = \ create_stucture(ratio, width, edge, key = 'top', a = bond) mdfile, mdlogfile, mdrelax, simulfile, folder, relaxed \ = get_fileName(pot_key, edge + '_twistRod', width, \ length_int, vmax * 1000, int(T), taito) #view(atoms) # FIXES constraints, add_pot, twist, rend_b, rend_t = \ get_constraints(atoms, edge, bond, b_idxs, \ key = 'twist_p', pot = pot_key) # END FIXES if relaxed: atoms = PickleTrajectory(mdrelax, 'r')[-1] else: trans = trans_atomsKC(atoms.positions[rend_b], edge, bond) atoms.translate(trans) #plot_posits(atoms, edge, bond) # CALCULATOR LAMMPS calc = LAMMPS(parameters=get_lammps_params()) atoms.set_calculator(calc) # END CALCULATOR # TRAJECTORY if save: traj = PickleTrajectory(mdfile, 'w', atoms) else: traj = None #data = np.zeros((M/interval, 5)) # RELAX atoms.set_constraint(add_pot) dyn = BFGS(atoms, trajectory=mdrelax) dyn.run(fmax=0.05) dist = np.linalg.norm(atoms.positions[rend_b] - atoms.positions[rend_t]) twist.set_dist(dist) # FIX AFTER RELAXATION atoms.set_constraint(constraints) # DYNAMICS dyn = Langevin(atoms, dt * units.fs, T * units.kB, fric) header = '#t [fs], shift y [Angstrom], Rad, theta [rad], hmax [A], epot_tot [eV], ekin_tot [eV], etot_tot [eV], F [eV/angst] \n' write_line_own(mdlogfile, header, 'w') if T != 0: # put initial MaxwellBoltzmann velocity distribution mbd(atoms, T * units.kB) y0 = atoms.positions[rend_b, 1] kink_formed = False kink_vanished = False i = 0 print 'width = %i, length = %i, v=%.6f' % (width, length_int, vmax) M_therm = int(tau / dt) dyn.run(M_therm) M = int(2 * L / (np.pi * dt * vmax)) M_min = int(2 * L / (np.pi * dt * vMAX)) dtheta = np.pi / 2 / M dtheta_max = np.pi / 2 / M_min interval = int(M / 1000) theta, time, m = 0., 0., 0 i_kink = 0 while 0. <= theta: if not kink_formed: if theta < np.pi / 4: theta += dtheta_max else: theta += dtheta twist.set_angle(theta) else: if i_kink / 10 < m: theta -= dtheta twist.set_angle(theta) dyn.run(1) if i % interval == 0: epot, ekin = saveAndPrint(atoms, traj, False)[:2] deltaY = atoms.positions[rend_b, 1] - y0 hmax = np.max( atoms.positions[:, 2]) #substract the height of the plane? R = get_R(L, deltaY) data = [time, deltaY, R, theta, hmax, epot, ekin, epot + ekin] if save: stringi = '' for k, d in enumerate(data): if k == 0: stringi += '%.2f ' % d elif k == 1 or k == 2: stringi += '%.4f ' % d else: stringi += '%.12f ' % d write_line_own(mdlogfile, stringi + '\n', 'a') if thres_Z < hmax and not kink_formed: idxs = np.where(thres_Z < atoms.positions[:, 2]) write_line_own(mdlogfile, '# Kink! at idxs %s' % str(idxs) + '\n', 'a') print ' kink formed! ' + str(i / interval) kink_formed = True i_kink = i if hmax < 3.6 and kink_formed and not kink_vanished: write_line_own(mdlogfile, '# Kink vanished! \n', 'a') print ' kink vanished ' kink_vanished = True print i / interval, theta / (2 * np.pi) * 360, R if kink_formed: m += 1 i += 1 time += dt make_simul_param_file(simulfile, W, L, width, length_int, dtheta/dt, dtheta, T, \ dt, fric, thres_Z, interval, deltaY, theta, i, edge) return folder
# Write visualization of molecule f = open("optmol.xyz", 'w') f.write('\n' + str(len(bz)) + '\n') for i in bz: f.write( str(i.symbol) + ' ' + str(i.x) + ' ' + str(i.y) + ' ' + str(i.z) + '\n') f.close() # Temperature T = 300.0 # We want to run MD with constant energy using the Langevin algorithm # with a time step of 5 fs, the temperature T and the friction # coefficient to 0.02 atomic units. dyn = Langevin(bz, 0.25 * units.fs, T * units.kB, 0.05) #dyn = NVTBerendsen(bz, 0.5 * units.fs, 300.0, taut=3.0*1000*units.fs) start_loop_time = time.time() distCH = [] distCC = [] mdcrd = open("mdcrd.xyz", 'w') temp = open("temp.dat", 'w') def printenergy(a=bz, b=mdcrd, d=dyn, t=temp,
epistemic = atoms.calc.results['epistemic'] / len(atoms) except: aleatoric = -1. epistemic = -1. print('%.4d Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV Alea = %.3feV Epis = %.3feV' % (step, epot, ekin, ekin / (1.5 * units.kB), epot + ekin, aleatoric, epistemic)) atoms.info['md_step'] += 1 # MD traj = Trajectory("Si.traj", 'w', struc) MaxwellBoltzmannDistribution(struc, temperature_K=temp + 50) # NVT dyn = Langevin(struc, timestep=1 * units.fs, temperature_K=temp, friction=0.08) # NPT #dyn = NPT(struc, 1. * units.fs, externalstress=0., ttime=1000*units.fs, pfactor=1000*units.fs, # temperature_K=300) dyn.attach(printenergy) dyn.attach(traj.write, interval=10) printenergy() dyn.run(steps) #for i in range(1000): # dyn.run(steps=steps) # PrintEnergy(struc, i) # save_to_ASE_db(struc, path=ase_db) #traj.close()
atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], symbol='Fe', size=(size, size, size), pbc=True, latticeconstant=3.5646) view(atoms) atoms.set_calculator(calc) # MaxwellBoltzmannDistribution(atoms, 300 * units.kB) # dyn = VelocityVerlet(atoms, 5 * units.fs) T = 10 dyn = Langevin(atoms, 5 * units.fs, T * units.kB, 0.002) traj = Trajectory('md.traj', 'w', atoms) dyn.attach(traj.write, interval=50) 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)) printenergy(atoms)