Esempio n. 1
0
    def read_results(self):
        FileIOCalculator.read(self, self.label)
        if not os.path.isfile(self.label + '.got'):
            raise ReadError

        with open(self.label + '.got') as f:
            lines = f.readlines()

        cycles = -1
        self.optimized = None
        for i, line in enumerate(lines):
            m = re.match(r'\s*Total lattice energy\s*=\s*(\S+)\s*eV', line)
            if m:
                energy = float(m.group(1))
                self.results['energy'] = energy
                self.results['free_energy'] = energy

            elif line.find('Optimisation achieved') != -1:
                self.optimized = True

            elif line.find('Final Gnorm') != -1:
                self.Gnorm = float(line.split()[-1])

            elif line.find('Cycle:') != -1:
                cycles += 1

            elif line.find('Final Cartesian derivatives') != -1:
                s = i + 5
                forces = []
                while(True):
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    if lines[s].find(" s ") != -1:
                        continue
                    g = lines[s].split()[3:6]
                    G = [-float(x) * eV / Ang for x in g]
                    forces.append(G)
                forces = np.array(forces)
                self.results['forces'] = forces

            elif line.find('Final cartesian coordinates of atoms') != -1:
                s = i + 5
                positions = []
                while True:
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    if lines[s].find(" s ") != -1:
                        continue
                    xyz = lines[s].split()[3:6]
                    XYZ = [float(x) * Ang for x in xyz]
                    positions.append(XYZ)
                positions = np.array(positions)
                self.atoms.set_positions(positions)

        self.steps = cycles
Esempio n. 2
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        self.parameters = Parameters.read(self.label + '.ase')
        self.atoms = read_gamess_us_input(self.label + '.inp')

        self.read_results()
Esempio n. 3
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        self.parameters = Parameters.read(self.label + '.ase')
        self.atoms = read_orca_input(self.label + '.inp')

        self.read_results()
Esempio n. 4
0
    def read_results(self):
        """Read the results, such as energy, forces, eigenvalues, etc.
        """
        FileIOCalculator.read(self, self.label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        with open(self.label + '.out') as f:
            lines = f.readlines()

        for i, line in enumerate(lines):
            if line.find('TOTAL ENERGY') != -1:
                self.results['energy'] = float(line.split()[3])
            elif line.find('FINAL HEAT OF FORMATION') != -1:
                self.final_hof = float(line.split()[5]) * kcal / mol
            elif line.find('NO. OF FILLED LEVELS') != -1:
                self.nspins = 1
                self.no_occ_levels = int(line.split()[-1])
            elif line.find('NO. OF ALPHA ELECTRON') != -1:
                self.nspins = 2
                self.no_alpha_electrons = int(line.split()[-1])
                self.no_beta_electrons = int(lines[i + 1].split()[-1])
                self.results['magmom'] = abs(self.no_alpha_electrons -
                                             self.no_beta_electrons)
            elif line.find('FINAL  POINT  AND  DERIVATIVES') != -1:
                forces = [
                    -float(line.split()[6])
                    for line in lines[i + 3:i + 3 + 3 * len(self.atoms)]
                ]
                self.results['forces'] = np.array(forces).reshape(
                    (-1, 3)) * kcal / mol
            elif line.find('EIGENVALUES') != -1:
                if line.find('ALPHA') != -1:
                    j = i + 1
                    eigs_alpha = []
                    while not lines[j].isspace():
                        eigs_alpha += [float(eps) for eps in lines[j].split()]
                        j += 1
                elif line.find('BETA') != -1:
                    j = i + 1
                    eigs_beta = []
                    while not lines[j].isspace():
                        eigs_beta += [float(eps) for eps in lines[j].split()]
                        j += 1
                    eigs = np.array([eigs_alpha, eigs_beta]).reshape(2, 1, -1)
                    self.eigenvalues = eigs
                else:
                    eigs = []
                    j = i + 1
                    while not lines[j].isspace():
                        eigs += [float(e) for e in lines[j].split()]
                        j += 1
                    self.eigenvalues = np.array(eigs).reshape(1, 1, -1)
            elif line.find('DIPOLE   ') != -1:
                self.results['dipole'] = np.array(
                    lines[i + 3].split()[1:1 + 3], float) * Debye
Esempio n. 5
0
    def read_results(self):
        FileIOCalculator.read(self, self.label)
        if not os.path.isfile(self.label + '.got'):
            raise ReadError

        with open(self.label + '.got') as f:
            lines = f.readlines()

        cycles = -1
        self.optimized = None
        for i, line in enumerate(lines):
            if line.startswith("  Final energy") and 'eV' in line:
                energy = float(line.split()[-2])
                self.results['energy'] = energy
                self.results['free_energy'] = energy

            elif line.find('Optimisation achieved') != -1:
                self.optimized = True

            elif line.find('Final Gnorm') != -1:
                self.Gnorm = float(line.split()[-1])

            elif line.find('Cycle:') != -1:
                cycles += 1

            elif line.find('Final Cartesian derivatives') != -1:
                s = i + 5
                forces = []
                while (True):
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    if lines[s].find(" s ") != -1:
                        continue
                    g = lines[s].split()[3:6]
                    G = [-float(x) * eV / Ang for x in g]
                    forces.append(G)
                forces = np.array(forces)
                self.results['forces'] = forces

            elif line.find('Final cartesian coordinates of atoms') != -1:
                s = i + 5
                positions = []
                while True:
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    if lines[s].find(" s ") != -1:
                        continue
                    xyz = lines[s].split()[3:6]
                    XYZ = [float(x) * Ang for x in xyz]
                    positions.append(XYZ)
                positions = np.array(positions)
                self.atoms.set_positions(positions)

        self.steps = cycles
Esempio n. 6
0
 def read_results(self):
     """Read the results, such as energy, forces, eigenvalues, etc.
     """
     FileIOCalculator.read(self, self.label)
     if not os.path.isfile(self.label + '.out'):
         raise ReadError
     parser = MopacParser(self.label)
     self.parser = parser
     self.atoms = parser.atoms
     self.results = parser.get_properties()
Esempio n. 7
0
    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 '%block species' in clean_line:
                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_cond(out)
            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)
Esempio n. 8
0
    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 '%block species' in clean_line:
                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_cond(out)
            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)
Esempio n. 9
0
    def read_results(self):
        """Read the results, such as energy, forces, eigenvalues, etc.
        """
        FileIOCalculator.read(self, self.label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        with open(self.label + '.out') as f:
            lines = f.readlines()

        for i, line in enumerate(lines):
            if line.find('TOTAL ENERGY') != -1:
                self.results['energy'] = float(line.split()[3])
            elif line.find('FINAL HEAT OF FORMATION') != -1:
                self.final_hof = float(line.split()[5]) * kcal / mol
            elif line.find('NO. OF FILLED LEVELS') != -1:
                self.nspins = 1
                self.no_occ_levels = int(line.split()[-1])
            elif line.find('NO. OF ALPHA ELECTRON') != -1:
                self.nspins = 2
                self.no_alpha_electrons = int(line.split()[-1])
                self.no_beta_electrons = int(lines[i+1].split()[-1])
                self.results['magmom'] = abs(self.no_alpha_electrons -
                                             self.no_beta_electrons)
            elif line.find('FINAL  POINT  AND  DERIVATIVES') != -1:
                forces = [-float(line.split()[6])
                          for line in lines[i + 3:i + 3 + 3 * len(self.atoms)]]
                self.results['forces'] = np.array(
                    forces).reshape((-1, 3)) * kcal / mol
            elif line.find('EIGENVALUES') != -1:
                if line.find('ALPHA') != -1:
                    j = i + 1
                    eigs_alpha = []
                    while not lines[j].isspace():
                        eigs_alpha += [float(eps) for eps in lines[j].split()]
                        j += 1
                elif line.find('BETA') != -1:
                    j = i + 1
                    eigs_beta = []
                    while not lines[j].isspace():
                        eigs_beta += [float(eps) for eps in lines[j].split()]
                        j += 1
                    eigs = np.array([eigs_alpha, eigs_beta]).reshape(2, 1, -1)
                    self.eigenvalues = eigs
                else:
                    eigs = []
                    j = i + 1
                    while not lines[j].isspace():
                        eigs += [float(e) for e in lines[j].split()]
                        j += 1
                    self.eigenvalues = np.array(eigs).reshape(1, 1, -1)
            elif line.find('DIPOLE   ') != -1:
                self.results['dipole'] = np.array(
                    lines[i + 3].split()[1:1 + 3], float) * Debye
    def read(self, label):
        # Set the label
        FileIOCalculator.read(self, label)

        # We can read the output file from cp2k
        outfile = open("%s.out" % label, "r")
        outlines = [line.strip() for line in  outfile.readlines() ]
        outfile.close()



        unit_cell = np.zeros((3,3), dtype = np.float64)
        reading_atoms = False
        nat = 0
        atm_coords = []
        atm_type = []
        __start__ = 0
        for i, line in  enumerate(outlines):
            data_line = line.strip()

            if len(data_line) == 0:
                continue

            if data_line[0] == "CELL|" and data_line[1] == "Vector" :
                index = {"a" : 0, "b" : 1, "c" : 2}
                v_i = index[data_line[2]]
                unit_cell[v_i, 0] = float( data_line[4])
                unit_cell[v_i, 1] = float( data_line[5])
                unit_cell[v_i, 2] = float( data_line[6])
            
            if "ATOMIC COORDINATES" in line:
                reading_atoms = True
            
            if reading_atoms:
                if len(data_line) != 8:
                    reading_atoms = False
                    continue

                if data_line[0] == "Atom":
                    continue
                
                atm_type_conv = {"H": "H", "D": "H", "O":"O"} # Avoid deuterium
                nat += 1
                atm_coords.append( [float(data_line[3]), float(data_line[4]), float(data_line[5])])
                atm_type.append( atm_type_conv[data_line[2]])

        # Generate the ASE ATOM structure
        self.atoms = Atoms(atm_type, atm_coords, cell=unit_cell)
        self.read_results()

        print ("Test results:")
        print ("energy:", self.results["energy"])
        print ("forces:", self.results["forces"])
        print ("stress:", self.results["stress"])
Esempio n. 11
0
    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

        self.atoms = read_abinit(self.label + '.in')
        self.parameters = Parameters.read(self.label + '.ase')

        self.initialize(self.atoms)
        self.read_results()
Esempio n. 12
0
    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()
Esempio n. 13
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        geometry = os.path.join(self.directory, 'geometry.in')
        control = os.path.join(self.directory, 'control.in')
                        
        for filename in [geometry, control, self.out]:
            if not os.path.isfile(filename):
                raise ReadError

        self.atoms = read_aims(geometry)
        self.parameters = Parameters.read(os.path.join(self.directory,
                                                       'parameters.ase'))
        self.read_results()
Esempio n. 14
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        geometry = self.label + '.car'
        output = self.label + '.outmol'
        force = self.label + '.grad'

        for filename in [force, output, geometry]:
            if not os.path.isfile(filename):
                raise ReadError

        self.atoms = read(geometry)
        self.parameters = Parameters.read(self.label + 'parameters.ase')
        self.read_results()
Esempio n. 15
0
    def read(self, label):
        """Used to read the results of a previous calculation if restarting"""
        FileIOCalculator.read(self, label)

        from ase.io.orca import read_orca_out
        filename = self.label

        if not os.path.isfile(filename + ".log"):
            raise ReadError

        self.atoms = read_orca_out(filename, quantity='atoms')
        self.parameters = Parameters.read(self.label + '.ase')
        self.read_results()
Esempio n. 16
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        geometry = self.label + '.car'
        output = self.label + '.outmol'
        force = self.label + '.grad'

        for filename in [force, output, geometry]:
            if not os.path.isfile(filename):
                raise ReadError

        self.atoms = read(geometry)
        self.parameters = Parameters.read(self.label + 'parameters.ase')
        self.read_results()
Esempio n. 17
0
    def read(self, label):
        """ Read results and input from a MyMD calculation.

        The FileIOCalculator API of ASE prescribes this method and states
        that it should read both input and output.
        """
        FileIOCalculator.read(self, label)

        self.read_input(label)

        # Here start reading the trajectories etc.
        self.state = Atoms(symbols, positions,
                           magmoms=self.parameters.pop('magmoms'))
        self.read_results()
Esempio n. 18
0
    def read(self, label):
        """Used to read the results of a previous calculation if restarting"""
        FileIOCalculator.read(self, label)

        from ase.io.gaussian import read_gaussian_out
        filename = self.label + '.log'

        if not os.path.isfile(filename):
            raise ReadError

        self.atoms = read_gaussian_out(filename, quantity='atoms')
        self.parameters = Parameters.read(self.label + '.ase')
        initial_magmoms = self.parameters.pop('initial_magmoms')
        self.atoms.set_initial_magnetic_moments(initial_magmoms)
        self.read_results()
Esempio n. 19
0
    def read(self, label):
        """Used to read the results of a previous calculation if restarting"""
        FileIOCalculator.read(self, label)

        from ase.io.gaussian import read_gaussian_out
        filename = self.label + '.log'

        if not os.path.isfile(filename):
            raise ReadError

        self.atoms = read_gaussian_out(filename, quantity='atoms')
        self.parameters = Parameters.read(self.label + '.ase')
        initial_magmoms = self.parameters.pop('initial_magmoms')
        self.atoms.set_initial_magnetic_moments(initial_magmoms)
        self.read_results()
Esempio n. 20
0
    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()
Esempio n. 21
0
    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()
Esempio n. 22
0
    def read(self, label=None):
        if label is None: label = self.label
        FileIOCalculator.read(self, label)
        geometry = os.path.join(self.directory, 'geometry.in')
        control = os.path.join(self.directory, 'control.in')

        for filename in [geometry, control, self.out]:
            if not os.path.isfile(filename):
                raise ReadError

        self.atoms, symmetry_block = read_aims(geometry, True)
        self.parameters = Parameters.read(
            os.path.join(self.directory, 'parameters.ase'))
        if symmetry_block:
            self.parameters["symmetry_block"] = symmetry_block
        self.read_results()
Esempio n. 23
0
File: elk.py Progetto: PHOTOX/fuase
    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

        # 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()
Esempio n. 24
0
    def read(self, label):
        # XXX label of restart file may not be the same as actual label!
        # This makes things rather tricky.  We first set the label to
        # that of the restart file and arbitrarily expect the remaining code
        # to rectify any consequent inconsistencies.
        self.set_label(label)

        FileIOCalculator.read(self, label)
        inp_path = self._getpath('inp')
        fd = open(inp_path)
        names, values = parse_input_file(fd)
        kwargs = purify(dict(zip(names, values)))

        self.atoms, kwargs = kwargs2atoms(kwargs)
        self.kwargs.update(kwargs)

        fd.close()
        self.read_results()
Esempio n. 25
0
    def read_results(self):
        FileIOCalculator.read(self, self.label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        with open(self.label + '.out') as f:
            lines = f.readlines()

        for i, line in enumerate(lines):
            if line.find('TOTAL ENERGY') != -1:
                self.results['energy'] = float(line.split()[3])
            elif line.find('FINAL  POINT  AND  DERIVATIVES') != -1:
                forces = [
                    -float(line.split()[6])
                    for line in lines[i + 3:i + 3 + 3 * len(self.atoms)]
                ]
                forces = np.array(forces).reshape((-1, 3)) * kcal / mol
                self.results['forces'] = forces
                break
Esempio n. 26
0
    def read(self, label):
        # XXX label of restart file may not be the same as actual label!
        # This makes things rather tricky.  We first set the label to
        # that of the restart file and arbitrarily expect the remaining code
        # to rectify any consequent inconsistencies.
        self.set_label(label)

        FileIOCalculator.read(self, label)
        inp_path = self._getpath('inp')
        fd = open(inp_path)
        kwargs = parse_input_file(fd)
        if self.octopus_keywords is not None:
            self.check_keywords_exist(kwargs)

        self.atoms, kwargs = kwargs2atoms(kwargs)
        self.kwargs.update(kwargs)

        fd.close()
        self.read_results()
Esempio n. 27
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        with open(self.label + '.inp') as fd:
            for line in fd:
                if line.startswith('geometry'):
                    break
            symbols = []
            positions = []
            for line in fd:
                if line.startswith('end'):
                    break
                words = line.split()
                symbols.append(words[0])
                positions.append([float(word) for word in words[1:]])

        self.parameters = Parameters.read(self.label + '.ase')
        self.read_results()
Esempio n. 28
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        if not os.path.isfile(self.label + ".out"):
            raise ReadError

        f = open(self.label + ".nw")
        for line in f:
            if line.startswith("geometry"):
                break
        symbols = []
        positions = []
        for line in f:
            if line.startswith("end"):
                break
            words = line.split()
            symbols.append(words[0])
            positions.append([float(word) for word in words[1:]])

        self.parameters = Parameters.read(self.label + ".ase")
        self.state = Atoms(symbols, positions, magmoms=self.parameters.pop("magmoms"))
        self.read_results()
Esempio n. 29
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        with open(self.label + '.out') as f:
            lines = f.readlines()

        self.parameters = Parameters(task='', method='')
        p = self.parameters
        parm_line = self.read_parameters_from_file(lines)
        for keyword in parm_line.split():
            if 'RELSCF' in keyword:
                p.relscf = float(keyword.split('=')[-1])
            elif keyword in self.methods:
                p.method = keyword
            else:
                p.task += keyword + ' '

        p.task.rstrip()
        self.read_results()
Esempio n. 30
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        f = open(self.label + '.nw')
        for line in f:
            if line.startswith('geometry'):
                break
        symbols = []
        positions = []
        for line in f:
            if line.startswith('end'):
                break
            words = line.split()
            symbols.append(words[0])
            positions.append([float(word) for word in words[1:]])

        self.parameters = Parameters.read(self.label + '.ase')
        self.atoms = Atoms(symbols, positions,
                           magmoms=self.parameters.pop('initial_magmoms'))
        self.read_results()
Esempio n. 31
0
 def read(self, label):
     """Read results from ABINIT's text-output file."""
     # XXX I think we should redo the concept of 'restarting'.
     # It makes sense to load a previous calculation as
     #
     #  * static, calculator-independent results
     #  * an actual calculator capable of calculating
     #
     # Either of which is simpler than our current mechanism which
     # implies both at the same time.  Moreover, we don't need
     # something like calc.read(label).
     #
     # What we need for these two purposes is
     #
     #  * calc = MyCalculator.read(basefile)
     #      (or maybe it should return Atoms with calc attached)
     #  * results = read_results(basefile, format='abinit')
     #
     # where basefile determines the file tree.
     FileIOCalculator.read(self, label)
     self.atoms, self.parameters = io.read_ase_and_abinit_inputs(self.label)
     self.results = io.read_results(self.label, self._output_filename())
Esempio n. 32
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        with open(self.label + '.out') as f:
            lines = f.readlines()

        self.parameters = Parameters(task='', method='')
        p = self.parameters
        parm_line = self.read_parameters_from_file(lines)
        for keyword in parm_line.split():
            if 'RELSCF' in keyword:
                p.relscf = float(keyword.split('=')[-1])
            elif keyword in self.methods:
                p.method = keyword
            else:
                p.task += keyword + ' '

        p.task.rstrip()
        self.atoms = self.read_atoms_from_file(lines)
        self.read_results()
Esempio n. 33
0
    def read(self, label):
        FileIOCalculator.read(self, label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        f = open(self.label + '.nw')
        for line in f:
            if line.startswith('geometry'):
                break
        symbols = []
        positions = []
        for line in f:
            if line.startswith('end'):
                break
            words = line.split()
            symbols.append(words[0])
            positions.append([float(word) for word in words[1:]])

        self.parameters = Parameters.read(self.label + '.ase')
        self.atoms = Atoms(symbols, positions,
                           magmoms=self.parameters.pop('initial_magmoms'))
        self.read_results()
Esempio n. 34
0
    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
        FileIOCalculator.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 file in ['OUTCAR', 'CONTCAR', 'vasprun.xml']:
            filename = os.path.join(self.directory, file)
            if not os.path.isfile(filename):
                raise ReadError(
                    'VASP outputfile {} was not found'.format(filename))

        # Read atoms
        self.atoms = self.read_atoms()

        # Build sorting and resorting lists
        self.read_sort()

        # Read parameters
        olddir = os.getcwd()
        try:
            os.chdir(self.directory)
            self.read_incar()
            self.read_kpoints()
            self.read_potcar()
        finally:
            os.chdir(olddir)

        # Read the results from the calculation
        self.read_results()
Esempio n. 35
0
    def read_results(self):
        """Read the results, such as energy, forces, eigenvalues, etc.
        """
        FileIOCalculator.read(self, self.label)
        if not os.path.isfile(self.label + '.out'):
            raise ReadError

        with open(self.label + '.out') as f:
            lines = f.readlines()

        for i, line in enumerate(lines):
            if line.find('TOTAL ENERGY') != -1:
                self.results['energy'] = float(line.split()[3])
            elif line.find('FINAL HEAT OF FORMATION') != -1:
                self.final_hof = float(line.split()[5]) * kcal / mol
            elif line.find('BOND ORDERS AND VALENCIES') != -1:
                bo = []
                for k in range(math.ceil(len(self.atoms) / 6)):
                    if k == 0: kf = 0
                    else: kf = ((len(self.atoms) + 1) * k - 3 * k * k)
                    for j in range(min(6, len(self.atoms) - 6 * k - 1)):
                        bo.append([
                            line.split()[2 + j]
                            for line in lines[i + j + 6 + kf + 6 * k:i + 5 +
                                              len(self.atoms) + kf]
                        ])
                self.bond_order = [item for sublist in bo for item in sublist]
            elif line.find('NO. OF FILLED LEVELS') != -1:
                self.nspins = 1
                self.no_occ_levels = int(line.split()[-1])
            elif line.find('NO. OF ALPHA ELECTRON') != -1:
                self.nspins = 2
                self.no_alpha_electrons = int(line.split()[-1])
                self.no_beta_electrons = int(lines[i + 1].split()[-1])
                self.results['magmom'] = abs(self.no_alpha_electrons -
                                             self.no_beta_electrons)
            elif line.find('FINAL  POINT  AND  DERIVATIVES') != -1:
                nf = [
                    len(line.split()) == 8
                    for line in lines[i + 3:i + 3 + 3 * len(self.atoms)]
                ]
                if not False in nf:
                    self.forces_permission = True
                    forces = [
                        -float(line.split()[6])
                        for line in lines[i + 3:i + 3 + 3 * len(self.atoms)]
                    ]
                    self.results['forces'] = np.array(forces).reshape(
                        (-1, 3)) * kcal / mol
                else:
                    self.forces_permission = False
                    self.results['forces'] = np.array(
                        np.zeros(3 * len(self.atoms))).reshape((-1, 3))
            elif line.find('EIGENVALUES') != -1:
                if line.find('ALPHA') != -1:
                    j = i + 1
                    eigs_alpha = []
                    while not lines[j].isspace():
                        eigs_alpha += [float(eps) for eps in lines[j].split()]
                        j += 1
                elif line.find('BETA') != -1:
                    j = i + 1
                    eigs_beta = []
                    while not lines[j].isspace():
                        eigs_beta += [float(eps) for eps in lines[j].split()]
                        j += 1
                    eigs = np.array([eigs_alpha, eigs_beta]).reshape(2, 1, -1)
                    self.eigenvalues = eigs
                else:
                    eigs = []
                    j = i + 1
                    while not lines[j].isspace():
                        eigs += [float(e) for e in lines[j].split()]
                        j += 1
                    self.eigenvalues = np.array(eigs).reshape(1, 1, -1)
            elif line.find('DIPOLE   ') != -1:
                self.results['dipole'] = np.array(
                    lines[i + 3].split()[1:1 + 3], float) * Debye
Esempio n. 36
0
 def read(self, label):
     """Used to read the results of a previous calculation if restarting"""
     FileIOCalculator.read(self, label)
Esempio n. 37
0
    def read_results(self):
        FileIOCalculator.read(self, self.label)
        if not os.path.isfile(self.label + '.got'):
            raise ReadError

        with open(self.label + '.got') as f:
            lines = f.readlines()

        cycles = -1
        self.optimized = None
        for i, line in enumerate(lines):
            m = re.match(r'\s*Total lattice energy\s*=\s*(\S+)\s*eV', line)
            if m:
                energy = float(m.group(1))
                self.results['energy'] = energy
                self.results['free_energy'] = energy

            elif line.find('Optimisation achieved') != -1:
                self.optimized = True

            elif line.find('Final Gnorm') != -1:
                self.Gnorm = float(line.split()[-1])

            elif line.find('Cycle:') != -1:
                cycles += 1

            elif line.find('Final Cartesian derivatives') != -1:
                s = i + 5
                forces = []
                while (True):
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    if lines[s].find(" s ") != -1:
                        continue
                    g = lines[s].split()[3:6]
                    G = [-float(x) * eV / Ang for x in g]
                    forces.append(G)
                forces = np.array(forces)
                self.results['forces'] = forces

            elif line.find('Final internal derivatives') != -1:
                s = i + 5
                forces = []
                while (True):
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    g = lines[s].split()[3:6]

                    # Uncomment the section below to separate the numbers when there is no space between them, in the case of long numbers. This prevents the code to break if numbers are too big.
                    '''for t in range(3-len(g)):
                        g.append(' ')
                    for j in range(2):
                        min_index=[i+1 for i,e in enumerate(g[j][1:]) if e == '-']
                        if j==0 and len(min_index) != 0:
                            if len(min_index)==1:
                                g[2]=g[1]
                                g[1]=g[0][min_index[0]:]
                                g[0]=g[0][:min_index[0]]
                            else:
                                g[2]=g[0][min_index[1]:]
                                g[1]=g[0][min_index[0]:min_index[1]]
                                g[0]=g[0][:min_index[0]]
                                break
                        if j==1 and len(min_index) != 0:
                            g[2]=g[1][min_index[0]:]
                            g[1]=g[1][:min_index[0]]'''

                    G = [-float(x) * eV / Ang for x in g]
                    forces.append(G)
                forces = np.array(forces)
                self.results['forces'] = forces

            elif line.find('Final cartesian coordinates of atoms') != -1:
                s = i + 5
                positions = []
                while True:
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    if lines[s].find(" s ") != -1:
                        continue
                    xyz = lines[s].split()[3:6]
                    XYZ = [float(x) * Ang for x in xyz]
                    positions.append(XYZ)
                positions = np.array(positions)
                self.atoms.set_positions(positions)

            elif line.find('Final stress tensor components') != -1:
                res = [0., 0., 0., 0., 0., 0.]
                for j in range(3):
                    var = lines[i + j + 3].split()[1]
                    res[j] = float(var)
                    var = lines[i + j + 3].split()[3]
                    res[j + 3] = float(var)
                stress = np.array(res)
                self.results['stress'] = stress

            elif line.find('Final Cartesian lattice vectors') != -1:
                lattice_vectors = np.zeros((3, 3))
                s = i + 2
                for j in range(s, s + 3):
                    temp = lines[j].split()
                    for k in range(3):
                        lattice_vectors[j - s][k] = float(temp[k])
                self.atoms.set_cell(lattice_vectors)
                if self.fractional_coordinates is not None:
                    self.fractional_coordinates = np.array(
                        self.fractional_coordinates)
                    self.atoms.set_scaled_positions(
                        self.fractional_coordinates)

            elif line.find('Final fractional coordinates of atoms') != -1:
                s = i + 5
                scaled_positions = []
                while True:
                    s = s + 1
                    if lines[s].find("------------") != -1:
                        break
                    if lines[s].find(" s ") != -1:
                        continue
                    xyz = lines[s].split()[3:6]
                    XYZ = [float(x) for x in xyz]
                    scaled_positions.append(XYZ)
                self.fractional_coordinates = scaled_positions

        self.steps = cycles
Esempio n. 38
0
 def read(self, label):
     """Used to read the results of a previous calculation if restarting"""
     FileIOCalculator.read(self, label)
Esempio n. 39
0
File: octopus.py Progetto: jboes/ase
 def read(self, label):
     FileIOCalculator.read(self, label)
     self.read_results()