Exemple #1
0
Fichier : res.py Projet : jboes/ase
    def from_string(data):
        """
        Reads a Res from a string.

        Args:
            data (str): string containing Res data.

        Returns:
            Res object.
        """
        abc = []
        ang = []
        sp = []
        coords = []
        info = dict()
        coord_patt = re.compile("""(\w+)\s+
                                   ([0-9]+)\s+
                                   ([0-9\-\.]+)\s+
                                   ([0-9\-\.]+)\s+
                                   ([0-9\-\.]+)\s+
                                   ([0-9\-\.]+)""", re.VERBOSE)
        lines = data.splitlines()
        line_no = 0
        while line_no < len(lines):
            line = lines[line_no]
            tokens = line.split()
            if tokens:
                if tokens[0] == 'TITL':
                    try:
                        info = Res.parse_title(line)
                    except (ValueError, IndexError):
                        info = dict()
                elif tokens[0] == 'CELL' and len(tokens) == 8:
                    abc = [float(tok) for tok in tokens[2:5]]
                    ang = [float(tok) for tok in tokens[5:8]]
                elif tokens[0] == 'SFAC':
                    for atom_line in lines[line_no:]:
                        if line.strip() == 'END':
                            break
                        else:
                            match = coord_patt.search(atom_line)
                            if match:
                                sp.append(match.group(1))  # 1-indexed
                                cs = match.groups()[2:5]
                                coords.append([float(c) for c in cs ])
                        line_no += 1  # Make sure the global is updated
            line_no += 1

        return Res(Atoms(symbols=sp,
                         positions=coords,
                         cell=cellpar_to_cell(list(abc) + list(ang)),
                         pbc=True, info=info),
                   info.get('name'),
                   info.get('pressure'),
                   info.get('energy'),
                   info.get('spacegroup'),
                   info.get('times_found'))
Exemple #2
0
Fichier : eon.py Projet : jboes/ase
def read_reactant_con(fileobj):
    """Reads an EON reactant.con file.  If *fileobj* is the name of a
    "states" directory created by EON, all the structures will be read."""
    if isinstance(fileobj, str):
        if os.path.isdir(fileobj):
            return read_states(fileobj)
        else:
            f = open(fileobj)
    else:
        f = fileobj

    comment = f.readline().strip()
    f.readline()  # 0.0000 TIME  (??)
    cell_lengths = f.readline().split()
    cell_angles = f.readline().split()
    # Different order of angles in EON.
    cell_angles = [cell_angles[2], cell_angles[1], cell_angles[0]]
    cellpar = [float(x) for x in cell_lengths + cell_angles]
    f.readline()  # 0 0     (??)
    f.readline()  # 0 0 0   (??)
    ntypes = int(f.readline())  # number of atom types
    natoms = [int(n) for n in f.readline().split()]
    atommasses = [float(m) for m in f.readline().split()]

    symbols = []
    coords = []
    masses = []
    fixed = []
    for n in range(ntypes):
        symbol = f.readline().strip()
        symbols.extend([symbol] * natoms[n])
        masses.extend([atommasses[n]] * natoms[n])
        f.readline()  # Coordinates of Component n
        for i in range(natoms[n]):
            row = f.readline().split()
            coords.append([float(x) for x in row[:3]])
            fixed.append(bool(int(row[3])))

    if isinstance(fileobj, str):
        f.close()

    atoms = Atoms(
        symbols=symbols,
        positions=coords,
        masses=masses,
        cell=cellpar_to_cell(cellpar),
        constraint=FixAtoms(mask=fixed),
        info=dict(comment=comment),
    )

    return atoms
Exemple #3
0
def read_reactant_con(fileobj):
    """Reads an EON reactant.con file.  If *fileobj* is the name of a
    "states" directory created by EON, all the structures will be read."""
    if isinstance(fileobj, str):
        if (os.path.isdir(fileobj)):
            return read_states(fileobj)
        else:
            f = open(fileobj)
    else:
        f = fileobj

    comment = f.readline().strip()
    f.readline()  # 0.0000 TIME  (??)
    cell_lengths = f.readline().split()
    cell_angles = f.readline().split()
    # Different order of angles in EON.
    cell_angles = [cell_angles[2], cell_angles[1], cell_angles[0]]
    cellpar = [float(x) for x in cell_lengths + cell_angles]
    f.readline()  # 0 0     (??)
    f.readline()  # 0 0 0   (??)
    ntypes = int(f.readline())  # number of atom types
    natoms = [int(n) for n in f.readline().split()]
    atommasses = [float(m) for m in f.readline().split()]

    symbols = []
    coords = []
    masses = []
    fixed = []
    for n in range(ntypes):
        symbol = f.readline().strip()
        symbols.extend([symbol] * natoms[n])
        masses.extend([atommasses[n]] * natoms[n])
        f.readline()  # Coordinates of Component n
        for i in range(natoms[n]):
            row = f.readline().split()
            coords.append([float(x) for x in row[:3]])
            fixed.append(bool(int(row[3])))

    if isinstance(fileobj, str):
        f.close()

    atoms = Atoms(symbols=symbols,
                  positions=coords,
                  masses=masses,
                  cell=cellpar_to_cell(cellpar),
                  constraint=FixAtoms(mask=fixed),
                  info=dict(comment=comment))

    return atoms
Exemple #4
0
def read_pdb(fileobj, index=-1):
    """Read PDB files.

    The format is assumed to follow the description given in
    http://www.wwpdb.org/documentation/format32/sect8.html and
    http://www.wwpdb.org/documentation/format32/sect9.html."""
    if isinstance(fileobj, str):
        fileobj = open(fileobj)

    images = []
    orig = np.identity(3)
    trans = np.zeros(3)
    atoms = Atoms()
    for line in fileobj.readlines():
        if line.startswith('CRYST1'):
            cellpar = [float(word) for word in line[6:54].split()]
            atoms.set_cell(cellpar_to_cell(cellpar))
        for c in range(3):
            if line.startswith('ORIGX' + '123'[c]):
                pars = [float(word) for word in line[10:55].split()]
                orig[c] = pars[:3]
                trans[c] = pars[3]
            
        if line.startswith('ATOM') or line.startswith('HETATM'):
            try:
                # Atom name is arbitrary and does not necessarily contain the element symbol.
                # The specification requires the element symbol to be in columns 77+78.
                symbol = line[76:78].strip().lower().capitalize()
                words = line[30:55].split()
                position = np.array([float(words[0]), 
                                     float(words[1]),
                                     float(words[2])])
                position = np.dot(orig, position) + trans
                atoms.append(Atom(symbol, position))
            except:
                pass
        if line.startswith('ENDMDL'):
            images.append(atoms)
            atoms = Atoms()
    if len(images) == 0:
        images.append(atoms)
    return images[index]
def get_energy(x):
    global iteration
    iteration += 1

    cellpar = [lcfix, x[0], lcfix, 90, 90, 90]
    ucell = cellpar_to_cell(cellpar)

    # setting up the atomic configuration
    atoms = io.read('init.traj')
    #Set the unit cell
    atoms.set_cell(ucell, scale_atoms=True)

    atoms.write('input.traj')

    calc = espresso(pw=pw_cutoff,
                    dw=dw_cutoff,
                    xc=xc,
                    kpts=kpts,
                    nbands=nbands,
                    spinpol=spinpol,
                    dipole=dipole,
                    convergence=convergence,
                    output=output,
                    outdir='calcdir' + str(np.round(x[0], 5)))

    atoms.set_calculator(calc)
    trajfile = 'out' + str(np.round(x[0], 5)) + '.traj'
    logfile = 'out' + str(np.round(x[0], 5)) + '.log'
    dyn = BFGS(atoms, logfile=logfile, trajectory=trajfile)
    dyn.run(fmax=0.01)
    energy = atoms.get_potential_energy()
    print('%20.8f%20.8f' % (x[0], energy))
    f = open('out' + str(np.round(x[0], 5)) + '.energy', 'w')
    f.write(repr(x) + ' ' + str(energy))
    f.close()
    calc.stop()
    del calc
    return energy
    def __getitem__(self, i=-1):
        self._open()

        if isinstance(i, slice):
            return [self[j] for j in range(*i.indices(self._len()))]

        N = self._len()
        if 0 <= i < N:
            # Non-periodic boundaries have cell_length == 0.0
            cell_lengths = \
                np.array(self.nc.variables[self._cell_lengths_var][i][:])
            pbc = np.abs(cell_lengths > 1e-6)

            # Do we have a cell origin?
            if self._has_variable(self._cell_origin_var):
                origin = np.array(
                    self.nc.variables[self._cell_origin_var][i][:])
            else:
                origin = np.zeros([3], dtype=float)

            # Do we have an index variable?
            if self._has_variable(self.index_var):
                index = np.array(self.nc.variables[self.index_var][i][:]) + \
                    self.index_offset
            else:
                index = np.arange(self.n_atoms)

            # Read element numbers
            self.numbers = self._get_data(self._numbers_var, i, exc=False)
            if self.numbers is None:
                self.numbers = np.ones(self.n_atoms, dtype=int)
            else:
                self.numbers = np.array(self.numbers[index])
            if self.types_to_numbers is not None:
                self.numbers = self.types_to_numbers[self.numbers]
            self.masses = atomic_masses[self.numbers]

            # Read positions
            positions = np.array(self._get_data(self._positions_var, i)[index])

            # Determine cell size for non-periodic directions
            for dim in np.arange(3)[np.logical_not(pbc)]:
                origin[dim] = positions[:, dim].min()
                cell_lengths[dim] = positions[:, dim].max() - origin[dim]

            # Construct cell shape from cell lengths and angles
            cell = cellpar_to_cell(
                list(cell_lengths) +
                list(self.nc.variables[self._cell_angles_var][i])
            )

            # Compute momenta from velocities (if present)
            momenta = self._get_data(self._velocities_var, i, exc=False)
            if momenta is not None:
                momenta = momenta[index] * self.masses.reshape(-1, 1)

            # Fill info dict with additional data found in the NetCDF file
            info = {}
            for name in self.extra_per_frame_atts:
                info[name] = np.array(self.nc.variables[name][i])

            # Create atoms object
            atoms = ase.Atoms(
                positions=positions - origin.reshape(1, -1),
                numbers=self.numbers,
                cell=cell,
                momenta=momenta,
                masses=self.masses,
                pbc=pbc,
                info=info
            )

            # Attach additional arrays found in the NetCDF file
            for name in self.extra_per_frame_vars:
                atoms.set_array(name, self.nc.variables[name][i][index])
            for name in self.extra_per_file_vars:
                atoms.set_array(name, self.nc.variables[name][:])
            self._close()
            return atoms

        i = N + i
        if i < 0 or i >= N:
            self._close()
            raise IndexError('Trajectory index out of range.')
        return self[i]
Exemple #7
0
    def __getitem__(self, i=-1):
        self._open()

        if isinstance(i, slice):
            return [self[j] for j in range(*i.indices(self._len()))]

        N = self._len()
        if 0 <= i < N:
            # Non-periodic boundaries have cell_length == 0.0
            cell_lengths = \
                np.array(self.nc.variables[self._cell_lengths_var][i][:])
            pbc = np.abs(cell_lengths > 1e-6)

            # Do we have a cell origin?
            if self._has_variable(self._cell_origin_var):
                origin = np.array(
                    self.nc.variables[self._cell_origin_var][i][:])
            else:
                origin = np.zeros([3], dtype=float)

            # Do we have an index variable?
            if self._has_variable(self.index_var):
                index = np.array(self.nc.variables[self.index_var][i][:]) +\
                    self.index_offset
            else:
                index = np.arange(self.n_atoms)

            # Read positions
            positions_var = self.nc.variables[self._positions_var]
            positions = np.array(positions_var[i][index])

            # Determine cell size for non-periodic directions
            for dim in np.arange(3)[np.logical_not(pbc)]:
                origin[dim] = positions[:, dim].min()
                cell_lengths[dim] = positions[:, dim].max() - origin[dim]

            # Construct cell shape from cell lengths and angles
            cell = cellpar_to_cell(
                list(cell_lengths) +
                list(self.nc.variables[self._cell_angles_var][i]))

            # Compute momenta from velocities (if present)
            if self._has_variable(self._velocities_var):
                momenta = self.nc.variables[self._velocities_var][i][index] * \
                    self.masses.reshape(-1, 1)
            else:
                momenta = None

            # Fill info dict with additional data found in the NetCDF file
            info = {}
            for name in self.extra_per_frame_atts:
                info[name] = np.array(self.nc.variables[name][i])

            # Create atoms object
            atoms = ase.Atoms(positions=positions - origin.reshape(1, -1),
                              numbers=self.numbers,
                              cell=cell,
                              momenta=momenta,
                              masses=self.masses,
                              pbc=pbc,
                              info=info)

            # Attach additional arrays found in the NetCDF file
            for name in self.extra_per_frame_vars:
                atoms.set_array(name, self.nc.variables[name][i][index])
            for name in self.extra_per_file_vars:
                atoms.set_array(name, self.nc.variables[name][:])
            self._close()
            return atoms

        i = N + i
        if i < 0 or i >= N:
            self._close()
            raise IndexError('Trajectory index out of range.')
        return self[i]