def read_dacapo(filename): from ase_ext.io.pupynere import NetCDFFile nc = NetCDFFile(filename) dims = nc.dimensions vars = nc.variables cell = vars['UnitCell'][-1] try: magmoms = vars['InitialAtomicMagneticMoment'][:] except KeyError: magmoms = None try: tags = vars['AtomTags'][:] except KeyError: tags = None atoms = Atoms(scaled_positions=vars['DynamicAtomPositions'][-1], symbols=[(a + b).strip() for a, b in vars['DynamicAtomSpecies'][:]], cell=cell, magmoms=magmoms, tags=tags, pbc=True) try: energy = vars['TotalEnergy'][-1] force = vars['DynamicAtomForces'][-1] except KeyError: energy = None force = None calc = SinglePointCalculator(energy, force, None, None, atoms) ### Fixme magmoms atoms.set_calculator(calc) return atoms
def read_xsf(fileobj, index=-1): if isinstance(fileobj, str): fileobj = open(fileobj) readline = fileobj.readline line = readline() if line.startswith('ANIMSTEPS'): nimages = int(line.split()[1]) line = readline() else: nimages = 1 if line.startswith('CRYSTAL'): pbc = True elif line.startswith('SLAB'): pbc = (True, True, Flase) elif line.startswith('POLYMER'): pbc = (True, False, Flase) else: pbc = False images = [] for n in range(nimages): cell = None if pbc: line = readline() assert line.startswith('PRIMVEC') cell = [] for i in range(3): cell.append([float(x) for x in readline().split()]) line = readline() assert line.startswith('PRIMCOORD') natoms = int(readline().split()[0]) numbers = [] positions = [] for a in range(natoms): line = readline().split() numbers.append(int(line[0])) positions.append([float(x) for x in line[1:]]) positions = np.array(positions) if len(positions[0]) == 3: forces = None else: positions = positions[:, :3] forces = positions[:, 3:] * Hartree image = Atoms(numbers, positions, cell=cell, pbc=pbc) if forces is not None: image.set_calculator(SinglePointCalculator(None, forces, None, None, image)) images.append(image) return images[index]
def calculate_and_hide(i): image = self.images[i] calc = image.get_calculator() if self.calculators[i] is None: self.calculators[i] = calc if calc is not None: if not isinstance(calc, SinglePointCalculator): self.images[i].set_calculator( SinglePointCalculator(image.get_potential_energy(), image.get_forces(), None, None, image)) self.emax = min(self.emax, image.get_potential_energy())
def get_atoms(self, frame): atoms = Atoms(positions=self.P[frame], numbers=self.Z, magmoms=self.M[0], tags=self.T, cell=self.A[frame], pbc=self.pbc) # check for constrained atoms and add them accordingly: if not self.dynamic.all(): atoms.set_constraint(FixAtoms(mask=1 - self.dynamic)) atoms.set_calculator( SinglePointCalculator(self.E[frame], self.F[frame], None, None, atoms)) return atoms
def read_dacapo_text(fileobj): if isinstance(fileobj, str): fileobj = open(fileobj) lines = fileobj.readlines() i = lines.index(' Structure: A1 A2 A3\n') cell = np.array([[float(w) for w in line.split()[2:5]] for line in lines[i + 1:i + 4]]).transpose() i = lines.index(' Structure: >> Ionic positions/velocities ' + 'in cartesian coordinates <<\n') atoms = [] for line in lines[i + 4:]: words = line.split() if len(words) != 9: break Z, x, y, z = words[2:6] atoms.append(Atom(int(Z), [float(x), float(y), float(z)])) atoms = Atoms(atoms, cell=cell.tolist()) try: i = lines.index( ' DFT: CPU time Total energy\n') except ValueError: pass else: column = lines[i + 3].split().index('selfcons') - 1 try: i2 = lines.index(' ANALYSIS PART OF CODE\n', i) except ValueError: pass else: while i2 > i: if lines[i2].startswith(' DFT:'): break i2 -= 1 energy = float(lines[i2].split()[column]) atoms.set_calculator( SinglePointCalculator(energy, None, None, None, atoms)) return atoms
def __getitem__(self, i=-1): N = len(self.offsets) if 0 <= i < N: self.fd.seek(self.offsets[i]) try: d = pickle.load(self.fd) except EOFError: raise IndexError if i == N - 1: self.offsets.append(self.fd.tell()) try: magmoms = d['magmoms'] except KeyError: magmoms = None atoms = Atoms(positions=d['positions'], numbers=self.numbers, cell=d['cell'], momenta=d['momenta'], magmoms=magmoms, tags=self.tags, masses=self.masses, pbc=self.pbc, constraint=[c.copy() for c in self.constraints]) if 'energy' in d: calc = SinglePointCalculator(d.get('energy', None), d.get('forces', None), d.get('stress', None), magmoms, atoms) atoms.set_calculator(calc) return atoms if i >= N: for j in range(N - 1, i + 1): atoms = self[j] return atoms i = len(self) + i if i < 0: raise IndexError('Trajectory index out of range.') return self[i]
def read_aims_output(filename, index=-1): """ Import FHI-aims output files with all data available, i.e. relaxations, MD information, force information etc etc etc. """ from ase_ext import Atoms, Atom from ase_ext.calculators.singlepoint import SinglePointCalculator from ase_ext.units import Ang, fs molecular_dynamics = False fd = open(filename, 'r') cell = [] images = [] n_periodic = -1 f = None pbc = False found_aims_calculator = False v_unit = Ang / (1000.0 * fs) while True: line = fd.readline() if not line: break if "List of parameters used to initialize the calculator:" in line: fd.readline() calc = read_aims_calculator(fd) calc.out = filename found_aims_calculator = True if "Number of atoms" in line: inp = line.split() n_atoms = int(inp[5]) if "| Unit cell:" in line: if not pbc: pbc = True for i in range(3): inp = fd.readline().split() cell.append([inp[1], inp[2], inp[3]]) if "Atomic structure:" in line and not molecular_dynamics: fd.readline() atoms = Atoms() for i in range(n_atoms): inp = fd.readline().split() atoms.append(Atom(inp[3], (inp[4], inp[5], inp[6]))) if "Complete information for previous time-step:" in line: molecular_dynamics = True if "Updated atomic structure:" in line and not molecular_dynamics: fd.readline() atoms = Atoms() velocities = [] for i in range(n_atoms): inp = fd.readline().split() atoms.append(Atom(inp[4], (inp[1], inp[2], inp[3]))) if molecular_dynamics: inp = fd.readline().split() if "Atomic structure (and velocities)" in line: fd.readline() atoms = Atoms() velocities = [] for i in range(n_atoms): inp = fd.readline().split() atoms.append(Atom(inp[4], (inp[1], inp[2], inp[3]))) inp = fd.readline().split() velocities += [[ float(inp[1]) * v_unit, float(inp[2]) * v_unit, float(inp[3]) * v_unit ]] atoms.set_velocities(velocities) images.append(atoms) if "Total atomic forces" in line: f = [] for i in range(n_atoms): inp = fd.readline().split() f.append([float(inp[2]), float(inp[3]), float(inp[4])]) if not found_aims_calculator: e = images[-1].get_potential_energy() images[-1].set_calculator( SinglePointCalculator(e, f, None, None, atoms)) e = None f = None if "Total energy corrected" in line: e = float(line.split()[5]) if pbc: atoms.set_cell(cell) atoms.pbc = True if not found_aims_calculator: atoms.set_calculator( SinglePointCalculator(e, None, None, None, atoms)) if not molecular_dynamics: images.append(atoms) e = None if found_aims_calculator: calc.set_results(images[-1]) images[-1].set_calculator(calc) fd.close() if molecular_dynamics: images = images[1:] # return requested images, code borrowed from ase_ext.io/trajectory.py if isinstance(index, int): return images[index] else: step = index.step or 1 if step > 0: start = index.start or 0 if start < 0: start += len(images) stop = index.stop or len(images) if stop < 0: stop += len(images) else: if index.start is None: start = len(images) - 1 else: start = index.start if start < 0: start += len(images) if index.stop is None: stop = -1 else: stop = index.stop if stop < 0: stop += len(images) return [images[i] for i in range(start, stop, step)]
def read_netcdf(filename, index=-1): nc = NetCDFFile(filename) dims = nc.dimensions vars = nc.variables positions = vars['CartesianPositions'] numbers = vars['AtomicNumbers'][:] pbc = vars['BoundaryConditions'][:] cell = vars['UnitCell'] tags = vars['Tags'][:] if not tags.any(): tags = None magmoms = vars['MagneticMoments'][:] if not magmoms.any(): magmoms = None nimages = positions.shape[0] attach_calculator = False if 'PotentialEnergy' in vars: energy = vars['PotentialEnergy'] attach_calculator = True else: energy = nimages * [None] if 'CartesianForces' in vars: forces = vars['CartesianForces'] attach_calculator = True else: forces = nimages * [None] if 'Stress' in vars: stress = vars['Stress'] attach_calculator = True else: stress = nimages * [None] if isinstance(index, int): indices = [index] else: indices = list(range(nimages))[index] images = [] for i in indices: atoms = Atoms(positions=positions[i], numbers=numbers, cell=cell[i], pbc=pbc, tags=tags, magmoms=magmoms) if attach_calculator: calc = SinglePointCalculator(energy[i], forces[i], stress[i], None, atoms) ### Fixme magmoms atoms.set_calculator(calc) images.append(atoms) if isinstance(index, int): return images[0] else: return images
def read_gpaw_text(fileobj, index=-1): if isinstance(fileobj, str): fileobj = open(fileobj) def index_startswith(lines, string): for i, line in enumerate(lines): if line.startswith(string): return i raise ValueError lines = fileobj.readlines() images = [] while True: try: i = lines.index('Unit Cell:\n') except ValueError: pass else: cell = [] pbc = [] for line in lines[i + 3:i + 6]: words = line.split() if len(words) == 5: # old format cell.append(float(words[2])) pbc.append(words[1] == 'yes') else: # new format with GUC cell.append([float(word) for word in words[3:6]]) pbc.append(words[2] == 'yes') try: i = lines.index('Positions:\n') except ValueError: break atoms = Atoms(cell=cell, pbc=pbc) for line in lines[i + 1:]: words = line.split() if len(words) != 5: break n, symbol, x, y, z = words symbol = symbol.split('.')[0] atoms.append(Atom(symbol, [float(x), float(y), float(z)])) lines = lines[i + 5:] try: i = lines.index('-------------------------\n') except ValueError: e = None else: line = lines[i + 9] assert line.startswith('Zero Kelvin:') e = float(line.split()[-1]) try: ii = index_startswith(lines, 'Total Charge:') except ValueError: q = None else: q = float(lines[ii].split()[2]) try: ii = lines.index('Forces in eV/Ang:\n') except ValueError: f = None else: f = [] for i in range(ii + 1, ii + 1 + len(atoms)): try: x, y, z = lines[i].split()[-3:] f.append((float(x), float(y), float(z))) except (ValueError, IndexError) as m: raise IOError('Malformed GPAW log file: %s' % m) if len(images) > 0 and e is None: break if e is not None or f is not None: atoms.set_calculator(SinglePointCalculator( e, f, None, None, atoms)) ### Fixme magmoms if q is not None: n = len(atoms) atoms.set_charges([q / n] * n) images.append(atoms) lines = lines[i:] if len(images) == 0: raise IOError('Corrupted GPAW-text file!') return images[index]
def read_vasp_out(filename='OUTCAR', index=-1): """Import OUTCAR type file. Reads unitcell, atom positions, energies, and forces from the OUTCAR file. - does not (yet) read any constraints """ import os import numpy as np from ase_ext.calculators.singlepoint import SinglePointCalculator from ase_ext import Atoms, Atom if isinstance(filename, str): f = open(filename) else: # Assume it's a file-like object f = filename data = f.readlines() natoms = 0 images = [] atoms = Atoms(pbc=True) energy = 0 species = [] species_num = [] symbols = [] for n, line in enumerate(data): if 'POSCAR:' in line: temp = line.split() species = temp[1:] if 'ions per type' in line: temp = line.split() for ispecies in range(len(species)): species_num += [int(temp[ispecies + 4])] natoms += species_num[-1] for iatom in range(species_num[-1]): symbols += [species[ispecies]] if 'direct lattice vectors' in line: cell = [] for i in range(3): temp = data[n + 1 + i].split() cell += [[float(temp[0]), float(temp[1]), float(temp[2])]] atoms.set_cell(cell) if 'FREE ENERGIE OF THE ION-ELECTRON SYSTEM' in line: energy = float(data[n + 2].split()[4]) if 'POSITION ' in line: forces = [] for iatom in range(natoms): temp = data[n + 2 + iatom].split() atoms += Atom(symbols[iatom], [float(temp[0]), float(temp[1]), float(temp[2])]) forces += [[float(temp[3]), float(temp[4]), float(temp[5])]] atoms.set_calculator( SinglePointCalculator(energy, forces, None, None, atoms)) images += [atoms] atoms = Atoms(pbc=True) # return requested images, code borrowed from ase_ext.io/trajectory.py if isinstance(index, int): return images[index] else: step = index.step or 1 if step > 0: start = index.start or 0 if start < 0: start += len(images) stop = index.stop or len(images) if stop < 0: stop += len(images) else: if index.start is None: start = len(images) - 1 else: start = index.start if start < 0: start += len(images) if index.stop is None: stop = -1 else: stop = index.stop if stop < 0: stop += len(images) return [images[i] for i in range(start, stop, step)]