def solve(self): #Create the initial particle from the defining string/number atoms self.particle = NanoClass.genParticle(self.definingString, int(self.numberOfAtoms)) self.reCenter() self.bestEnergy = self.particle.get_potential_energy() self.bestParticle = deepcopy(self.particle) # berendsen = NVTBerendsen(self.particle, 2.5 * units.fs, 2000, taut=0.5*100*units.fs) berendsen = Langevin(self.particle, 5 * units.fs, units.kB * 2000, 0.005) dyn = FIRE(atoms=self.particle) MaxwellBoltzmannDistribution(self.particle,2000*units.kB) CALCULATIONS=100 for i in range(CALCULATIONS): if i%1==0: pDone=float(i)/CALCULATIONS self.setStatusDone(str(math.floor(pDone*100))+"% | "+self.remainingTime(pDone)) self.checkTimeout() self.setSolution(self.getAnswer()) MaxwellBoltzmannDistribution(self.particle,2000*units.kB) self.particle.get_potential_energy() berendsen.run(500) dyn.run() self.reCenter() testEnergy = self.particle.get_potential_energy() if (testEnergy < self.bestEnergy): self.bestEnergy = testEnergy self.bestParticle = deepcopy(self.particle) elif ((testEnergy + .5) > self.bestEnergy): self.particle = NanoClass.genParticle(self.definingString, int(self.numberOfAtoms)) MaxwellBoltzmannDistribution(self.particle,2000*units.kB) self.particle.get_potential_energy() if (testEnergy < self.bestEnergy): self.bestEnergy = testEnergy self.bestParticle = deepcopy(self.particle) return self.getAnswer()
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 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 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 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__(self, atoms, timestep=None, temperature=None, friction=None, trajectory=None, **kwargs): Langevin.__init__(self, atoms, timestep, temperature, friction) OTF.__init__(self, **kwargs) self.md_engine = 'Langevin'
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 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 _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 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 solve(self): #Create the initial particle from the defining string/number atoms temp = 1750 mintemp = 150 self.particle = genParticle(self.definingString,int(self.numberOfAtoms)) if (len(self.particle) < 16): temp = 1250 maxtemp = temp berendsen = Langevin(self.particle, 2.5 * units.fs, units.kB * temp, 0.02) # the 5.0 * units.fs is used instead of 0.1 * units.fs b/c it makes the program run faster MaxwellBoltzmannDistribution(self.particle,units.kB * temp) self.bestEnergy = self.particle.get_potential_energy() self.bestParticle = deepcopy(self.particle) self.reCenter() self.getAnswer() while (temp > mintemp): berendsen = Langevin(self.particle, 2.5 * units.fs, units.kB * temp, 0.02) berendsen.run(100) testEnergy = self.particle.get_potential_energy() self.bestEnergy = self.particle.get_potential_energy() self.bestParticle = deepcopy(self.particle) self.reCenter() self.getAnswer() temp -= 10 if (temp % 50 == 0): self.bestEnergy = self.particle.get_potential_energy() self.bestParticle = deepcopy(self.particle) self.reCenter() self.checkTimeout() self.setSolution(self.getAnswer()) pDone=float(maxtemp - temp)/(maxtemp-mintemp) self.setStatusDone(str(math.floor(pDone*100))+"% | "+self.remainingTime(pDone)) elif (temp <= mintemp): dyn = FIRE(atoms=self.particle) dyn.run(fmax=0.01) self.bestEnergy = self.particle.get_potential_energy() self.bestParticle = deepcopy(self.particle) self.reCenter() self.setSolution(self.getAnswer()) pDone=float(temp)/(maxtemp-mintemp) self.setStatusDone(str(math.floor(pDone*100))+"% | "+self.remainingTime(pDone)) return self.getAnswer()
def updatevars(self): Langevin_ASE.updatevars(self) if len(self.atoms.constraints) == 1: # Process the FixAtoms constraint constr = self.atoms.constraints[0].index self.sdpos[constr] = 0.0 self.sdmom[constr] = 0.0 self.c1[constr] = 0.0 self.c2[constr] = 0.0 self.c3[constr] = 0.0 self.c4[constr] = 0.0 self.act0[constr] = 0.0 if self._localfrict: self.asap_md.set_vector_constants(self.prefix+"act0", self.prefix+"c3", self.prefix+"c4", self.prefix+"pmcor", self.prefix+"cnst") else: self.asap_md.set_scalar_constants(self.act0, self.c3, self.c4, self.pmcor, self.cnst)
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 __init__(self, atoms, timestep, temperature, friction, fixcm=True, trajectory=None, logfile=None, loginterval=1): assert(getattr(Langevin_ASE, "_lgv_version", 1) >= 2) ParallelMolDynMixin.__init__(self, "Langevin", atoms) self._uselocaldata = False # Need to store on atoms for serial simul too. self.calculator = atoms.get_calculator() self.asap_md = asap3._asap.Langevin(atoms, self.calculator, timestep, self.prefix+"sdpos", self.prefix+"sdmom", self.prefix+"c1", self.prefix+"c2", fixcm, randint(1 << 30)) if not atoms.has('momenta'): atoms.set_momenta(np.zeros((len(atoms), 3), float)) if atoms.constraints: assert len(atoms.constraints) == 1 constraint = atoms.constraints[0] assert isinstance(constraint, asap3.constraints.FixAtoms) constraint.prepare_for_asap(atoms) # Make all constants arrays by making friction an array friction = friction * np.zeros(len(atoms)) Langevin_ASE.__init__(self, atoms, timestep, temperature, friction, fixcm, trajectory, logfile, loginterval, communicator=None)
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 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 __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 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 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_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 md_run(origin_poscar_path, index): print('%d' % index + ' In directory : %s' % origin_poscar_path) atoms = read(origin_poscar_path) calc = ANNCalculator(potentials={ "Ga": "Ga.10t-10t.nn", "N": "N.10t-10t.nn" }) atoms.set_calculator(calc) MaxwellBoltzmannDistribution(atoms, 1200 * kB) Stationary(atoms) md = NVT(atoms, timestep=2 * fs, temperature=1000 * kB, friction=0.05) logger = MDLogger(md, atoms, '-', stress=True) md.attach(logger, interval=1) traj = Trajectory( "nvt_%s.traj" % (origin_poscar_path.split('/')[-1].split('.xsf')[0]), "w", atoms) md.attach(traj.write, interval=200) md.run(40000)
def cylinderDynamics(R, T, params): nk = params['nk'] #20 fmax = params['fmax'] #1E-2 fric = params['fric'] #0.002 dt = params['dt'] #5.0 mdsteps = params['mdsteps'] #int(10/fric/dt) path = params['path'] #'/space/tohekorh/Au_bend/files/' print 'radius',R, '\n' name = '%.1f' %R # Get the optimal flat atoms , unit-cell config for this temperature: atoms = get_opmAtomsFlat(T, params) # Take the diagonal of the cell: L = atoms.get_cell().diagonal() atoms.set_cell(L) # The wedge angle is: angle = L[1]/R # fiddle with atoms: atoms.rotate('y', np.pi/2) atoms.translate((-atoms[0].x, 0, 0) ) #view(atoms) # Initial map for atoms, to get the on surface of cylinder: phi_max = angle for a in atoms: r0 = a.position phi = r0[1]/L[1]*phi_max a.position[0] = R*np.cos(phi) a.position[1] = R*np.sin(phi) #view(atoms) # proper number of kappa points in angle direction, if angle >= 2*pi/3 the use genuine # physical boundary conditions and proper kappa-points. With 64 atoms in unit cell souhld not # happen as the radius -> very small if angle = 2*pi/3 or larger. # Check that the unit-cell angle is 2*pi/integer. This can be removed! if (2*np.pi/angle)%1 > 0: raise # This does not have any effect unless angle >= 2*pi/3: m = int(round(2*np.pi/angle)) physical = False if m <= 3: nk1 = m physical = True else: nk1 = nk # Set up the wedge container: atoms = Atoms(atoms = atoms, container = 'Wedge') atoms.set_container(angle = angle, height = L[0], physical = physical, pbcz = True) # Check that everything looks good: #view(atoms.extended_copy((2,1,2))) # FOLDERS path_opm = path + 'cylinder/opm/T=%.0f/' %T path_md = path + 'cylinder/md_data/T=%.0f/' %T checkAndCreateFolder(path_opm) checkAndCreateFolder(path_md) # CALCULATOR calc = Hotbit(SCC=False, kpts=(nk1, 1, nk), physical_k = physical, \ txt= path_opm + 'optimization_%s.cal' %name) atoms.set_calculator(calc) # RELAX opt = BFGS(atoms, trajectory= path_opm + 'optimization_%s.traj' %name) opt.run(fmax=fmax, steps=1000) # DYNAMICS traj = PickleTrajectory(path_md + 'md_R%.3f.traj' %R,'w',atoms) # Perform dynamics dyn = Langevin(atoms, dt*units.fs, units.kB*T, fric) dyn.attach(MDLogger(dyn, atoms, path_md + 'md_R%.3f.log' %R, header=True, stress=False, peratom=True, mode="w"), interval = 1) dyn.attach(traj.write) dyn.run(mdsteps) traj.close() # load the dynamics back, to make exteded trajectory: traj = PickleTrajectory(path_md + 'md_R%.3f.traj' %R) trajToExtTraj(traj, (2, 1, 2), R, T, angle, L[0], path)
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 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 run_moldy(): KC = False # DEFINE FILES mdfile, mdlogfile = 'md.traj', 'md.log' atoms = make_graphene_slab(a,h,width,4,2, passivate = True)[3] params = {'bond':bond, 'a':a, 'h':h} params['positions'] = atoms.positions.copy() params['pbc'] = atoms.get_pbc() params['cell'] = atoms.get_cell().diagonal() params['ia_dist'] = 14 params['chemical_symbols'] = atoms.get_chemical_symbols() constraints = [] add_kc = KC_potential(params) left = get_ind(atoms.positions.copy(), 'left', 1, bond) rend = get_ind(atoms.positions.copy(), 'rend', atoms.get_chemical_symbols(), 0) ''' # FIX #zset, layer_inds = find_layers(atoms.positions.copy()) add_adh = add_adhesion(params) add_kc = KC_potential(params) #constraints.append(add_adh) # END FIX ''' fix_left = FixAtoms(indices = left) for ind in rend: fix_deform = FixedPlane(ind, (0., 0., 1.)) constraints.append(fix_deform) constraints.append(fix_left) if KC: constraints.append(add_kc) # CALCULATOR LAMMPS parameters = {'pair_style':'rebo', 'pair_coeff':['* * CH.airebo C H'], 'mass' :['1 12.0', '2 1.0'], 'units' :'metal', 'boundary' :'f p f'} calc = LAMMPS(parameters=parameters) atoms.set_calculator(calc) # END CALCULATOR atoms.set_constraint(constraints) #view(atoms) # TRAJECTORY traj = PickleTrajectory(mdfile, 'w', atoms) data = np.zeros((M, 6)) # DYNAMICS dyn = Langevin(atoms, dt*units.fs, T*units.kB, 0.002) n = 0 header = '#t [fs], d [Angstrom], epot_tot [eV], ekin_tot [eV], etot_tot [eV] \n' log_f = open(mdlogfile, 'w') log_f.write(header) log_f.close() for i in range(0, M): #for ind in rend: atoms[3].position[2] -= dz dyn.run(1) va = atoms.get_velocities() vamax = np.linalg.norm(va[3]*0.0982269353) #print vamax epot, ekin = saveAndPrint(atoms, traj, False)[:2] data[n] = [i*dt, i*dz, epot, ekin, epot + ekin, vamax] log_f = open(mdlogfile, 'a') stringi = '' for k,d in enumerate(data[n]): if k == 0: stringi += '%.2f ' %d elif k == 1: stringi += '%.6f ' %d else: stringi += '%.12f ' %d log_f.write(stringi + '\n') log_f.close() np.savetxt(mdlogfile, data, header = header) n += 1 if i%(int(M/100)) == 0: print 'ready = %.1f' %(i/(int(M/100))) + '%'
def runAndStudy(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'] width = params_set['width'] ratio = params_set['ratio'] edge = params_set['edge'] ncores = params_set['ncores'] Ld_i = params_set['Ldilde_i'] bend, straight, [matchL_idx, matchR_idx, vec], [L_bend, L_straight], [left_idxs, right_idxs]\ = create_bend_stucture(width, ratio, Ld_i, edge, bond) mdfile, mdlogfile, mdrelax, simulfile, folder, relaxed \ = get_fileName(pot_key, edge + '_corrStick', width, \ L_bend, L_straight, int(T), taito, key = 'corrStick') if relaxed: bend = PickleTrajectory(mdrelax, 'r')[-1] else: relaxBend(bend, left_idxs, right_idxs, edge, bond, mdrelax) bend.set_constraint([]) shift_v = -straight.positions[matchR_idx] + (bend.positions[matchL_idx] + vec) straight.translate(shift_v) atoms = bend + straight cell = [1.5*(L_bend + L_straight), L_bend + L_straight, 20] atoms.set_cell(cell) atoms.positions[:,2] = 3.4 trans_vec = trans_atomsKC(straight.positions[matchR_idx], edge, bond) atoms.translate(trans_vec) #plot_posits(atoms, edge, bond) if edge == 'ac': nx = int((cell[0]/5 - np.min(atoms.positions[:,0]))/(3*bond)) ny = int((cell[1]/5 - np.min(atoms.positions[:,1]))/(np.sqrt(3)*bond)) atoms.translate([nx*3.*bond, ny*np.sqrt(3)*bond, 0]) width_f = np.sqrt(3)/2.*bond*(width - 1) elif edge == 'zz': nx = int((cell[0]/5 - np.min(atoms.positions[:,0]))/(np.sqrt(3)*bond)) ny = int((cell[1]/5 - np.min(atoms.positions[:,1]))/(3*bond)) atoms.translate([nx*np.sqrt(3)*bond, ny*3*bond, 0]) width_f = (3./2.*width - 1)*bond cminx, cmaxx = strip_Hend(atoms, 'right') left_b = get_idxOfEnds(atoms, cminx, cmaxx)[0] # CONSTRAINTS constraints = [] constraints.append(FixAtoms(indices = left_b)) params = {} params['positions'] = atoms.positions params['chemical_symbols'] = atoms.get_chemical_symbols() params['ia_dist'] = 10 params['edge'] = edge params['bond'] = bond params['ncores'] = ncores add_pot = KC_potential_p(params) constraints.append(add_pot) atoms.set_constraint(constraints) ## # CALCULATOR calc = LAMMPS(parameters=get_lammps_params()) atoms.set_calculator(calc) ## # 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') traj = PickleTrajectory(mdfile, 'w', atoms) if T != 0: # put initial MaxwellBoltzmann velocity distribution mbd(atoms, T*units.kB) #### # SIMULATION PARAMS nframes = 1000 M = int(20*tau/dt) interval = int(M/nframes) thres_cancel= 2*bond stick = 'True' xmax_idx = np.where(atoms.positions[:,0] == np.max(atoms.positions[:,0]))[0][0] r_init = atoms.positions[xmax_idx].copy() R = L_bend/np.pi*3. print '# data_line: width, length bend, length tail, tail/bend, theta' print width_f, L_bend, L_straight, L_straight/L_bend, width_f/(2*R) # SIMULATION LOOP for i in range(nframes): print float(i)/nframes*100. dyn.run(interval) epot, ekin = saveAndPrint(atoms, traj, False)[:2] data = [i*interval*dt, 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') #print np.linalg.norm(atoms.positions[xmax_idx] - r_init) if thres_cancel < np.linalg.norm(atoms.positions[xmax_idx] - r_init): stick = 'false' break make_stick_simul_param_file(simulfile, width, L_bend, L_straight, T, \ dt, fric, interval, M, edge, stick) return stick == 'True' #plot_posits(atoms, edge, bond) #view(atoms)
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)
def main(): T = 300.0 # Simulation temperature dt = 1 * units.fs # MD timestep nsteps = 100000 # MD number of steps mixing = [1,-1,0] # [1.0, -1.0, 0.3] # mixing weights for "real" and ML forces lengthscale = 0.5 # KRR Gaussian width. gamma = 1 / (2 * lengthscale**2) grid_spacing = 0.05 # mlmodel = GaussianProcess(corr='squared_exponential', # # theta0=1e-1, thetaL=1e-4, thetaU=1e+2, # theta0=1., # random_start=100, normalize=False, nugget=1.0e-2) mlmodel = KernelRidge(kernel='rbf', gamma=gamma, gammaL = gamma/4, gammaU=2*gamma, alpha=1.0e-2, variable_noise=False, max_lhood=False) anglerange = sp.arange(0, 2*sp.pi + grid_spacing, grid_spacing) X_grid = sp.array([[sp.array([x,y]) for x in anglerange] for y in anglerange]).reshape((len(anglerange)**2, 2)) ext_field = None # IgnoranceField(X_grid, y_threshold=-0.075, cutoff = 3.) # Bootstrap from initial database? uncomment # data = sp.loadtxt('phi_psi_F.csv') # # data[:,:2] -= 0.025 # fix because of old round_vector routine # mlmodel.fit(data[:,:2], data[:,2]) # ext_field.update_cost(mlmodel.X_fit_, mlmodel.y) # mlmodel.fit(X_grid, sp.zeros(len(X_grid))) # mlmodel.fit(sp.load('X_fitD.npy'), sp.load('y_fitD.npy')) # Prepare diagnostic visual effects. plt.close('all') plt.ion() fig, ax = plt.subplots(1, 2, figsize=(24, 13)) atoms = ase.io.read('myplum.xyz') with open('data.input', 'r') as file: lammpsdata = file.readlines() # Set temperature MaxwellBoltzmannDistribution(atoms, 0.5 * units.kB * T, force_temp=True) # Set total momentum to zero p = atoms.get_momenta() p -= p.sum(axis=0) / len(atoms) atoms.set_momenta(p) atoms.rescale_velocities(T) # Select MD propagator mdpropagator = Langevin(atoms, dt, T*units.kB, 1.0e-2, fixcm=True) # mdpropagator = MLVerlet(atoms, dt, T) # Zero-timestep evaluation and data files setup. print("START") pot_energy, f = calc_lammps(atoms, preloaded_data=lammpsdata) mlmodel.accumulate_data(round_vector(atoms.colvars(), precision=grid_spacing), 0.) # mlmodel.accumulate_data(round_vector(atoms.colvars(), precision=grid_spacing), pot_energy) printenergy(atoms, pot_energy) try: os.remove('atomstraj.xyz') except: pass traj = open("atomstraj.xyz", 'a') atoms.write(traj, format='extxyz') results, traj_buffer = [], [] # When in the simulation to update the ML fit -- optional. teaching_points = sp.unique((sp.linspace(0, nsteps**(1/3), nsteps/20)**3).astype('int') + 1) # MD Loop for istep in range(nsteps): # Flush Cholesky decomposition of K if istep % 1000 == 0: mlmodel.Cho_L = None mlmodel.max_lhood = False print("Dihedral angles | phi = %.3f, psi = %.3f " % (atoms.phi(), atoms.psi())) do_update = (istep % 60 == 59) t = get_time() mdpropagator.halfstep_1of2(f) print("TIMER 001 | %.3f" % (get_time() - t)) t = get_time() f, pot_energy, _ = get_all_forces(atoms, mlmodel, grid_spacing, T, extfield=ext_field, mixing=mixing, lammpsdata=lammpsdata, do_update=do_update) if do_update and mlmodel.max_lhood: mlmodel.max_lhood = False mdpropagator.halfstep_2of2(f) print("TIMER 002 | %.3f" % (get_time() - t)) # manual cooldown!!! if sp.absolute(atoms.get_kinetic_energy() / (1.5 * units.kB * atoms.get_number_of_atoms()) - T) > 100: atoms.rescale_velocities(T) printenergy(atoms, pot_energy/atoms.get_number_of_atoms(), step=istep) # if do_update: # try: # print("Lengthscale = %.3e, Noise = %.3e" % (1/(2 * mlmodel.gamma)**0.5, mlmodel.noise.mean())) # except: # print("") if istep % 60 == 59: t = get_time() if 'datasetplot' not in locals(): datasetplot = pl.Plot_datapts(ax[0], mlmodel) else: datasetplot.update() if hasattr(mlmodel, 'dual_coef_'): if 'my2dplot' not in locals(): my2dplot = pl.Plot_energy_n_point(ax[1], mlmodel, atoms.colvars().ravel()) else: my2dplot.update_prediction() my2dplot.update_current_point(atoms.colvars().ravel()) print("TIMER 003 | %.03f" % (get_time() - t)) t = get_time() fig.canvas.draw() print("TIMER 004 | %.03f" % (get_time() - t)) # fig.canvas.print_figure('current.png') t = get_time() # traj_buffer.append(atoms.copy()) # if istep % 100 == 0: # for at in traj_buffer: # atoms.write(traj, format='extxyz') # traj_buffer = [] results.append(sp.array([atoms.phi(), atoms.psi(), pot_energy])) print("TIMER 005 | %.03f" % (get_time() - t)) traj.close() print("FINISHED") sp.savetxt('results.csv', sp.array(results)) sp.savetxt('mlmodel.dual_coef_.csv', mlmodel.dual_coef_) sp.savetxt('mlmodel.X_fit_.csv', mlmodel.X_fit_) sp.savetxt('mlmodel.y.csv', mlmodel.y) calc = None return mlmodel
mixer_forces = [forces_full_system] mixer_energies = [energy_full_system] elif calc_style == "quantum": mixer_forces = [forces_qbox_gpaw] mixer_energies = [energy_qbox_gpaw] mixer = Mixer(name="mixer_box", forces=mixer_forces, energies=mixer_energies, debug=debug) atoms.set_calculator(mixer) dyn = None if md_style == "Langevin": dyn = Langevin(atoms, timestep, 1.5*T*units.kB, 0.002) elif md_style == "Verlet": dyn = VelocityVerlet(atoms, timestep) elif md_style == "TESTING": dyn = DynTesting(atoms, timestep=0.1*units.fs, offset=(0.1, 0., 0.)) energy_file = None def printenergy(a=atoms): epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) energy_file.write("%.5e,%.5e,%.5e,%.5e" % (epot + ekin, epot, ekin, ekin/(1.5*units.kB)) + "\n") # only enable logging for master node where rank == 0 if rank == 0:
def sphereDynamics(R, T, params): d = params['d'] #2.934 nk = params['nk'] #20 fmax = params['fmax'] #1E-2 fric = params['fric'] #0.002 # equilibration time tau = 10 fs/fric (= mdsteps*dt) dt = params['dt'] #5.0 mdsteps = params['mdsteps'] #int(10/fric/dt) path = params['path'] #'/space/tohekorh/Au_bend/files/' uzsize = params['uz_size'] print 'radius',R name = '%.1f' %R # ATOMS #atoms = fcc111('Au',size=uzsize,a=np.sqrt(2)*d) atoms = get_opmAtomsFlat(T, params) atoms.rotate((0,0,1), -np.pi/6, rotate_cell = True) length1 = np.linalg.norm( atoms.get_cell()[0] ) length2 = np.linalg.norm( atoms.get_cell()[1] ) n1 = ( np.cos(np.pi/3), np.sin(np.pi/3), 0) n2 = (-np.cos(np.pi/3), np.sin(np.pi/3), 0) angle1 = length1/R angle2 = length2/R #view(atoms) # Scale the atoms close to ball Lx = np.linalg.norm(atoms.get_cell()[0] + atoms.get_cell()[1]) Ly = np.linalg.norm(atoms.get_cell()[0] - atoms.get_cell()[1]) phi_max = Ly/R theta_max = Lx/R for a in atoms: r0 = a.position phi = r0[1]/Ly*phi_max theta = r0[0]/Lx*theta_max a.position[0] = R*np.sin(theta) #*np.sin(theta) a.position[1] = R*np.sin(phi) #a.position[1] #R*np.sin(phi) #*np.sin(theta) a.position[2] = R*np.cos(theta) #atoms.translate((0,0,R)) # End scaling atoms = Atoms(atoms=atoms,container='Sphere') atoms.set_container(angle1=angle1,angle2=angle2,n1=n1,n2=n2,mode=4) #view(atoms.extended_copy((2,2,1))) # FOLDERS path_md = path + 'sphere/md_data/T=%.0f/' %T path_opm= path + 'sphere/opm/T=%.0f/' %T checkAndCreateFolder(path_md) checkAndCreateFolder(path_opm) # CALCULATOR calc = Hotbit(SCC=False, kpts=(nk,nk,1),txt= path_opm + 'optimization_%s.cal' %name,) atoms.set_calculator(calc) # RELAX opt = BFGS(atoms, trajectory= path_opm + 'optimization_%s.traj' %name) opt.run(fmax=fmax,steps=1000) #write(path_opm + 'opm_structure_R%.3f' %R, atoms, format='traj') # DYNAMICS traj = PickleTrajectory(path_md + 'md_R%.3f.traj' %R, 'w', atoms) dyn = Langevin(atoms, dt*units.fs, units.kB*T,fric) dyn.attach(MDLogger(dyn, atoms, path_md + 'md_R%.3f.log' %R, header=True, stress=False, peratom=True, mode="w"), interval = 1) dyn.attach(traj.write) dyn.run(mdsteps) traj.close() # load the dynamics back.. To write the extended trajectory traj = PickleTrajectory(path_md + 'md_R%.3f.traj' %R) trajToExtTraj(traj, (2, 2, 1), R, T, angle1, angle2, n1, n2, path)
class clustergenerator(): def __init__(self, cnstfile, saefile, nnfprefix, Nnet, solv_list, solu_list, gpuid=0, sinet=False): # Molecules list self.solv_list = solv_list self.solu_list = solu_list # Number of networks self.Nn = Nnet # Build ANI ensemble self.aens = ensemblemolecule(cnstfile, saefile, nnfprefix, Nnet, gpuid) self.edgepad = 1.0 self.mindist = 2.0 #def closeoutputs(self): # self.mdcrd.close() # self.traj.close() def __generategarbagebox__(self, Nm, Nembed, L, T): self.X = np.empty((0, 3), dtype=np.float32) self.S = [] self.C = np.zeros((Nm, 3), dtype=np.float32) rint = np.random.randint(len(self.solv_list), size=Nm) self.Na = np.zeros(Nm, dtype=np.int32) self.ctd = [] pos = 0 plc = 0 for idx, j in enumerate(rint): if idx < Nembed: ri = np.random.randint(len(self.solu_list), size=1) s = self.solu_list[ri[0]]['species'] xyz = self.solu_list[ri[0]]['coordinates'] nmc = self.solu_list[ri[0]]['nmdisplacements'] frc = self.solu_list[ri[0]]['forceconstant'] nms = nmt.nmsgenerator(xyz, nmc, frc, s, T, minfc=5.0E-2) x = nms.get_Nrandom_structures(1)[0] else: s = self.solv_list[j]['species'] xyz = self.solv_list[j]['coordinates'] nmc = self.solv_list[j]['nmdisplacements'] frc = self.solv_list[j]['forceconstant'] nms = nmt.nmsgenerator(xyz, nmc, frc, s, T, minfc=5.0E-2) x = nms.get_Nrandom_structures(1)[0] # Apply a random rotation M = rand_rotation_matrix() x = np.dot(x, M.T) maxd = hdn.generatedmatsd3(x).flatten().max() / 2.0 Nf = 0 fail = True while fail: ctr = np.random.uniform(2.0 * maxd + self.edgepad, L - 2.0 * maxd - self.edgepad, (3)) fail = False for cid, c in enumerate(self.ctd): if np.linalg.norm(c[0] - ctr) < maxd + c[1] + 10.0: # search for atoms within r angstroms minv = 1000.0 for xi in self.X[c[2]:c[2] + self.Na[cid], :]: for xj in x + ctr: dij = np.linalg.norm(xi - xj) if dij < minv: minv = dij if minv < self.mindist: fail = True Nf += 1 if not fail: plc += 1 #print('Added:',plc) self.ctd.append((ctr, maxd, pos)) self.X = np.vstack([self.X, x + ctr]) self.Na[idx] = len(s) pos += len(s) #print('Placement Complete...',plc,'-',Nf) self.S.extend(s) 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) # Define the printer #def printenergy(a=self.mol, d=self.dyn, b=self.mdcrd, t=self.traj): # 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) # # stddev = hdn.evtokcal * a.calc.stddev # # t.write(str(d.get_number_of_steps()) + ' ' + str(ekin / (1.5 * units.kB)) + ' ' + str(epot) + ' ' + str( # ekin) + ' ' + str(epot + ekin) + '\n') # b.write(str(len(a)) + '\n' + str(ekin / (1.5 * units.kB)) + ' Step: ' + str(d.get_number_of_steps()) + '\n') # c = a.get_positions(wrap=True) # for j, i in zip(a, c): # b.write(str(j.symbol) + ' ' + str(i[0]) + ' ' + str(i[1]) + ' ' + str(i[2]) + '\n') # # print('Step: %d Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' # 'Etot = %.3feV' ' StdDev = %.3fkcal/mol/sqrt(Na)' % ( # d.get_number_of_steps(), epot, ekin, ekin / (1.5 * units.kB), epot + ekin, stddev)) # Attach the printer #self.dyn.attach(printenergy, interval=1) def run_dynamics(self, Ni): for id, nc in enumerate(self.aens.ncl): nc.setMolecule(coords=np.array(self.mol.get_positions(), dtype=np.float32), types=self.mol.get_chemical_symbols()) self.dyn.run(Ni) # Do Ni steps def __fragmentbox__(self, file, sighat): self.X = self.mol.get_positions() self.frag_list = [] self.Nd = 0 self.Nt = 0 self.maxsig = 0 for i in range(len(self.Na)): si = self.ctd[i][2] di = self.ctd[i][1] Nai = self.Na[i] Xci = np.sum(self.X[si:si + Nai, :], axis=0) / Nai Xi = self.X[si:si + Nai, :] if np.all(Xci > 4.5) and np.all(Xci <= self.L - 4.5): if np.all(Xci > di) and np.all(Xci < self.L - di): Xf = Xi Sf = self.S[si:si + Nai] Nmax = random.randint(2, 14) Nmol = 0 for j in range(len(self.Na)): if i != j: sj = self.ctd[j][2] dj = self.ctd[j][1] Naj = self.Na[j] Xcj = np.sum(self.X[sj:sj + Naj, :], axis=0) / Naj Xj = self.X[sj:sj + Naj, :] if np.all(Xcj > dj) and np.all(Xcj < self.L - dj): dc = np.linalg.norm(Xci - Xcj) if dc < di + dj + 5.0: min = 10.0 for ii in range(Nai): Xiii = Xi[ii] for jj in range(Naj): Xjjj = Xj[jj] v = np.linalg.norm(Xiii - Xjjj) if v < min: min = v if min < 4.5 and min > 0.70: Xf = np.vstack([Xf, Xj]) Sf.extend(self.S[sj:sj + Naj]) Nmol += 1 if Nmol >= Nmax: break Xcf = np.sum(Xf, axis=0) / float(len(Sf)) Xf = Xf - Xcf E = np.empty(5, dtype=np.float64) for id, nc in enumerate(self.aens.ncl): nc.setMolecule(coords=np.array(Xf, dtype=np.float32), types=Sf) E[id] = nc.energy()[0] sig = np.std(hdn.hatokcal * E) / np.sqrt(Nai + Naj) #print('Mol(',i,'): sig=',sig) self.Nt += 1 if sig > sighat: if sig > self.maxsig: self.maxsig = sig self.Nd += 1 hdn.writexyzfile(file + str(i).zfill(4) + '.xyz', Xf.reshape(1, Xf.shape[0], 3), Sf) self.frag_list.append(dict({'coords': Xf, 'spec': Sf})) #print(dc, Sf, sig) def generate_clusters(self, gcmddict, mol_sizes, id): self.edgepad = gcmddict['edgepad'] self.mindist = gcmddict['mindist'] dstore = gcmddict['dstore'] difo = open( dstore + 'info_data_mdcluster-' + str(id).zfill(2) + '.nfo', 'w') difo.write('Beginning dimer generation...\n') Nt = 0 Nd = 0 for i in range(gcmddict['Nr']): self.init_dynamics( mol_sizes[i], gcmddict['Nembed'], gcmddict['V'], gcmddict['L'], gcmddict['dt'], gcmddict['T'], ) for j in range(gcmddict['Ns']): if j is 0: Ni = 0 else: Ni = gcmddict['Ni'] self.run_dynamics(Ni) self.__fragmentbox__( gcmddict['molfile'] + '-' + str(id).zfill(2) + '-' + str(i).zfill(2) + '-' + str(j).zfill(4) + '_', gcmddict['sig']) #print('Step (',i,',',j,') [', str(self.Nd), '/', str(self.Nt),'] generated ',len(self.frag_list),' maxsig: ', self.maxsig,' dimers...') difo.write('Step (' + str(i) + ',' + str(i) + ') [' + str(self.Nd) + '/' + str(self.Nt) + '] generated ' + str(len(self.frag_list)) + ' clusters. ' + ' maxsig: ' + "{:.2f}".format(self.maxsig) + '\n') Nt += self.Nt Nd += self.Nd if self.maxsig > gcmddict['maxsig']: difo.write("Terminated after: " + "{:.2f}".format(Ni * gcmddict['Ns'] * gcmddict['dt']) + 'fs for maxsig\n') break difo.flush() #self.closeoutputs() difo.write('Generated ' + str(Nd) + ' of ' + str(Nt) + ' tested dimers. Percent: ' + "{:.2f}".format(100.0 * Nd / float(Nt))) difo.close()
class dimergenerator(): def __init__(self, cnstfile, saefile, nnfprefix, Nnet, molecule_list, gpuid=0, sinet=False): # Molecules list self.mols = molecule_list # Number of networks self.Nn = Nnet # Build ANI ensemble self.aens = ensemblemolecule(cnstfile, saefile, nnfprefix, Nnet, gpuid) # Construct pyNeuroChem class #self.ncl = [pync.molecule(cnstfile, saefile, nnfprefix+str(i)+'/networks/', gpuid, sinet) for i in range(self.Nn)] def __generategarbagebox__(self, Nm, L, T): self.X = np.empty((0, 3), dtype=np.float32) self.S = [] self.C = np.zeros((Nm, 3), dtype=np.float32) rint = np.random.randint(len(self.mols), size=Nm) self.Na = np.zeros(Nm, dtype=np.int32) self.ctd = [] pos = 0 plc = 0 attempts = 0 for idx, j in enumerate(rint): if attempts >= 10000: break #x = self.mols[j]['coordinates'] #s = self.mols[j]['species'] s = self.mols[j]['species'] xyz = self.mols[j]['coordinates'] nmc = self.mols[j]['nmdisplacements'] frc = self.mols[j]['forceconstant'] nms = nmt.nmsgenerator(xyz, nmc, frc, s, T, minfc=5.0E-2) x = nms.get_Nrandom_structures(1)[0] # Apply a random rotation M = rand_rotation_matrix() x = np.dot(x, M.T) maxd = hdn.generatedmatsd3(x).flatten().max() / 2.0 #print('after:', maxd) fail = True while fail and attempts < 10000: ctr = np.random.uniform(2.0 * maxd + 1.0, L - 2.0 * maxd - 1.0, (3)) fail = False for cid, c in enumerate(self.ctd): if np.linalg.norm(c[0] - ctr) < maxd + c[1] + 10.0: # search for atoms within r angstroms minv = 1000.0 for xi in self.X[c[2]:c[2] + self.Na[cid], :]: for xj in x + ctr: dij = np.linalg.norm(xi - xj) if dij < minv: minv = dij if minv < 1.5: fail = True attempts += 1 if not fail: plc += 1 attempts = 0 #print('Added:',plc) self.ctd.append((ctr, maxd, pos)) self.X = np.vstack([self.X, x + ctr]) self.Na[idx] = len(s) pos += len(s) self.S.extend(s) self.Na = self.Na[0:plc] 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 run_dynamics(self, Ni): # Open MD output #mdcrd = open(xyzfile, 'w') # Open MD output #traj = open(trajfile, 'w') # Define the printer #def printenergy(a=self.mol, d=self.dyn): # 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('Step: %d Size: %d Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) ' # 'Etot = %.3feV' % (d.get_number_of_steps(), len(a), epot, ekin, ekin / (1.5 * units.kB), epot + ekin)) # Attach the printer #self.dyn.attach(printenergy, interval=4) self.dyn.run(Ni) # Do Ni steps # Open MD output #mdcrd.close() # Open MD output #traj.close() def __fragmentbox__(self, file, sig_cut): self.X = self.mol.get_positions() self.frag_list = [] self.Nd = 0 self.Nt = 0 for i in range(len(self.Na)): si = self.ctd[i][2] di = self.ctd[i][1] Nai = self.Na[i] Xci = np.sum(self.X[si:si + Nai, :], axis=0) / Nai Xi = self.X[si:si + Nai, :] if np.all(Xci > di) and np.all(Xci < self.L - di): for j in range(i + 1, len(self.Na)): sj = self.ctd[j][2] dj = self.ctd[j][1] Naj = self.Na[j] Xcj = np.sum(self.X[sj:sj + Naj, :], axis=0) / Naj Xj = self.X[sj:sj + Naj, :] if np.all(Xcj > dj) and np.all(Xcj < self.L - dj): dc = np.linalg.norm(Xci - Xcj) if dc < di + dj + 6.0: min = 10.0 for ii in range(Nai): Xiii = Xi[ii] for jj in range(Naj): Xjjj = Xj[jj] v = np.linalg.norm(Xiii - Xjjj) if v < min: min = v if min < 4.2 and min > 1.1: Xf = np.vstack([Xi, Xj]) Sf = self.S[si:si + Nai] Sf.extend(self.S[sj:sj + Naj]) Xcf = np.sum(Xf, axis=0) / (Nai + Naj) Xf = Xf - Xcf E = np.empty(5, dtype=np.float64) for id, nc in enumerate(self.aens.ncl): nc.setMolecule(coords=np.array( Xf, dtype=np.float32), types=Sf) E[id] = nc.energy()[0] sig = np.std( hdn.hatokcal * E) / np.sqrt(Nai + Naj) self.Nt += 1 if sig > sig_cut: self.Nd += 1 hdn.writexyzfile( file + str(i).zfill(4) + '-' + str(j).zfill(4) + '.xyz', Xf.reshape(1, Xf.shape[0], 3), Sf) self.frag_list.append( dict({ 'coords': Xf, 'spec': Sf }))
from asap3 import EMT # Way too slow with ase.EMT ! size = 10 T = 1500 # Kelvin # Set up a crystal atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], symbol="Cu", size=(size,size,size), pbc=False) # Describe the interatomic interactions with the Effective Medium Theory atoms.set_calculator(EMT()) # 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(atoms, 5*units.fs, T*units.kB, 0.002) #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=50) #We also want to save the positions of all atoms after every 100th time step. traj = PickleTrajectory("moldyn3.traj", 'w', atoms) dyn.attach(traj.write, interval=50) # Now run the dynamics printenergy()
def __init__(self, atoms, timestep, temperature, friction, fixcm=True, trajectory=None, logfile=None, loginterval=1): assert(getattr(Langevin_ASE, "_lgv_version", 1) >= 2) ParallelMolDynMixin.__init__(self, "Langevin", atoms) Langevin_ASE.__init__(self, atoms, timestep, temperature, friction, fixcm, trajectory, logfile, loginterval, communicator=None)
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)
d = 2.934 for R in r0list: print 'radius',R name=(folder,'%.1f' %R) atoms = fcc111('Au',size=(2,2,1),a=sqrt(2)*d) L = atoms.get_cell().diagonal() atoms. set_cell(L) angle = L[1]/R atoms.rotate('y',pi/2) atoms.translate( (-atoms[0].x,0,0) ) atoms.translate((R,0,0)) atoms = Atoms(atoms=atoms,container='Wedge') atoms.set_container(angle=angle,height=L[0],physical=False,pbcz=True) calc = Hotbit(SCC=False,txt='%s/optimization_%s.cal' %name,kpts=(nk,1,nk),physical_k=False) atoms.set_calculator(calc) traj = PickleTrajectory( 'md_R%.3f-T%.0f.traj' %(R,T),'w',atoms) dyn = Langevin(atoms,dt*units.fs,units.kB*T,fric) dyn.attach(MDLogger(dyn, atoms, path + 'md_R%.3f-T%.0f.log' %(R,T), header=False, stress=False, peratom=True, mode="w"), interval = 1) dyn.run(mdsteps) cohesion = mean([atoms.get_potential_energy() for a in traj]) /len(atoms) savez('%s/data_%s.npz' %name,cohesion=cohesion) io.write('%s/extended_%s.traj' %name,atoms2)