def __init__( self, atoms, timestep, temperature, nvt_q, trajectory=None, logfile=None, loginterval=1, append_trajectory=False, ): # set angular and com momentum to zero, necessary for nose-hoover dynamics. ZeroRotation(atoms) Stationary(atoms) # thermostat parameters self.temp = temperature / units.kB self.nvt_q = nvt_q self.dt = timestep self.dtdt = np.power(self.dt, 2) self.nvt_bath = 0.0 self.natoms = len(atoms) MolecularDynamics.__init__( self, atoms, timestep, trajectory, logfile, loginterval, append_trajectory=append_trajectory, )
def init_vel(cml): ''' ''' arg = parse_cml_args(cml) # read in the initial structure init_pos = read(arg.poscar) # set the momenta corresponding to T MaxwellBoltzmannDistribution(init_pos, arg.temperature * ase.units.kB) Stationary(init_pos) ZeroRotation(init_pos) # scale the temperature to T vel = init_pos.get_velocities() Tn = init_pos.get_temperature() vel *= np.sqrt(arg.temperature / Tn) init_pos.set_velocities(vel) # write the structure write(arg.out, init_pos, vasp5=True, direct=True) # units in VASP and ASE are different vel = init_pos.get_velocities() * ase.units.fs # np.savetxt('init_vel.dat', vel, fmt='%20.16f') # append the velocities to the POSCAR with open(arg.out, 'a+') as pos: pos.write('\n') pos.write( '\n'.join([ ''.join(["%20.16f" % x for x in row]) for row in vel ]) )
def test_otf_md(md_engine, md_params, super_cell, flare_calc, qe_calc): np.random.seed(12345) flare_calculator = flare_calc[md_engine] # set up OTF MD engine otf_params = { 'init_atoms': [0, 1, 2, 3], 'output_name': md_engine, 'std_tolerance_factor': 2, 'max_atoms_added': len(super_cell.positions), 'freeze_hyps': 10 } # 'use_mapping': flare_calculator.use_mapping} md_kwargs = md_params[md_engine] # intialize velocity temperature = md_params['temperature'] MaxwellBoltzmannDistribution(super_cell, temperature * units.kB) Stationary(super_cell) # zero linear momentum ZeroRotation(super_cell) # zero angular momentum super_cell.set_calculator(flare_calculator) test_otf = ASE_OTF(super_cell, timestep=1 * units.fs, number_of_steps=3, dft_calc=qe_calc, md_engine=md_engine, md_kwargs=md_kwargs, **otf_params) # TODO: test if mgp matches gp # TODO: see if there's difference between MD timestep & OTF timestep # set up logger # otf_logger = OTFLogger(test_otf, super_cell, # logfile=md_engine+'.log', mode="w", data_in_logfile=True) # test_otf.attach(otf_logger, interval=1) test_otf.run() for f in glob.glob("scf*.pw*"): os.remove(f) for f in glob.glob("*.npy"): os.remove(f) for f in glob.glob("kv3*"): shutil.rmtree(f) for f in glob.glob("otf_data"): shutil.rmtree(f, ignore_errors=True) for f in glob.glob("out"): shutil.rmtree(f, ignore_errors=True) for f in os.listdir("./"): if md_engine in f or 'lmp.mgp' in f: os.remove(f) if 'slurm' in f: os.remove(f)
def otf_md_test(md_engine): import atom_setup, flare_setup, qe_setup np.random.seed(12345) print(md_engine) # ----------- set up atoms ----------------- super_cell = atom_setup.super_cell # ----------- setup flare calculator --------------- flare_calc = deepcopy(flare_setup.flare_calc) super_cell.set_calculator(flare_calc) # ----------- setup qe calculator -------------- dft_calc = qe_setup.dft_calc # ----------- create otf object ----------- # set up OTF MD engine md_params = {'timestep': 1 * units.fs, 'trajectory': None, 'dt': None, 'externalstress': 0, 'ttime': 25, 'pfactor': 3375, 'mask': None, 'temperature': 500, 'taut': 1, 'taup': 1, 'pressure': 0, 'compressibility': 0, 'fixcm': 1, 'friction': 0.02} otf_params = {'dft_calc': dft_calc, 'init_atoms': [0, 1, 2, 3], 'std_tolerance_factor': 2, 'max_atoms_added' : len(super_cell.positions), 'freeze_hyps': 10, 'use_mapping': super_cell.calc.use_mapping} # intialize velocity temperature = md_params['temperature'] MaxwellBoltzmannDistribution(super_cell, temperature * units.kB) Stationary(super_cell) # zero linear momentum ZeroRotation(super_cell) # zero angular momentum test_otf = otf_md(md_engine, super_cell, md_params, otf_params) # set up logger test_otf.attach(OTFLogger(test_otf, super_cell, logfile=md_engine+'.log', mode="w", data_in_logfile=True), interval=1) # run otf number_of_steps = 3 test_otf.otf_run(number_of_steps) os.system('rm {}.log'.format(md_engine)) os.system('rm AgI.pw*') os.system('rm -r out') os.system('rm -r __pycache__') os.system('rm -r kv3') os.system('rm lmp.mgp') os.system('rm -r otf_data') os.system('rm *.npy')
def test_otf_md(md_engine, md_params, super_cell, flare_calc, qe_calc): np.random.seed(12345) flare_calculator = flare_calc[md_engine] # set up OTF MD engine otf_params = { "init_atoms": [0, 1, 2, 3], "output_name": md_engine, "std_tolerance_factor": 2, "max_atoms_added": len(super_cell.positions), "freeze_hyps": 10, "write_model": 1, } # 'use_mapping': flare_calculator.use_mapping} md_kwargs = md_params[md_engine] # intialize velocity temperature = md_params["temperature"] MaxwellBoltzmannDistribution(super_cell, temperature * units.kB) Stationary(super_cell) # zero linear momentum ZeroRotation(super_cell) # zero angular momentum super_cell.set_calculator(flare_calculator) test_otf = ASE_OTF( super_cell, timestep=1 * units.fs, number_of_steps=number_of_steps, dft_calc=qe_calc, md_engine=md_engine, md_kwargs=md_kwargs, trajectory=md_engine + "_otf.traj", **otf_params, ) # TODO: test if mgp matches gp # TODO: see if there's difference between MD timestep & OTF timestep test_otf.run() for f in glob.glob("scf*.pw*"): os.remove(f) for f in glob.glob("*.npy"): os.remove(f) for f in glob.glob("kv3*"): shutil.rmtree(f) for f in glob.glob("otf_data"): shutil.rmtree(f, ignore_errors=True) for f in glob.glob("out"): shutil.rmtree(f, ignore_errors=True) for f in os.listdir("./"): if ".mgp" in f or ".var" in f: os.remove(f) if "slurm" in f: os.remove(f)
def build_atoms(self, system, size, temp, seed=None): assert system in self.systems.keys(), "System {} not found!".format( system) atoms = self.systems[system](size) rng = np.random if seed is not None: rng.seed(seed) MaxwellBoltzmannDistribution(atoms, temp * units.kB, rng=rng) Stationary(atoms) ZeroRotation(atoms) return atoms
def _init_velocities(self, temp_init=300, remove_translation=True, remove_rotation=True): """ Initialize velocities for molecular dynamics Args: temp_init (float): Initial temperature in Kelvin (default 300) remove_translation (bool): Remove translation components of velocity (default True) remove_rotation (bool): Remove rotation components of velocity (default True) """ MaxwellBoltzmannDistribution(self.molecule, temp_init * units.kB) if remove_translation: Stationary(self.molecule) if remove_rotation: ZeroRotation(self.molecule)
def init_velocities(atoms, temp): """Initialize atom velocities according to Maxwell-Bolzmann, then zero total linear and angular momenta. Args: atoms (ase.Atoms): initial configuration temp (float): temperature in Kelvin """ from ase import units from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase.md.velocitydistribution import Stationary, ZeroRotation MaxwellBoltzmannDistribution(atoms, temp*units.kB) Stationary(atoms) ZeroRotation(atoms)
def init_vel(cml): ''' ''' arg = parse_cml_args(cml) # read in the initial structure init_pos = read(arg.poscar) # set the momenta corresponding to T MaxwellBoltzmannDistribution(init_pos, temperature_K=arg.temperature, force_temp=True) # set the center-of-mass to 0 Stationary(init_pos) # set the total angular momentum to 0 ZeroRotation(init_pos) ################################################################################ # No need to do this, use "force_temp" parameter in MaxwellBoltzmannDistribution ################################################################################ # scale the temperature to T # vel = init_pos.get_velocities() # Tn = init_pos.get_temperature() # vel *= np.sqrt(arg.temperature / Tn) # init_pos.set_velocities(vel) # write the structure write(arg.out, init_pos, vasp5=True, direct=True) # units in VASP and ASE are different vel = init_pos.get_velocities() * ase.units.fs # np.savetxt('init_vel.dat', vel, fmt='%20.16f') # append the velocities to the POSCAR with open(arg.out, 'a+') as pos: pos.write('\n') pos.write('\n'.join( [''.join(["%20.16f" % x for x in row]) for row in vel]))
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 __init__( self, atomsbatch, mdparam=DEFAULTNVEPARAMS, ): # initialize the atoms batch system self.atomsbatch = atomsbatch self.mdparam = mdparam # todo: structure optimization before starting # intialize system momentum MaxwellBoltzmannDistribution(self.atomsbatch, self.mdparam['T_init'] * units.kB) Stationary(self.atomsbatch) # zero linear momentum ZeroRotation(self.atomsbatch) # set thermostats integrator = self.mdparam['thermostat'] self.integrator = integrator(self.atomsbatch, **self.mdparam['thermostat_params']) # attach trajectory dump self.traj = Trajectory(self.mdparam['traj_filename'], 'w', self.atomsbatch) self.integrator.attach(self.traj.write, interval=self.mdparam['save_frequency']) # attach log file self.integrator.attach(NeuralMDLogger(self.integrator, self.atomsbatch, self.mdparam['thermo_filename'], mode='a'), interval=self.mdparam['save_frequency'])
def __init__(self, mol, gl, path, i, Bi): self.geom_print = gl.full_geom_print self.printSMILES = False self.procNum = i self.gl = gl self.biMolecular = Bi self.method = gl.trajMethod self.level = gl.trajLevel self.mdSteps = gl.mdSteps self.printFreq = gl.printFreq self.mixedTimestep = gl.mixedTimestep if self.biMolecular: try: self.initialT = gl.BiTemp except: print("No specific bimolecular temperature set, using the Langevin temperature instead") self.initialT = gl.LTemp else: self.initialT = gl.LTemp self.MDIntegrator =gl.MDIntegrator self.timeStep = gl.timeStep * units.fs self.eneBXD = gl.eneBXD self.comBXD = gl.comBXD try: self.minCOM = gl.minCOM except: self.minCOM = 3.0 try: self.fragIdx = gl.fragIndices except: self.fragIdx = 0 self.forces = np.zeros(mol.get_positions().shape) self.LangFric = gl.LFric self.LangTemp = self.initialT self.Mol = Atoms(symbols=mol.get_chemical_symbols(), positions = mol.get_positions()) MaxwellBoltzmannDistribution(self.Mol, self.initialT * units.kB, force_temp=True) Stationary(self.Mol) ZeroRotation(self.Mol) self.velocity = self.Mol.get_velocities() print('initialising velocities for process ' + str(i) + '\n') print(str(self.velocity) + '\n') self.tempReactGeom = mol.copy() self.tempProdGeom = mol.copy() self.NEBguess = [] self.TSgeom = mol.copy() self.productGeom = self.Mol.get_positions() try: self.window = gl.reactionWindow self.endOnReac = gl.endOnReaction self.consistantWindow = gl.reactionWindow except: pass if self.biMolecular: self.consistantWindow = int(gl.reactionWindow /4) self.savePath = path self.ReactionCountDown = 0 self.MolList = [] self.KeepTracking = True self.tempList = [1000] self.transindex = np.zeros(3) self.numberOfSteps = 0 self.AssDisoc = False self.TSpoint = 0 self.names=[] self.changePoints=[] self.adaptiveSteps = gl.maxAdapSteps
def learn_pes_by_tempering(atoms, gp, cutoff, ttime, calculator=None, model=None, dt=2., ediff=0.01, volatile=None, target_temperature=1000., stages=1, equilibration=5, rescale_velocities=1.05, pressure=None, stress_equilibration=5, rescale_cell=1.01, eps='random', algorithm='fastfast', name='model', overwrite=True, traj='tempering.traj', logfile='leapfrog.log'): """ pressure (hydrostatic): defined in units of Pascal and is equal to -(trace of stress tensor)/3 eps: if 'random', strain *= a random number [0, 1) if a positive float, strain *= 1-e^(-|dp/p|/eps) i.e. eps ~ relative p fluctuations else, no action """ assert rescale_velocities > 1 and rescale_cell > 1 if pressure is not None: warnings.warn('rescaling cell is not robust!') if model is not None: if type(model) == str: model = PosteriorPotentialFromFolder(model) if gp is None: gp = model.gp if atoms.get_velocities() is None: t = target_temperature MaxwellBoltzmannDistribution(atoms, t * units.kB) Stationary(atoms) ZeroRotation(atoms) dyn = VelocityVerlet(atoms, dt * units.fs, trajectory=traj) dyn = Leapfrog(dyn, gp, cutoff, calculator=calculator, model=model, ediff=ediff, volatile=volatile, algorithm=algorithm, logfile=logfile) t = 0 T = '{} (instant)'.format(atoms.get_temperature()) checkpoints = np.linspace(0, ttime, stages + 1)[1:] for k, target_t in enumerate(checkpoints): print('stage: {}, time: {}, target time: {}, (temperature={})'.format( k, t, target_t, T)) while t < target_t: spu, e, T, s = dyn.run_updates(equilibration) t += spu * equilibration * dt dyn.rescale_velocities( rescale_velocities if T < target_temperature else 1. / rescale_velocities) if pressure is not None: spu, e, T, s = dyn.run_updates(stress_equilibration) t += spu * stress_equilibration * dt p = -s[:3].mean() / units.Pascal # figure out strain dp = p - pressure strain = (rescale_cell if dp > 0 else 1. / rescale_cell) - 1 if eps is 'random': strain *= np.random.uniform() elif type(eps) == float and eps > 0 and abs(p) > 0: strain *= 1 - np.exp(-np.abs(dp / p) / eps) # apply strain dyn.strain_atoms(np.eye(3) * strain) if k == stages - 1: dyn.model.to_folder(name, info='temperature: {}'.format(T), overwrite=overwrite) else: dyn.model.to_folder('{}_{}'.format(name, k), info='temperature: {}'.format(T), overwrite=overwrite) return dyn.get_atoms(), dyn.model
def learn_pes_by_anealing(atoms, gp, cutoff, calculator=None, model=None, dt=2., ediff=0.01, volatile=None, target_temperature=1000., stages=1, equilibration=5, rescale_velocities=1.05, algorithm='fastfast', name='model', overwrite=True, traj='anealing.traj', logfile='leapfrog.log'): assert rescale_velocities > 1 if model is not None: if type(model) == str: model = PosteriorPotentialFromFolder(model) if gp is None: gp = model.gp if atoms.get_velocities() is None: t = target_temperature / stages MaxwellBoltzmannDistribution(atoms, t * units.kB) Stationary(atoms) ZeroRotation(atoms) dyn = VelocityVerlet(atoms, dt * units.fs, trajectory=traj) dyn = Leapfrog(dyn, gp, cutoff, calculator=calculator, model=model, ediff=ediff, volatile=volatile, algorithm=algorithm, logfile=logfile) # initial equilibration while dyn.volatile(): _, e, t, s = dyn.run_updates(1) _, e, t, s = dyn.run_updates(equilibration) temperatures = np.linspace(t, target_temperature, stages + 1)[1:] heating = t < target_temperature cooling = not heating for k, target_t in enumerate(temperatures): print( 'stage: {}, temperature: {}, target temperature: {}, ({})'.format( k, t, target_t, 'heating' if heating else 'cooling')) while (heating and t < target_t) or (cooling and t > target_t): dyn.rescale_velocities(rescale_velocities if heating else 1. / rescale_velocities) _, e, t, s = dyn.run_updates(equilibration) if k == stages - 1: dyn.model.to_folder(name, info='temperature: {}'.format(t), overwrite=overwrite) else: dyn.model.to_folder('{}_{}'.format(name, k), info='temperature: {}'.format(t), overwrite=overwrite) return dyn.get_atoms(), dyn.model
def train_pes_by_tempering(atoms, gp, cutoff, ttime, calculator=None, model=None, dt=2., ediff=0.01, volatile=None, target_temperature=1000., stages=1, equilibration=5, rescale_velocities=1.05, pressure=None, stress_equilibration=5, rescale_cell=1.01, randomize=True, algorithm='fastfast', name='model', overwrite=True, traj='tempering.traj', logfile='leapfrog.log'): assert rescale_velocities > 1 and rescale_cell > 1 if model is not None: if type(model) == str: model = PosteriorPotentialFromFolder(model) if gp is None: gp = model.gp if atoms.get_velocities() is None: t = target_temperature MaxwellBoltzmannDistribution(atoms, t * units.kB) Stationary(atoms) ZeroRotation(atoms) dyn = VelocityVerlet(atoms, dt * units.fs, trajectory=traj) dyn = Leapfrog(dyn, gp, cutoff, calculator=calculator, model=model, ediff=ediff, volatile=volatile, algorithm=algorithm, logfile=logfile) t = 0 T = '{} (instant)'.format(atoms.get_temperature()) checkpoints = np.linspace(0, ttime, stages + 1)[1:] for k, target_t in enumerate(checkpoints): print('stage: {}, time: {}, target time: {}, (temperature={})'.format( k, t, target_t, T)) while t < target_t: spu, e, T, s = dyn.run_updates(equilibration) t += spu * equilibration * dt dyn.rescale_velocities( rescale_velocities if T < target_temperature else 1. / rescale_velocities) if pressure is not None: spu, e, T, s = dyn.run_updates(stress_equilibration) t += spu * stress_equilibration * dt p = -s[:3].mean() / units.Pascal # figure out factor dp = p - pressure factor = (rescale_cell if dp > 0 else 1. / rescale_cell) if randomize: factor = 1 + np.random.uniform(0, 1) * (factor - 1) # apply rescaling dyn.rescale_cell(factor) if k == stages - 1: dyn.model.to_folder(name, info='temperature: {}'.format(T), overwrite=overwrite) else: dyn.model.to_folder('{}_{}'.format(name, k), info='temperature: {}'.format(T), overwrite=overwrite) return dyn.get_atoms(), dyn.model
atoms = FaceCenteredCubic('Cu', surfaces=[[1, 0, 0], [1, 1, 0], [1, 1, 1]], layers=(size, size, size), vacuum=4) # Describe the interatomic interactions with the Effective Medium Theory atoms.set_calculator(EMT()) # Do a quick relaxation of the cluster qn = QuasiNewton(atoms) qn.run(0.001, 10) # Set the momenta corresponding to T=1200K MaxwellBoltzmannDistribution(atoms, 1200 * units.kB) Stationary(atoms) # zero linear momentum ZeroRotation(atoms) # zero angular momentum # We want to run MD using the VelocityVerlet algorithm. # Save trajectory: dyn = VelocityVerlet(atoms, 5 * units.fs, trajectory='moldyn4.traj') def printenergy(a=atoms): # store a reference to atoms in the definition. """Function to print the potential, kinetic and total energy.""" epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) print('Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' 'Etot = %.3feV' % (epot, ekin, ekin / (1.5 * units.kB), epot + ekin)) dyn.attach(printenergy, interval=10)
def test_otf_md(md_engine, super_cell, flare_calc, qe_calc): np.random.seed(12345) flare_calculator = flare_calc[md_engine] # set up OTF MD engine md_params = { 'timestep': 1 * units.fs, 'trajectory': None, 'dt': 1 * units.fs, 'externalstress': 0, 'ttime': 25, 'pfactor': 3375, 'mask': None, 'temperature': 500, 'taut': 1, 'taup': 1, 'pressure': 0, 'compressibility': 0, 'fixcm': 1, 'friction': 0.02 } otf_params = { 'dft_calc': qe_calc, 'init_atoms': [0, 1, 2, 3], 'std_tolerance_factor': 2, 'max_atoms_added': len(super_cell.positions), 'freeze_hyps': 10, 'use_mapping': flare_calculator.use_mapping } # intialize velocity temperature = md_params['temperature'] MaxwellBoltzmannDistribution(super_cell, temperature * units.kB) Stationary(super_cell) # zero linear momentum ZeroRotation(super_cell) # zero angular momentum super_cell.set_calculator(flare_calculator) test_otf = otf_md(md_engine, super_cell, md_params, otf_params) # set up logger otf_logger = OTFLogger(test_otf, super_cell, logfile=md_engine + '.log', mode="w", data_in_logfile=True) test_otf.attach(otf_logger, interval=1) # run otf number_of_steps = 3 test_otf.otf_run(number_of_steps) for f in glob.glob("scf.pw*"): os.remove(f) for f in glob.glob("*.npy"): os.remove(f) for f in glob.glob("kv3*"): shutil.rmtree(f) for f in os.listdir("./"): if f in [f'{md_engine}.log', 'lmp.mgp']: os.remove(f) if f in ['out', 'otf_data']: shutil.rmtree(f)
def test_zero_rotation(atoms): mom1 = atoms.get_angular_momentum() ZeroRotation(atoms) mom2 = atoms.get_angular_momentum() assert norm(mom1) > 0.1 assert norm(mom2) < 1e-13
#dft_calc = Espresso(pseudopotentials=dft_input['pseudopotentials'], label=dft_input['label'], # tstress=True, tprnfor=True, nosym=True, # input_data=input_data, kpts=dft_input['kpts']) # -------------- set up otf npt md -------------------- timestep = 1 # fs temperature = 100 externalstress = 0 ttime = 25 pfactor = 3375 logfile = 'al.log' # intialize velocity MaxwellBoltzmannDistribution(super_cell, 200 * units.kB) Stationary(super_cell) # zero linear momentum ZeroRotation(super_cell) # zero angular momentum test_otf_npt = OTF_NPT( super_cell, timestep, temperature, externalstress, ttime, pfactor, mask=None, # on-the-fly parameters dft_calc=dft_calc, std_tolerance_factor=1, max_atoms_added=nat, freeze_hyps=0, # mff parameters