示例#1
0
def get_aiida_structure_data(
        optimade_structure: OptimadeStructure) -> StructureData:
    """Get AiiDA `StructureData` from OPTIMADE structure.

    Parameters:
        optimade_structure: OPTIMADE structure.

    Returns:
        AiiDA `StructureData` Node.

    """
    if "optimade.adapters" in repr(globals().get("StructureData")):
        warn(AIIDA_NOT_FOUND)
        return None

    attributes = optimade_structure.attributes

    # Convert null/None values to float("nan")
    lattice_vectors, adjust_cell = pad_cell(attributes.lattice_vectors)
    structure = StructureData(cell=lattice_vectors)

    # Add Kinds
    for kind in attributes.species:
        symbols = []
        concentration = []
        for index, chemical_symbol in enumerate(kind.chemical_symbols):
            # NOTE: The non-chemical element identifier "X" is identical to how AiiDA handles this,
            # so it will be treated the same as any other true chemical identifier.
            if chemical_symbol == "vacancy":
                # Skip. This is how AiiDA handles vacancies;
                # to not include them, while keeping the concentration in a site less than 1.
                continue
            else:
                symbols.append(chemical_symbol)
                concentration.append(kind.concentration[index])

        # AiiDA needs a definition for the mass, and for it to be > 0
        # mass is OPTIONAL for OPTIMADE structures
        mass = kind.mass if kind.mass else 1

        structure.append_kind(
            Kind(symbols=symbols,
                 weights=concentration,
                 mass=mass,
                 name=kind.name))

    # Add Sites
    for index in range(attributes.nsites):
        # range() to ensure 1-to-1 between kind and site
        structure.append_site(
            Site(
                kind_name=attributes.species_at_sites[index],
                position=attributes.cartesian_site_positions[index],
            ))

    if adjust_cell:
        structure._adjust_default_cell(
            pbc=[bool(dim.value) for dim in attributes.dimension_types])

    return structure
示例#2
0
    def get_step_structure(self, index, custom_kinds=None):
        """
        Return an AiiDA :py:class:`aiida.orm.nodes.data.structure.StructureData` node
        (not stored yet!) with the coordinates of the given step, identified by
        its index. If you know only the step value, use the
        :py:meth:`.get_index_from_stepid` method to get the corresponding index.

        .. note:: The periodic boundary conditions are always set to True.

        .. versionadded:: 0.7
           Renamed from step_to_structure

        :param index: The index of the step that you want to retrieve, from
           0 to ``self.numsteps- 1``.
        :param custom_kinds: (Optional) If passed must be a list of
          :py:class:`aiida.orm.nodes.data.structure.Kind` objects. There must be one
          kind object for each different string in the ``symbols`` array, with
          ``kind.name`` set to this string.
          If this parameter is omitted, the automatic kind generation of AiiDA
          :py:class:`aiida.orm.nodes.data.structure.StructureData` nodes is used,
          meaning that the strings in the ``symbols`` array must be valid
          chemical symbols.
        """
        from aiida.orm.nodes.data.structure import StructureData, Kind, Site

        # ignore step, time, and velocities
        _, _, cell, symbols, positions, _ = self.get_step_data(index)

        if custom_kinds is not None:
            kind_names = []
            for k in custom_kinds:
                if not isinstance(k, Kind):
                    raise TypeError(
                        'Each element of the custom_kinds list must '
                        'be a aiida.orm.nodes.data.structure.Kind object'
                    )
                kind_names.append(k.name)
            if len(kind_names) != len(set(kind_names)):
                raise ValueError('Multiple kinds with the same name passed as custom_kinds')
            if set(kind_names) != set(symbols):
                raise ValueError(
                    'If you pass custom_kinds, you have to '
                    'pass one Kind object for each symbol '
                    'that is present in the trajectory. You '
                    'passed {}, but the symbols are {}'.format(sorted(kind_names), sorted(symbols))
                )

        struc = StructureData(cell=cell)
        if custom_kinds is not None:
            for _k in custom_kinds:
                struc.append_kind(_k)
            for _s, _p in zip(symbols, positions):
                struc.append_site(Site(kind_name=_s, position=_p))
        else:
            for _s, _p in zip(symbols, positions):
                # Automatic species generation
                struc.append_atom(symbols=_s, position=_p)

        return struc
示例#3
0
    def get_structuredata(self):
        """Return a StructureData object based on the data in the input file.

        All of the names corresponding of the ``Kind`` objects composing the ``StructureData`` object will match those
        found in the ``ATOMIC_SPECIES`` block, so the pseudo potentials can be linked to the calculation using the kind
        name for each specific type of atom (in the event that you wish to use different pseudo's for two or more of the
        same atom).

        :return: structure data node of the structure defined in the input file.
        :rtype: :class:`~aiida.orm.nodes.data.structure.StructureData`
        """
        from aiida.orm.nodes.data.structure import StructureData, Kind, Site

        valid_elements_regex = re.compile(
            """
            (?P<ele>
    H  | He |
    Li | Be | B  | C  | N  | O  | F  | Ne |
    Na | Mg | Al | Si | P  | S  | Cl | Ar |
    K  | Ca | Sc | Ti | V  | Cr | Mn | Fe | Co | Ni | Cu | Zn | Ga | Ge | As | Se | Br | Kr |
    Rb | Sr | Y  | Zr | Nb | Mo | Tc | Ru | Rh | Pd | Ag | Cd | In | Sn | Sb | Te | I  | Xe |
    Cs | Ba | Hf | Ta | W  | Re | Os | Ir | Pt | Au | Hg | Tl | Pb | Bi | Po | At | Rn |
    Fr | Ra | Rf | Db | Sg | Bh | Hs | Mt |

    La | Ce | Pr | Nd | Pm | Sm | Eu | Gd | Tb | Dy | Ho | Er | Tm | Yb | Lu | # Lanthanides
    Ac | Th | Pa | U  | Np | Pu | Am | Cm | Bk | Cf | Es | Fm | Md | No | Lr | # Actinides
            )
            [^a-z]  # Any specification of an element is followed by some number
                    # or capital letter or special character.
        """, re.X | re.I)

        data = self.get_structure_from_qeinput()
        species = self.atomic_species

        structure = StructureData()
        structure.set_attribute('cell', data['cell'])

        for mass, name, pseudo in zip(species['masses'], species['names'],
                                      species['pseudo_file_names']):
            try:
                symbols = valid_elements_regex.search(pseudo).group(
                    'ele').capitalize()
            except Exception:
                raise InputValidationError(
                    'could not determine element name from pseudo name: {}'.
                    format(pseudo))
            structure.append_kind(Kind(name=name, symbols=symbols, mass=mass))

        for symbol, position in zip(data['atom_names'], data['positions']):
            structure.append_site(Site(kind_name=symbol, position=position))

        return structure
示例#4
0
def import_aiida_xyz(filename, vacuum_factor, vacuum_addition, pbc, dry_run):
    """
    Import structure in XYZ format using AiiDA's internal importer
    """
    from aiida.orm import StructureData

    with open(filename, encoding='utf8') as fobj:
        xyz_txt = fobj.read()
    new_structure = StructureData()

    pbc_bools = []
    for pbc_int in pbc:
        if pbc_int == 0:
            pbc_bools.append(False)
        elif pbc_int == 1:
            pbc_bools.append(True)
        else:
            raise click.BadParameter('values for pbc must be either 0 or 1',
                                     param_hint='pbc')

    try:
        new_structure._parse_xyz(xyz_txt)  # pylint: disable=protected-access
        new_structure._adjust_default_cell(  # pylint: disable=protected-access
            vacuum_addition=vacuum_addition,
            vacuum_factor=vacuum_factor,
            pbc=pbc_bools)

    except (ValueError, TypeError) as err:
        echo.echo_critical(str(err))

    _store_structure(new_structure, dry_run)
示例#5
0
def import_ase(filename, label, group, dry_run):
    """
    Import structure with the ase library that supports a number of different formats
    """
    from aiida.orm import StructureData

    try:
        import ase.io
    except ImportError:
        echo.echo_critical('You have not installed the package ase. \nYou can install it with: pip install ase')

    try:
        asecell = ase.io.read(filename)
        new_structure = StructureData(ase=asecell)
    except ValueError as err:
        echo.echo_critical(str(err))

    if label:
        new_structure.label = label

    _store_structure(new_structure, dry_run)

    if group:
        group.add_nodes(new_structure)
示例#6
0
def spglib_tuple_to_structure(structure_tuple, kind_info=None, kinds=None):  # pylint: disable=too-many-locals
    """
    Convert a tuple of the format (cell, scaled_positions, element_numbers) to an AiiDA structure.

    Unless the element_numbers are identical to the Z number of the atoms,
    you should pass both kind_info and kinds, with the same format as returned
    by get_tuple_from_aiida_structure.

    :param structure_tuple: the structure in format (structure_tuple, kind_info)
    :param kind_info: a dictionary mapping the kind_names to
       the numbers used in element_numbers. If not provided, assumes {element_name: element_Z}
    :param kinds: a list of the kinds of the structure.
    """
    if kind_info is None and kinds is not None:
        raise ValueError('If you pass kind_info, you should also pass kinds')
    if kinds is None and kind_info is not None:
        raise ValueError('If you pass kinds, you should also pass kind_info')

    #Z = {v['symbol']: k for k, v in elements.items()}
    cell, rel_pos, numbers = structure_tuple
    if kind_info:
        _kind_info = copy.copy(kind_info)
        _kinds = copy.copy(kinds)
    else:
        try:
            # For each site
            symbols = [elements[num]['symbol'] for num in numbers]
        except KeyError as exc:
            raise ValueError(
                'You did not pass kind_info, but at least one number '
                'is not a valid Z number: {}'.format(exc.args[0]))

        _kind_info = {elements[num]['symbol']: num for num in set(numbers)}
        # Get the default kinds
        _kinds = [Kind(symbols=sym) for sym in set(symbols)]

    _kinds_dict = {k.name: k for k in _kinds}
    # Now I will use in any case _kinds and _kind_info
    if len(_kind_info) != len(set(_kind_info.values())):
        raise ValueError(
            'There is at least a number repeated twice in kind_info!')
    # Invert the mapping
    mapping_num_kindname = {v: k for k, v in _kind_info.items()}
    # Create the actual mapping
    try:
        mapping_to_kinds = {
            num: _kinds_dict[kindname]
            for num, kindname in mapping_num_kindname.items()
        }
    except KeyError as exc:
        raise ValueError("Unable to find '{}' in the kinds list".format(
            exc.args[0]))

    try:
        site_kinds = [mapping_to_kinds[num] for num in numbers]
    except KeyError as exc:
        raise ValueError(
            'Unable to find kind in kind_info for number {}'.format(
                exc.args[0]))

    structure = StructureData(cell=cell)
    for k in _kinds:
        structure.append_kind(k)
    abs_pos = np.dot(rel_pos, cell)
    if len(abs_pos) != len(site_kinds):
        raise ValueError(
            'The length of the positions array is different from the length of the element numbers'
        )

    for kind, pos in zip(site_kinds, abs_pos):
        structure.append_site(Site(kind_name=kind.name, position=pos))

    return structure
示例#7
0
 def parse_aiida(cls, string):
     from aiida.orm.nodes.data.structure import StructureData
     pym_struct = cls.parse(string)
     return StructureData(pymatgen_structure=pym_struct)