def traj_from_qe_xml(fileobj, index=-1, results_required=True): """Reads Quantum ESPRESSO output files. The atomistic configurations as well as results (energy, force, stress, magnetic moments) of the calculation are read for all configurations within the output file. Will probably raise errors for broken or incomplete files. Parameters ---------- fileobj : file|str A file like object or filename index : slice The index of configurations to extract. results_required : bool If True, atomistic configurations that do not have any associated results will not be included. This prevents double printed configurations and incomplete calculations from being returned as the final configuration with no results data. Yields ------ structure : Atoms The next structure from the index slice. The Atoms has a SinglePointCalculator attached with any results parsed from the file. """ root = ET.parse(fileobj).getroot() output = root.find('output') steps = root.findall('step') atoms, input_parameters = xml2atoms(output) trajectory = None trajectory = Trajectory('t1.traj', 'a') atoms_list = [] for step in steps: aaa, _ = xml2atoms(step) trajectory.write(aaa) atoms_list.append(aaa) trajectory.close() return atoms, input_parameters, atoms_list
def main(fname=None, ext="cif"): if fname is None: raise ValueError("No file name given") folder_name = fname.rpartition(".")[0] try: os.mkdir(folder_name) except OSError: pass traj = Trajectory(fname) for i, atom in enumerate(traj): atoms_file = folder_name + "/atoms{}.{}".format(i, ext) write(atoms_file, atom) print("Atoms written to {}".format(folder_name))
def test_unitcellfilter(): from math import sqrt from ase import Atoms from ase.optimize import LBFGS from ase.constraints import UnitCellFilter from ase.io import Trajectory from ase.optimize.mdmin import MDMin try: from asap3 import EMT except ImportError: pass else: a = 3.6 b = a / 2 cu = Atoms('Cu', cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1) * (6, 6, 6) cu.set_calculator(EMT()) f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.build import bulk cu = bulk('Cu', 'hcp', a=a / sqrt(2)) cu.cell[1, 0] -= 0.05 cu *= (6, 6, 3) cu.set_calculator(EMT()) print(cu.get_forces()) print(cu.get_stress()) f = UnitCellFilter(cu) opt = MDMin(f, dt=0.01) t = Trajectory('Cu-hcp.traj', 'w', cu) opt.attach(t) opt.run(0.2)
def test_unitcellfilter(asap3): a = 3.6 b = a / 2 cu = Atoms('Cu', cell=[(0, b, b), (b, 0, b), (b, b, 0)], pbc=1) * (6, 6, 6) cu.calc = asap3.EMT() f = UnitCellFilter(cu, [1, 1, 1, 0, 0, 0]) opt = LBFGS(f) t = Trajectory('Cu-fcc.traj', 'w', cu) opt.attach(t) opt.run(5.0) # HCP: from ase.build import bulk cu = bulk('Cu', 'hcp', a=a / sqrt(2)) cu.cell[1, 0] -= 0.05 cu *= (6, 6, 3) cu.calc = asap3.EMT() print(cu.get_forces()) print(cu.get_stress()) f = UnitCellFilter(cu) opt = MDMin(f, dt=0.01) t = Trajectory('Cu-hcp.traj', 'w', cu) opt.attach(t) opt.run(0.2)
def relaxGPAW(structure, label, calc=None, forcemax=0.1, niter_max=1, steps=10): # Create calculator if calc is None: calc = GPAW( poissonsolver=PoissonSolver(relax='GS', eps=1.0e-7), # C mode='lcao', basis='dzp', xc='PBE', gpts=h2gpts(0.2, structure.get_cell(), idiv=8), # C occupations=FermiDirac(0.1), maxiter=99, # C #maxiter=49, # Sn3O3 mixer=Mixer(nmaxold=5, beta=0.05, weight=75), nbands=-50, #kpts=(1,1,1), # C kpts=(2, 2, 1), # Sn3O3 txt=label + '_lcao.txt') else: calc.set(txt=label + '_true.txt') # Set calculator structure.set_calculator(calc) # loop a number of times to capture if minimization stops with high force # due to the VariansBreak calls niter = 0 # If the structure is already fully relaxed just return it if (structure.get_forces()**2).sum(axis=1).max()**0.5 < forcemax: return structure traj = Trajectory(label + '_lcao.traj', 'w', structure) while (structure.get_forces()** 2).sum(axis=1).max()**0.5 > forcemax and niter < niter_max: dyn = BFGS(structure, logfile=label + '.log') vb = VariansBreak(structure, dyn, min_stdev=0.01, N=15) dyn.attach(traj) dyn.attach(vb) dyn.run(fmax=forcemax, steps=steps) niter += 1 return structure
def main(): arg = sys.argv paras = readinputs(arg[1]) distances = paras['distance'].split() md_traj = read('3w-pos-1.xyz', index=slice(-3000, None), format='xyz') for p in md_traj: dist = p.get_distance(7, 13) + p.get_distance(9, 11) for distance in distances: if dist > float(distance) - 0.05 and dist < float(distance) + 0.05: make_dir(distance) write(distance + '/geometry.xyz', p, format='xyz') break traj = Trajectory('selected.traj', 'w') for distance in distances: traj.write( read(distance + '/geometry.xyz', index=':', format='xyz')[0])
def backup_outcar(): # it needs some improvement. Use with caution. import os import numpy as np from ase.io import read, write, Trajectory calc_id = int(np.loadtxt('db_id')) if os.path.isfile( 'OUTCAR') and not os.path.isfile(f'opt_id_{calc_id}.traj'): write(f'opt_id_{calc_id}.traj', read('OUTCAR', index=':')) elif os.path.isfile('OUTCAR') and os.path.isfile(f'opt_id_{calc_id}.traj'): t1 = Trajectory(f'opt_id_{calc_id}.traj', 'a') t2 = read('OUTCAR', index=':') for atoms in t2: t1.write(atoms) t1.close() return print('OUTCAR backup complete')
def train(): # Load the images with ASE images = Trajectory("cu_training.traj") # Arguments for fingerprinting the images normalized = True calc = Potentials( features=Gaussian(cutoff=6.5, normalized=normalized, save_preprocessor="cu_training.scaler"), # model=GaussianProcess(batch_size=batch_size), model=GaussianProcess(), label="cu_training", ) calc.train(training_set=images)
def main(): """docstring for main""" # Load the images with ASE images = Trajectory("cu_training.traj") calc = Potentials.load( model="cu_training.ml4c", params="cu_training.params", preprocessor="model.scaler", ) for atoms in images: energy = calc.get_potential_energy(atoms) print("ML4Chem predicted energy = {}".format(energy)) print(" DFT energy = {}".format( atoms.get_potential_energy()))
def run(T, sysID): ceBulk = init_BC() prec = 1E-4 db = dataset.connect("sqlite:///" + mc_db_name) entry = db["systems"].find_one(id=sysID) chem_pot = {"c1_0": entry["c1_0"], "c1_1": entry["c1_1"]} if entry["status"] == "finished": return equil_params = {"window_length": 30 * len(ceBulk.atoms), "mode": "fixed"} max_steps = 1000 * len(ceBulk.atoms) trajfile = "data/almgsi_sgc/traj_{}.traj".format(sysID) traj = None if rank == 0: traj = Trajectory(trajfile, mode='w') for temp in T: print("Current temperature {}K".format(temp)) mc_obj = SGCMonteCarlo(ceBulk.atoms, temp, mpicomm=comm, symbols=["Al", "Mg", "Si"]) mc_obj.runMC(mode="prec", prec=prec, chem_potential=chem_pot, equil_params=equil_params, steps=max_steps) thermo = mc_obj.get_thermodynamic() thermo["temperature"] = temp thermo["prec"] = prec thermo["internal_energy"] = thermo.pop("energy") thermo["converged"] = True thermo["muc1_0"] = chem_pot["c1_0"] thermo["muc1_1"] = chem_pot["c1_1"] if (rank == 0): thermo["sysID"] = sysID newID = db["thermodynamic"].insert(thermo) cf = ceBulk.atoms._calc.get_cf() cf["resultID"] = newID db["correlation"].insert(cf) atoms_cpy = ceBulk.atoms.copy() atoms_cpy.set_calculator(None) traj.write(atoms_cpy) if (rank == 0): db["systems"].update({"status": "finished", "id": sysID}, ["id"])
def test_verlet(): with seterr(all='raise'): a = Atoms('4X', masses=[1, 2, 3, 4], positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0), (0.1, 0.2, 0.7)], calculator=TstPotential()) print(a.get_forces()) md = VelocityVerlet(a, timestep=0.5 * fs, logfile='-', loginterval=500) traj = Trajectory('4N.traj', 'w', a) md.attach(traj.write, 100) e0 = a.get_total_energy() md.run(steps=10000) del traj assert abs(read('4N.traj').get_total_energy() - e0) < 0.0001 qn = QuasiNewton(a) qn.run(0.001) assert abs(a.get_potential_energy() - 1.0) < 0.000002
def relaxGPAW(structure, label, forcemax=0.1, niter_max=1, steps=10): # Set calculator # loop a number of times to capture if minimization stops with high force # due to the VariansBreak calls niter = 0 # If the structure is already fully relaxed just return it traj = Trajectory(label + '_lcao.traj', 'w', structure) while (structure.get_forces()** 2).sum(axis=1).max()**0.5 > forcemax and niter < niter_max: dyn = BFGS(structure, logfile=label + '.log') vb = VariansBreak(structure, dyn, min_stdev=0.01, N=15) dyn.attach(traj) dyn.attach(vb) dyn.run(fmax=forcemax, steps=steps) niter += 1 #print('relaxgpaw over',flush=True) return structure
def optimize(self, atoms, name): args = self.args if args.constrain_tags: tags = [int(t) for t in args.constrain_tags.split(',')] mask = [t in tags for t in atoms.get_tags()] atoms.constraints = FixAtoms(mask=mask) logfile = self.get_filename(name, 'log') if args.maximum_stress: optimizer = LBFGS(UnitCellFilter(atoms), logfile=logfile) fmax = args.maximum_stress else: optimizer = LBFGS(atoms, logfile=logfile) fmax = args.maximum_force trajectory = Trajectory(self.get_filename(name, 'traj'), 'w', atoms) optimizer.attach(trajectory) optimizer.run(fmax=fmax)
def test_example(testdir): atoms = Atoms('H7', positions=[(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0), (0.5, 0.5, 1)], constraint=[FixAtoms(range(6))], calculator=MorsePotential()) with Trajectory('H.traj', 'w', atoms) as traj, \ QuasiNewton(atoms, maxstep=0.2) as dyn: dyn.attach(traj.write) dyn.run(fmax=0.01, steps=100) print(atoms) del atoms[-1] print(atoms) del atoms[5] print(atoms) assert len(atoms.constraints[0].index) == 5
def main(): arg = sys.argv try: configs = read(arg[1], index=":") except: configs = read_atoms(arg[1]) traj = Trajectory('selected_' + arg[1], 'w') chem_symbols = ['H', 'Pd'] H_indices = [atom.index for atom in configs[0] if atom.symbol == 'H'] Pd_indices = [atom.index for atom in configs[0] if atom.symbol == 'Pd'] #temp = copy.deepcopy(configs) for itrj in range(len(configs)): print itrj config = configs[itrj] delete = False for i in range(len(H_indices) - 1): for j in range(i + 1, len(H_indices)): if config.get_distance(H_indices[i], H_indices[j]) < 0.5: delete = True break if delete: break for pd in Pd_indices: if config.get_distance(H_indices[i], pd) < 1.00: delete = True break if delete: break if delete: continue for i in range(len(Pd_indices) - 1): for j in range(i + 1, len(Pd_indices)): if config.get_distance(Pd_indices[i], Pd_indices[j]) < 2.00: delete = True break if delete: break if delete: continue traj.write(config)
def init_model(atoms, samples=5, rattle=0.05, trajectory='init.traj'): """ atoms: ASE atoms samples: number of samples rattle: stdev for random displacements trajectory: traj file name """ calc = cline.gen_active_calc() master = calc.rank == 0 if master: traj = Trajectory(trajectory, 'w') for _ in range(samples): tmp = atoms.copy() tmp.rattle(rattle, rng=np.random) tmp.set_calculator(calc) tmp.get_potential_energy() if master: traj.write(tmp)
def test_verlet_asap(asap3): with seterr(all='raise'): a = bulk('Au').repeat((2, 2, 2)) a[5].symbol = 'Ag' a.pbc = (True, True, False) print(a) a.calc = asap3.EMT() MaxwellBoltzmannDistribution(a, 300 * kB, force_temp=True) Stationary(a) assert abs(a.get_temperature() - 300) < 0.0001 print(a.get_forces()) md = VelocityVerlet(a, timestep=2 * fs, logfile='-', loginterval=500) traj = Trajectory('Au7Ag.traj', 'w', a) md.attach(traj.write, 100) e0 = a.get_total_energy() md.run(steps=10000) del traj assert abs(a.get_total_energy() - e0) < 0.0001 assert abs(read('Au7Ag.traj').get_total_energy() - e0) < 0.0001
def __init__(self, X=None, traj=None): if X is not None: self.X = [] for loc in X: assert loc.__class__ == Local self.X += [loc] elif traj is not None: from ase.io import Trajectory t = Trajectory(traj, 'r') self.X = [] for atoms in t: tatoms = TorchAtoms(ase_atoms=atoms) if not np.allclose(tatoms.positions[0], np.zeros((3, ))): raise RuntimeError self.X += [tatoms.as_local()] t.close() else: raise RuntimeError('LocalsData invoked without any input') self.trainable = False
def save_as_xyz(self, filename='./traj.xyz'): traj = Trajectory(self.mdparam['traj_filename'], mode='r') xyz = [] skip = self.mdparam['skip'] traj = list(traj)[skip:] if len(traj) > skip else traj for snapshot in traj: frames = np.concatenate([ snapshot.get_atomic_numbers().reshape(-1, 1), snapshot.get_positions().reshape(-1, 3) ], axis=1) xyz.append(frames) write_traj(filename, np.array(xyz))
def force_integration(images, amp_calc=None): """Compute force integration over images using pure ML Parameters ---------- images : str Path to images. amp_calc : str Path to .amp file containing information of the machine-learning model. """ # Loading data data = Trajectory(images) # Computing references E0 can be 0 or a DFT calcualtion of the reference E0 = 0 p0 = data[0].get_positions() # Loading Amp calculator amp_calc = Amp.load(amp_calc) temp = 0 for index in range(len(data)): image = data[index] p1 = image.get_positions() if index == 0: forcesi = amp_calc.get_forces(data[0]) else: p0 = data[index - 1].get_positions() forcesi = amp_calc.get_forces(data[index - 1]) forcesj = amp_calc.get_forces(image) forces = (forcesj + forcesi) / 2 E = 0. for atom in range(len(image)): driu = p1[atom] - p0[atom] temp += forces[atom].dot(driu) E = E0 - temp print(E) return E
def init_extra_info(self): # initialize booleans for extra calculations self.pca_quantify = False self.uncertainty_quantify = False self.parent_traj = None # if a trajectory is supplied in the optional config, store that for PCA, uncertainty metrics, etc. if (self.optional_config is not None and "links" in self.optional_config and "traj" in self.optional_config["links"]): self.parent_traj = Trajectory( self.optional_config["links"]["traj"]) self.pca_quantify = self.learner_params.get("logger", {}).get( "pca_quantify", False) self.uncertainty_quantify = self.learner_params.get( "logger", {}).get("uncertainty_quantify", False) if self.pca_quantify: self.pca_analyzer = TrajPCA(self.parent_traj)
def __init__( self, atomsbatch, nms_vel, mdparam, ): # initialize the atoms batch system self.atomsbatch = atomsbatch self.mdparam = mdparam #initialize velocity from nms self.vel = nms_vel self.temperature = self.mdparam['T_init'] self.friction = self.mdparam['friction'] # todo: structure optimization before starting # intialize system momentum by normal mode sampling self.atomsbatch.set_velocities(self.vel.reshape(-1, 3) * Ang / second) # set thermostats integrator = self.mdparam['thermostat'] self.integrator = integrator(self.atomsbatch, self.mdparam['time_step'] * fs, self.temperature * kB, self.friction) # attach trajectory dump self.traj = Trajectory(self.mdparam['traj_filename'], 'w', self.atomsbatch) self.integrator.attach(self.traj.write, interval=mdparam['save_frequency']) # attach log file self.integrator.attach(NeuralMDLogger(self.integrator, self.atomsbatch, self.mdparam['thermo_filename'], mode='a'), interval=mdparam['save_frequency'])
def __init__(self, atoms, calculator, minmode=davidson, H0=None, v0=None, trshift=1000, trshift_factor=4., use_angles=True, use_dihedrals=True, trajectory=None, extra_bonds=None): MinModeAtoms.__init__(self, atoms, None, minmode, H0, v0, trshift, trshift_factor, True, False, None) self.use_angles = use_angles self.use_dihedrals = use_dihedrals self.internal = Internal(self.atoms, angles=self.use_angles, dihedrals=self.use_dihedrals, extra_bonds=extra_bonds) if self.internal.ninternal < 3 * len(self.atoms) - 6: raise RuntimeError('Not enough internal coordinates found! ' 'Consider using angles or dihedrals.') self.d = 3 * self.internal.natoms self.ndof = 3 * len(self.internal.atoms) - 6 self.atoms = self.internal.atoms self.atoms.set_calculator(calculator) if trajectory is not None: self.trajectory = Trajectory(trajectory, 'w', self.atoms) else: self.trajectory = None
def save_as_xyz(self, filename): ''' TODO: save time information TODO: subclass TrajectoryReader/TrajectoryReader to digest AtomsBatch instead of Atoms? TODO: other system variables in .xyz formats ''' traj = Trajectory(self.mdparam['traj_filename'], mode='r') xyz = [] for snapshot in traj: frames = np.concatenate([ snapshot.get_atomic_numbers().reshape(-1, 1), snapshot.get_positions().reshape(-1, 3) ], axis=1) xyz.append(frames) write_traj(filename, np.array(xyz))
def main(): """docstring for main""" # Load the images with ASE images = Trajectory("cu_training.traj") calc = Potentials.load( model="cu_training.ml4c", params="cu_training.params", preprocessor="cu_training.scaler", ) # Passage of fingerprint database with reference space calc.reference_space = "fingerprints.db" for atoms in images: energy = calc.get_potential_energy(atoms) print("ML4Chem predicted energy = {}".format(energy)) print(" DFT energy = {}".format( atoms.get_potential_energy()))
def test_optimizer(cls, testdir, atoms, calc): """run optimization and verify that log and trajectory coincide""" opt_atoms = atoms.copy() opt_atoms.constraints = atoms.constraints logfile = 'opt.log' trajectory = 'opt.traj' opt_atoms.calc = calc with cls(opt_atoms, logfile=logfile, trajectory=trajectory) as opt: opt.run(0.2) opt.run(0.1) with Trajectory(trajectory) as traj, open(logfile) as f: next(f) for _, (a, line) in enumerate(zip(traj, f)): fmax1 = float(line.split()[-1]) fmax2 = fmax(a.get_forces()) assert np.allclose(fmax1, fmax2, atol=0.01), (fmax1, fmax2)
def run_test(atoms, optimizer, tag, fmax=0.02): wrapper = Wrapper(atoms) relax = optimizer(wrapper, logfile=tag + '.log') relax.attach(Trajectory(tag + '.traj', 'w', atoms=atoms)) tincl = -time() error = '' try: relax.run(fmax=fmax, steps=10000000) except Exception as x: wrapper.nsteps = float('inf') error = '{}: {}'.format(x.__class__.__name__, x) tb = traceback.format_exc() with open(tag + '.err', 'w') as fd: fd.write('{}\n{}\n'.format(error, tb)) tincl += time() return error, wrapper.nsteps, wrapper.texcl, tincl
def test_md(cls, atoms, calc, kwargs, logfile="md.log", timestep=1 * u.fs, trajectory="md.traj"): """ run MD for 10 steps and verify that trajectory and log coincide """ # clean files to make sure the correct ones are tested for file in (*Path().glob("*.log"), *Path().glob("*.traj")): file.unlink() if hasattr(atoms, "constraints"): del atoms.constraints atoms.calc = calc md = cls(atoms, logfile=logfile, timestep=timestep, trajectory=trajectory, **kwargs) # run md two times md.run(steps=5) md.run(steps=5) # assert log file has correct length length = sum(1 for l in open(logfile)) assert length == 12, length with Trajectory(trajectory) as traj, open(logfile) as f: next(f) for _, (a, line) in enumerate(zip(traj, f)): Epot1, T1 = float(line.split()[-3]), float(line.split()[-1]) Epot2, T2 = a.get_potential_energy(), a.get_temperature() assert np.allclose(T1, T2, atol=0.1), (T1, T2) assert np.allclose(Epot1, Epot2, atol=0.01), (Epot1, Epot2)
def test_md(cls, atoms, kwargs, logfile="md.log", timestep=1 * u.fs, trajectory="md.traj", loginterval=1): """ run MD for 10 steps and verify that log and trajectory have same number of steps""" # clean files to make sure the correct ones are tested for f in (logfile, trajectory): if os.path.exists(f): os.unlink(f) assert not atoms.constraints print("Testing", str(cls)) md = cls(atoms, logfile=logfile, timestep=timestep, trajectory=trajectory, loginterval=loginterval, **kwargs) # run md two times md.run(steps=5) md.run(steps=5) # Test number of lines in log file matches number of frames in trajectory with open(logfile, 'rt') as lf: lines = [l for l in lf] loglines = len(lines) print("Number of lines in log file:", loglines) with Trajectory(trajectory) as traj: trajframes = len(traj) print("Number of frames in trajectory:", trajframes) # There is a header line in the logfile assert loglines == trajframes + 1
def test_optimization_log_and_trajectory_length(cls): logfile = 'opt.log' trajectory = 'opt.traj' atoms = make_dimer() print("Testing", str(cls)) with cls(atoms, logfile=logfile, trajectory=trajectory) as opt: opt.run(0.2) opt.run(0.1) # Test number of lines in log file matches number of frames in trajectory with open(logfile, 'rt') as lf: lines = [l for l in lf] loglines = len(lines) print("Number of lines in log file:", loglines) with Trajectory(trajectory) as traj: trajframes = len(traj) print("Number of frames in trajectory:", trajframes) # There is a header line in the logfile assert loglines == trajframes + 1