def _read_geom_output(self, out): """Reads geometry optimisation output from ONETEP output file""" conv_fac = Bohr # Find start of atom positions while 'x-----' not in out.readline(): pass symbols = [] positions = [] # Read atom positions line = out.readline() while 'xxxxxx' not in line: line = line.strip() pos = line.split()[3:6] pos = [conv_fac * float(p) for p in pos] atom = line.split()[1] positions.append(pos) symbols.append(atom) line = out.readline() if len(positions) != len(self.atoms): raise ReadError('Wrong number of atoms found in output geometry' 'block') if len(symbols) != len(self.atoms): raise ReadError('Wrong number of atoms found in output geometry' 'block') # Update atoms object with new positions (and symbols) self.atoms.set_positions(positions) self.atoms.set_chemical_symbols(symbols)
def _read_lattice(self, out): """ read the lattice parameters out of a onetep .out formatted file stream""" axes = [] l = out.readline() # onetep assumes lengths are in atomic units by default conv_fac = Bohr if 'ang' in l: l = out.readline() conv_fac = 1.0 elif 'bohr' in l: l = out.readline() for _ in range(0, 3): l = l.strip() p = l.split() if len(p) != 3: raise ReadError('Malformed Lattice block line "%s"' % l) try: axes.append([conv_fac * float(comp) for comp in p[0:3]]) except ValueError: raise ReadError("Can't parse line \"%s\" in axes block" % l) l = out.readline() self.atoms.set_cell(axes)
def read(self, label): """Read a onetep .out file into the current instance.""" FileIOCalculator.read(self, label) onetep_file = self.label + '.out' warnings = [] try: out = paropen(onetep_file, 'r') except IOError: raise ReadError('Could not open output file "%s"' % onetep_file) # keep track of what we've read in read_lattice = False read_species = False read_positions = False line = out.readline() if self.atoms is None: self.atoms = Atoms() self.atoms.calc = self while line: clean_line = line.strip().lower() if '%block lattice_cart' in clean_line: self._read_lattice(out) read_lattice = True elif '%block species_pot' in clean_line: self._read_species_pot(out) elif clean_line.endswith('%block species_atomic_set'): self._read_species_solver(out) elif clean_line.endswith('%block species'): self._read_species(out) read_species = True elif '%block positions_abs' in clean_line: self._read_positions(out) read_positions = True elif '%block species_cond' in clean_line: self._read_species(out,cond=True) elif '%block species_atomic_set_cond' in clean_line: self._read_species_solver(out,cond=True) elif 'warn' in line.lower(): warnings.append(line) line = out.readline() out.close() if warnings: warn('WARNING: %s contains warnings' % onetep_file) for warning in warnings: warn(warning) if not (read_lattice and read_species and read_positions): raise ReadError('Failed to read in essential calculation' ' data from output file "%s"' % onetep_file) self.read_results(label)
def read(self, label): FileIOCalculator.read(self, label) filename = self.label + ".log" with open(filename, 'r') as f: lines = f.readlines() if 'WARNING' in lines: raise ReadError("Not convergy energy in log file {}.".format(filename)) if not '! total energy' in lines: raise ReadError("Wrong ACE-Molecule log file {}.".format(filename)) if not os.path.isfile(filename): raise ReadError("Wrong ACE-Molecule input file {}.".format(filename)) self.read_results()
def read_forces(self, atoms): """Read forces from the deMon.ase file.""" natoms = len(atoms) epath = pl.Path(self.label) if not (epath / 'deMon.ase').exists(): raise ReadError('The deMonNano output file for ASE {0} does not exist' .format(epath)) filename = self.label + '/deMon.ase' with open(filename, 'r') as fd: lines = fd.readlines() # find line where the forces start flag_found = False for i in range(len(lines)): if 'DFTB gradients at 0 time step in a.u.' in lines[i]: start = i + 1 flag_found = True break if flag_found: self.results['forces'] = np.zeros((natoms, 3), float) for i in range(natoms): line = [s for s in lines[i + start].strip().split(' ') if len(s) > 0] f = -np.array([float(x) for x in line[1:4]]) # output forces in a.u. #self.results['forces'][i, :] = f # output forces with real dimension self.results['forces'][i, :] = f * (Hartree / Bohr)
def read(self, label): """Read psi4 outputs made from this ASE calculator """ filename = label + '.dat' if not os.path.isfile(filename): raise ReadError('Could not find the psi4 output file: ' + filename) with open(filename, 'r') as fd: txt = fd.read() if '!ASE Information\n' not in txt: raise Exception('The output file {} could not be read because ' 'the file does not contain the "!ASE Information"' ' lines inserted by this calculator. This likely' ' means the output file was not made using this ' 'ASE calculator or has since been modified and ' 'thus cannot be read.'.format(filename)) info = txt.split('!ASE Information\n')[1] info = info.split('!')[0] saved_dict = json.loads(info) # use io read to recode atoms with StringIO(str(saved_dict['atoms'])) as g: self.atoms = io.read(g, format='json') self.parameters = saved_dict['parameters'] self.results = saved_dict['results'] # convert forces to numpy array if 'forces' in self.results: self.results['forces'] = np.array(self.results['forces'])
def _read_positions(self, out): """Read the contents of a positions_abs block into the calculator's atoms object, setting both species and positions. Tries to strip out comment lines and is aware of angstom vs. bohr""" line = out.readline() # onetep assumes lengths are in atomic units by default conv_fac = Bohr if 'ang' in line: line = out.readline() conv_fac = 1.0 elif 'bohr' in line: line = out.readline() symbols = [] positions = [] while '%endblock' not in line.lower(): line = line.strip() if line[0] != '#': atom, suffix = line.split(None, 1) pos = suffix.split(None, 3)[0:3] try: pos = [conv_fac * float(p) for p in pos] except ValueError: raise ReadError('Malformed position line "%s"', line) symbols.append(atom) positions.append(pos) line = out.readline() self.atoms.set_chemical_symbols(symbols) self.atoms.set_positions(positions)
def read_results(self): FileIOCalculator.read_results(self) onetep_file = self.label + '.out' warnings = [] try: out = paropen(onetep_file, 'r') except IOError: raise ReadError('Could not open output file "%s"' % onetep_file) line = out.readline() while line: if '| Total' in line: self.results['energy'] = Hartree * float(line.split()[-2]) elif ('Element Atom Cartesian components (Eh/a)' in line): self._read_forces(out) elif ('Final Configuration' in line): self._read_geom_output(out) elif ('Integrated spin density' in line): self.results['magmom'] = self._read_magmom(line) elif ('Dipole Moment Calculation' in line): self.results['dipole'] = self._read_dipole(out) elif 'warn' in line.lower(): warnings.append(line) line = out.readline() if warnings: warn('WARNING: %s contains warnings' % onetep_file) for warning in warnings: warn(warning)
def read(self, label=None): """Read results from VASP output files. Files which are read: OUTCAR, CONTCAR and vasprun.xml Raises ReadError if they are not found""" if label is None: label = self.label Calculator.read(self, label) # If we restart, self.parameters isn't initialized if self.parameters is None: self.parameters = self.get_default_parameters() # Check for existence of the necessary output files for f in ['OUTCAR', 'CONTCAR', 'vasprun.xml']: filename = self._indir(f) if not os.path.isfile(filename): raise ReadError( 'VASP outputfile {} was not found'.format(filename)) # Build sorting and resorting lists self.read_sort() # Read atoms self.atoms = self.read_atoms() # Read parameters self.read_incar(filename=self._indir('INCAR')) self.read_kpoints(filename=self._indir('KPOINTS')) self.read_potcar(filename=self._indir('POTCAR')) # Read the results from the calculation self.read_results()
def parse_xray(filename): #filename = self.label + '/deMon.xry' if op.isfile(filename): with open(filename, 'r') as f: lines = f.readlines() mode = lines[0].split()[0] ntrans = int(lines[0].split()[1]) E_trans = [] osc_strength = [] trans_dip = [] for i in range(1, ntrans + 1): tokens = lines[i].split() E_trans.append(float(tokens[0])) osc_strength.append(float(tokens[1].replace('D', 'e'))) dip1 = float(tokens[3].replace('D', 'e')) dip2 = float(tokens[4].replace('D', 'e')) dip3 = float(tokens[5].replace('D', 'e')) trans_dip.append([dip1, dip2, dip3]) return mode, ntrans, np.array(E_trans) * Hartree, np.array( osc_strength), np.array(trans_dip) else: raise ReadError('The file {0} does not exist'.format(filename))
def read(self, filename): """Read structural parameters from file .XV file Read other results from other files filename : siesta.XV """ fname = self.getpath(filename) if not os.path.exists(fname): raise ReadError("The restart file '%s' does not exist" % fname) self.atoms = xv_to_atoms(fname) self.read_results()
def read(self, restart_path): """Read parameters from directory restart_path.""" self.set_label(restart_path) if not op.exists(restart_path + '/deMon.inp'): raise ReadError('The restart_path file {0} does not exist'.format( restart_path)) self.atoms = self.deMon_inp_to_atoms(restart_path + '/deMon.inp') self.read_results()
def read(self, label): """Read results from ABINIT's text-output file.""" FileIOCalculator.read(self, label) filename = self.label + '.txt' if not os.path.isfile(filename): raise ReadError('ABINIT output file ' + filename + ' is missing.') self.atoms = read_abinit(self.label + '.in') self.parameters = Parameters.read(self.label + '.ase') self.initialize(self.atoms) self.read_results()
def _read_species_pot(self, out): """ Read in pseudopotential information from a onetep output file""" line = out.readline().strip() pots = [] while '%endblock' not in line.lower() and len(line) > 0: atom, suffix = line.split(None, 1) filename = suffix.split('#', 1)[0].strip() filename = filename.replace('"', '') # take out quotes filename = filename.replace("'", '') pots.append((atom, filename,)) line = out.readline().strip() if len(line) == 0: raise ReadError('End of file while reading potential block') self.set_pseudos(pots)
def _read_species_solver(self, out, cond=False): """ Read in pseudopotential information from a onetep output file""" line = out.readline().strip() solvers = [] while '%endblock' not in line.lower() and len(line) > 0: atom, suffix = line.split(None, 1) solver_str = suffix.split('#', 1)[0].strip() solvers.append((atom, solver_str)) line = out.readline().strip() if len(line) == 0: raise ReadError('End of file while reading solver block') if not cond: self.set_solvers(solvers) else: self.set_solvers_cond(solvers)
def read(self, label): FileIOCalculator.read(self, label) totenergy = os.path.join(self.directory, 'TOTENERGY.OUT') eigval = os.path.join(self.directory, 'EIGVAL.OUT') kpoints = os.path.join(self.directory, 'KPOINTS.OUT') for filename in [totenergy, eigval, kpoints, self.out]: if not os.path.isfile(filename): raise ReadError('ELK output file ' + filename + ' is missing.') # read state from elk.in because *.OUT do not provide enough digits! self.atoms = read_elk(os.path.join(self.directory, 'elk.in')) self.parameters = Parameters.read( os.path.join(self.directory, 'parameters.ase')) self.initialize(self.atoms) self.read_results()
def read(self, restart_path): """Read parameters from directory restart_path.""" self.set_label(restart_path) if not op.exists(restart_path + '/deMon.inp'): raise ReadError('The restart_path file {0} does not exist'.format( restart_path)) if op.exists(restart_path + '/deMon_parameters.pckl'): with open(restart_path + '/deMon_parameters.pckl') as fd: parameters = pickle.load(fd, 'r') self.parameters = parameters self.atoms = self.deMon_inp_to_atoms(restart_path + '/deMon.inp') self.read_results()
def read(self, label): """Read psi4 outputs made from this ASE calculator """ filename = label + '.dat' if not os.path.isfile(filename): raise ReadError('Could not find the psi4 output file: ' + filename) f = open(filename, 'r') txt = f.read() f.close() if '!ASE Information\n' not in txt: raise Exception('the output file must be made by the ase psi4 ' 'interface to be read by it') info = txt.split('!ASE Information\n')[1] saved_dict = pickle.loads(codecs.decode(info.encode(), "base64")) self.atoms = saved_dict['atoms'] self.parameters = saved_dict['parameters'] self.results = saved_dict['results']
def read_energy(self): """Read energy from deMon.ase output file.""" epath = pl.Path(self.label) if not (epath / 'deMon.ase').exists(): raise ReadError('The deMonNano output file for ASE {0} does not exist' .format(epath)) filename = self.label + '/deMon.ase' if op.isfile(filename): with open(filename, 'r') as fd: lines = fd.readlines() for i in range(len(lines)): if lines[i].startswith(' DFTB total energy [Hartree]'): self.results['energy'] = float(lines[i+1])*Hartree break
def _read_positions(self, out): """Read the contents of a positions_abs block into the calculator's atoms object, setting both species and positions. Tries to strip out comment lines and is aware of angstom vs. bohr""" line = out.readline() # onetep assumes lengths are in atomic units by default conv_fac = Bohr if 'ang' in line: line = out.readline() conv_fac = 1.0 elif 'bohr' in line: line = out.readline() symbols = [] positions = [] while '%endblock' not in line.lower(): line = line.strip() if line[0] != '#': atom, suffix = line.split(None, 1) pos = suffix.split(None, 3)[0:3] try: pos = [conv_fac * float(p) for p in pos] except ValueError: raise ReadError('Malformed position line "%s"', line) symbols.append(atom) positions.append(pos) line = out.readline() tags = deepcopy(symbols) for j in range(len(symbols)): symbols[j] = ''.join(i for i in symbols[j] if not i.isdigit()) for j in range(len(tags)): tags[j] = ''.join(i for i in tags[j] if not i.isalpha()) if tags[j]=='': tags[j]='0' tags[j] = int(tags[j]) if len(self.atoms)!=len(symbols): self.atoms = Atoms(symbols=symbols,positions=positions) self.atoms.set_chemical_symbols(symbols) self.atoms.set_tags(tags) self.atoms.set_positions(positions)
def read_results(self): filename = self.label + '.txt' text = open(filename).read().lower() for line in iter(text.split('\n')): if line.rfind('error') > -1 or line.rfind( 'was not enough scf cycles to converge') > -1: raise ReadError(line) if line.rfind('natom ') > -1: natoms = int(line.split()[-1]) lines = iter(text.split('\n')) # Stress: # Printed in the output in the following format [Hartree/Bohr^3]: # sigma(1 1)= 4.02063464E-04 sigma(3 2)= 0.00000000E+00 # sigma(2 2)= 4.02063464E-04 sigma(3 1)= 0.00000000E+00 # sigma(3 3)= 4.02063464E-04 sigma(2 1)= 0.00000000E+00 for line in lines: if line.rfind( 'cartesian components of stress tensor (hartree/bohr^3)' ) > -1: stress = np.empty(6) for i in range(3): entries = next(lines).split() stress[i] = float(entries[2]) stress[i + 3] = float(entries[5]) self.results['stress'] = stress * Hartree / Bohr**3 break else: raise RuntimeError # Energy [Hartree]: # Warning: Etotal could mean both electronic energy and free energy! etotal = None efree = None if 'PAW method is used'.lower( ) in text: # read DC energy according to M. Torrent for line in iter(text.split('\n')): if line.rfind('>>>>> internal e=') > -1: etotal = float( line.split('=')[-1]) * Hartree # second occurrence! for line in iter(text.split('\n')): if line.rfind('>>>> etotal (dc)=') > -1: efree = float(line.split('=')[-1]) * Hartree else: for line in iter(text.split('\n')): if line.rfind('>>>>> internal e=') > -1: etotal = float( line.split('=')[-1]) * Hartree # first occurrence! break for line in iter(text.split('\n')): if line.rfind('>>>>>>>>> etotal=') > -1: efree = float(line.split('=')[-1]) * Hartree if efree is None: raise RuntimeError('Total energy not found') if etotal is None: etotal = efree # Energy extrapolated to zero Kelvin: self.results['energy'] = (etotal + efree) / 2 self.results['free_energy'] = efree # Forces: for line in lines: if line.rfind('cartesian forces (ev/angstrom) at end:') > -1: forces = [] for i in range(natoms): forces.append( np.array([float(f) for f in next(lines).split()[1:]])) self.results['forces'] = np.array(forces) break else: raise RuntimeError # self.width = self.read_electronic_temperature() self.nband = self.read_number_of_bands() self.niter = self.read_number_of_iterations() self.nelect = self.read_number_of_electrons() self.results['magmom'] = self.read_magnetic_moment()
def read(self, filename): """Read parameters from file.""" if not os.path.exists(filename): raise ReadError("The restart file '%s' does not exist" % filename) self.atoms = xv_to_atoms(filename) self.read_results()