예제 #1
0
    def __init__(self, atoms: Atoms, oszicar: Oszicar, name: str=None, time: float=None):

        if name is None:
            self.name = str(self.atoms)
        else:
            self.name = name

        self.time = time

        self.atoms = atoms
        self.potential_energy = atoms.get_potential_energy()
        self.kinetic_energy = atoms.get_kinetic_energy()
        self.total_energy = atoms.get_total_energy()
        self.temperature = atoms.get_temperature()
        # self.magmom = atoms.get_magnetic_moment()

        self.elements = Counter(atoms.get_chemical_symbols())

        self.set_area()

        self.set_oszicar(oszicar)
        n = len(atoms)
        if self.get('F'):
            self.F_n = self.F / n
        else:
            self.F_n = self.potential_energy / n
예제 #2
0
파일: dftb.py 프로젝트: PHOTOX/fuase
def write_dftb(filename, atoms):
    """Method to write atom structure in DFTB+ format
       (gen format)
    """
    import numpy as np

    #sort
    atoms.set_masses()
    masses = atoms.get_masses()
    indexes = np.argsort(masses)
    atomsnew = Atoms()
    for i in indexes:
        atomsnew = atomsnew + atoms[i]

    if isinstance(filename, str):
        myfile = open(filename, 'w')
    else: # Assume it's a 'file-like object'
        myfile = filename

    ispbc = atoms.get_pbc()
    box = atoms.get_cell()
    
    if (any(ispbc)):
        myfile.write('%8d %2s \n' %(len(atoms), 'S'))
    else:
        myfile.write('%8d %2s \n' %(len(atoms), 'C'))

    chemsym = atomsnew.get_chemical_symbols()
    allchem = ''
    for i in chemsym:
        if i not in allchem:
            allchem = allchem + i + ' '
    myfile.write(allchem+' \n')

    coords = atomsnew.get_positions()
    itype = 1
    for iatom, coord in enumerate(coords):
        if iatom > 0:
            if chemsym[iatom] != chemsym[iatom-1]:
                itype = itype+1
        myfile.write('%5i%5i  %19.16f %19.16f %19.16f \n' \
                    %(iatom+1, itype, 
                      coords[iatom][0], coords[iatom][1], coords[iatom][2]))
    # write box
    if (any(ispbc)):
        #dftb dummy
        myfile.write(' %19.16f %19.16f %19.16f \n' %(0, 0, 0))
        myfile.write(' %19.16f %19.16f %19.16f \n' 
                %( box[0][0], box[0][1], box[0][2]))
        myfile.write(' %19.16f %19.16f %19.16f \n' 
                %( box[1][0], box[1][1], box[1][2]))
        myfile.write(' %19.16f %19.16f %19.16f \n' 
                %( box[2][0], box[2][1], box[2][2]))

    if type(filename) == str:    
        myfile.close()
예제 #3
0
def write_dftb(filename, atoms):
    """Method to write atom structure in DFTB+ format
       (gen format)
    """
    import numpy as np

    #sort
    atoms.set_masses()
    masses = atoms.get_masses()
    indexes = np.argsort(masses)
    atomsnew = Atoms()
    for i in indexes:
        atomsnew = atomsnew + atoms[i]

    if isinstance(filename, str):
        myfile = open(filename, 'w')
    else:  # Assume it's a 'file-like object'
        myfile = filename

    ispbc = atoms.get_pbc()
    box = atoms.get_cell()

    if (any(ispbc)):
        myfile.write('%8d %2s \n' % (len(atoms), 'S'))
    else:
        myfile.write('%8d %2s \n' % (len(atoms), 'C'))

    chemsym = atomsnew.get_chemical_symbols()
    allchem = ''
    for i in chemsym:
        if i not in allchem:
            allchem = allchem + i + ' '
    myfile.write(allchem + ' \n')

    coords = atomsnew.get_positions()
    itype = 1
    for iatom, coord in enumerate(coords):
        if iatom > 0:
            if chemsym[iatom] != chemsym[iatom - 1]:
                itype = itype + 1
        myfile.write('%5i%5i  %19.16f %19.16f %19.16f \n' \
                    %(iatom+1, itype,
                      coords[iatom][0], coords[iatom][1], coords[iatom][2]))
    # write box
    if (any(ispbc)):
        #dftb dummy
        myfile.write(' %19.16f %19.16f %19.16f \n' % (0, 0, 0))
        myfile.write(' %19.16f %19.16f %19.16f \n' %
                     (box[0][0], box[0][1], box[0][2]))
        myfile.write(' %19.16f %19.16f %19.16f \n' %
                     (box[1][0], box[1][1], box[1][2]))
        myfile.write(' %19.16f %19.16f %19.16f \n' %
                     (box[2][0], box[2][1], box[2][2]))

    if isinstance(filename, str):
        myfile.close()
def unf(phonon, sc_mat, qpoints, knames=None, x=None, xpts=None):
    prim = phonon.get_primitive()
    prim = Atoms(symbols=prim.get_chemical_symbols(),
                 cell=prim.get_cell(),
                 positions=prim.get_positions())
    #vesta_view(prim)
    sc_qpoints = np.array([np.dot(q, sc_mat) for q in qpoints])
    phonon.set_qpoints_phonon(sc_qpoints, is_eigenvectors=True)
    freqs, eigvecs = phonon.get_qpoints_phonon()
    uf = phonon_unfolder(atoms=prim,
                         supercell_matrix=sc_mat,
                         eigenvectors=eigvecs,
                         qpoints=sc_qpoints,
                         phase=False)
    weights = uf.get_weights()

    #ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*8065.6,weights[:,:].T*0.98+0.01,xticks=[knames,xpts],style='alpha')
    ax = plot_band_weight([list(x)] * freqs.shape[1],
                          freqs.T * 33.356,
                          weights[:, :].T * 0.99 + 0.001,
                          xticks=[knames, xpts],
                          style='alpha')
    return ax
예제 #5
0
class MapBase(StructuredGrid):
    """
    MapBase
    =======

    :subclass of: StructuredGrid

    :Note: MapBase is a virtual class whose subclasses should overload the
           *run* function.

    Synopsis
    --------
    In addition to managing a structured grid, capability this inherits from
    *StructuredGrid*, *Map* also provides the interface to the *Atomistic
    Simulation Environment* (*ASE*) :code:`Atoms` object.

    API
    ---
    In what follows, the functionality of this class, which is intended to
    be *purely virtual*, will be detailed as if accessed from a derived
    class, *i.e.* :code:`map = MapBaseDerivedClass()`

    :MapBaseDerivedClass.covalentRadii: Dictionary of covalent radii
            accessed by chemical symbol.
    :Map.vdwRadii: Dictionary of van der Waals radii, accessed by chemical
            symbol.
    :map.atoms: Get/set the ase.atoms.Atoms object.
    :map.get_chemical_symbols(): Returns a list of the chemical symbols,
            *e.g.* ['H', 'H', 'S', 'O', 'O', 'O', 'O']. This list will be
            the same length as the number of atoms in the structure.
    :map.get_radii(): Gets the radii of the atoms.
    :map.set_radii(): These must be set
            explicitly, which can be done with relative ease by using the
            Map.covalentRadii (or analogously, Map.vdwRadii):

            .. code:: python

                map.set_radii([Map.covalentRadii[s]
                               for s in map.get_chemical_symbols()])

    :map.set_pv(pv): Sets the periodicity vectors.
    :map.run(): **virtual**
    """
    # element information
    covalentRadii = dict(zip(chemical_symbols, covalent_radii))
    vdwRadii = dict(zip(chemical_symbols, vdw_radii))

    def __init__(self, ndiv=None, pv=None):  # pylint: disable=C0103
        self._absolute = True
        self._atoms = Atoms()
        self._radii = None
        super(MapBase, self).__init__(ndiv=ndiv, pv=pv)

    @property
    def atoms(self):
        """Gets the :code:`ase.atoms` object."""
        return self._atoms

    @atoms.setter
    def atoms(self, val):
        """Sets the :code:`ase.atoms` object."""
        if not isinstance(val, Atoms):
            TypeError('The atoms must be stored as an ase Atoms object.')
        self._atoms = val
        if np.all(self.atoms.get_cell() == np.eye(3)):
            self.atoms.set_cell(self.get_pv())
        else:
            self.set_pv(self.atoms.get_cell())
        self.atoms.set_pbc(3 * (True, ))

    def get_chemical_symbols(self):
        """Gets the chemical symbols for the atoms stored in this grid."""
        return self._atoms.get_chemical_symbols()

    def get_radii(self):
        """
        Gets the radii for the point-of-nearest-approach calculations.
        """
        if self._radii is None:
            return len(self.atoms) * [0.0]
        else:
            return self._radii

    def set_radii(self, radii):
        """
        Sets the radii to be used for point-of-nearest-approach.
        """
        if len(radii) != len(self.get_chemical_symbols()):
            raise ValueError('The number of provided radii (%d) does not '
                             'match the number of atoms in the system (%d).' %
                             (len(radii), len(self.get_chemical_symbols())))
        self._radii = radii[:]
        self._absolute = False

    radii = property(get_radii,
                     set_radii,
                     doc="Sets the radii of the atoms in this map.")

    def set_pv(self, pv):  # pylint: disable=C0103
        super(MapBase, self).set_pv(pv)
        self.atoms.set_cell(pv)
        self.atoms.set_pbc(3 * (True, ))

    def run(self, *args, **kwds):
        """
        Because the mapping process can be expensive, it must be
        called explicitly.

        :param leafsize: Specify the leafsize for the cKDTree used in
                         finding neighboring atoms.
        :param verbosity: specify the amount of status information
                        : to write (to the stderr)
        :type leafsize: positive integer
        :type verbosity: int
        :returns: none
        """
        pass
예제 #6
0
파일: database.py 프로젝트: Bismarrck/kcon
def xyz_to_database(xyzfile,
                    num_examples=None,
                    xyz_format='xyz',
                    verbose=True,
                    unit_to_ev=None,
                    restart=False):
    """
  Convert the xyz file to an `ase.db.core.Database`.

  Args:
    xyzfile: a `str` as the file to parse.
    num_examples: a `int` as the maximum number of examples to parse. If None,
      all examples in the given file will be saved.
    xyz_format: a `str` representing the format of the given xyz file.
    verbose: a `bool` indicating whether we should log the parsing progress.
    unit_to_ev: a `float` as the unit for converting energies to eV. Defaults
      to None so that default units will be used.
    restart: a `bool`. If True, the database will be re-built even if already
      existed.

  Returns:
    database: an `ase.db.core.Database`.
    auxdict: a `dict` as the auxiliary dict for this database.

  """
    if xyz_format.lower() == 'ase':
        formatter = _ase_xyz
    else:
        formatter = _xyz

    dbfile = "{}.db".format(splitext(xyzfile)[0])
    if isfile(dbfile):
        if restart:
            remove(dbfile)
        else:
            auxdict = _load_auxiliary_dict(dbfile)
            return connect(name=dbfile), auxdict

    unit = unit_to_ev or formatter.default_unit
    parse_forces = formatter.parse_forces
    count = 0
    ai = 0
    natoms = 0
    stage = 0
    atoms = None
    num_examples = num_examples or 0
    natoms_counter = Counter()
    y_min = np.inf
    y_max = -np.inf
    max_occurs = Counter()

    database = connect(name=dbfile)
    tic = time.time()
    if verbose:
        sys.stdout.write("Extract cartesian coordinates ...\n")
    with open(xyzfile) as f:
        for line in f:
            if num_examples and count == num_examples:
                break
            line = line.strip()
            if line == "":
                continue
            if stage == 0:
                if line.isdigit():
                    natoms = int(line)
                    atoms = Atoms(calculator=ProvidedCalculator())
                    if parse_forces:
                        atoms.info['provided_forces'] = np.zeros((natoms, 3))
                    natoms_counter[natoms] += 1
                    stage += 1
            elif stage == 1:
                m = formatter.energy_patt.search(line)
                if m:
                    if xyz_format.lower() == 'extxyz':
                        energy = float(m.group(3)) * unit
                    elif xyz_format.lower() == 'ase':
                        energy = float(m.group(2)) * unit
                        atoms.set_cell(
                            np.reshape([float(x) for x in m.group(1).split()],
                                       (3, 3)))
                        atoms.set_pbc([
                            True if x == "T" else False
                            for x in m.group(3).split()
                        ])
                    else:
                        energy = float(m.group(1)) * unit
                    atoms.info['provided_energy'] = energy
                    y_min = min(y_min, energy)
                    y_max = max(y_max, energy)
                    stage += 1
            elif stage == 2:
                m = formatter.string_patt.search(line)
                if m:
                    atoms.append(
                        Atom(symbol=m.group(1),
                             position=[float(v) for v in m.groups()[1:4]]))
                    if parse_forces:
                        atoms.info['provided_forces'][ai, :] = [
                            float(v) * unit for v in m.groups()[4:7]
                        ]
                    ai += 1
                    if ai == natoms:
                        atoms.calc.calculate()
                        database.write(atoms)
                        counter = Counter(atoms.get_chemical_symbols())
                        for symbol, n in counter.items():
                            max_occurs[symbol] = max(max_occurs[symbol], n)
                        ai = 0
                        stage = 0
                        count += 1
                        if verbose and count % 1000 == 0:
                            sys.stdout.write(
                                "\rProgress: {:7d}  /  {:7d} | Speed = {:.1f}".
                                format(count, num_examples,
                                       count / (time.time() - tic)))
        if verbose:
            print("")
            print("Total time: %.3f s\n" % (time.time() - tic))

        # Dump the auxiliary dict.
        auxdict = {
            "max_occurs": dict(max_occurs),
            "y_range": [y_min, y_max],
            "natoms_counter": dict(natoms_counter)
        }
        _save_auxiliary_dict(dbfile, auxdict)

        return database, auxdict