示例#1
0
    def get(self, key, unit=None, default=None, with_unit=False):
        """ Retrieve fdf-keyword from the file """

        # First split into specification and key
        key, tmp_unit = str_spec(key)
        if unit is None:
            unit = tmp_unit

        found, fdf = self._read(key)
        if not found:
            return default

        # The keyword is found...
        if fdf.startswith('%block'):
            found, fdf = self._read_block(key)
            if not found:
                return default
            else:
                return fdf

        # We need to process the returned value further.
        fdfl = fdf.split()
        # Check whether this is a logical flag
        if len(fdfl) == 1:
            # This *MUST* be a boolean
            #   SCF.Converge.H
            # defaults to .true.
            return True
        elif fdfl[1] in _LOGICAL_TRUE:
            return True
        elif fdfl[1] in _LOGICAL_FALSE:
            return False

        # It is something different.
        # Try and figure out what it is
        if len(fdfl) == 3:
            # We expect it to be a unit
            if unit is None:
                # Get group of unit
                group = unit_group(fdfl[2])
                # return in default sisl units
                unit = unit_default(group)

            if with_unit and tmp_unit is not None:
                # The user has specifically requested the unit:
                #  key{unit}
                return '{0:.4f} {1}'.format(
                    float(fdfl[1]) * unit_convert(fdfl[2], unit), unit)
            elif not with_unit:
                return float(fdfl[1]) * unit_convert(fdfl[2], unit)

        return ' '.join(fdfl[1:])
示例#2
0
文件: sile.py 项目: cationly/sisl
def get_sile(file, *args, **kwargs):
    """ Guess the ``Sile`` corresponding to the input file and return an open object of the corresponding ``Sile``

    Parameters
    ----------
    file : str
       the file to be quried for a correct `Sile` object.
       This file name may contain {<class-name>} which sets
       `cls` in case `cls` is not set.
       For instance:
          water.dat{XYZSile}
       will read the file water.dat as an `XYZSile`.
    cls : class
       In case there are several files with similar file-suffixes
       you may query the exact base-class that should be chosen.
       If there are several `Sile`s with similar file-endings this
       function returns a random one.
    """
    cls = kwargs.pop('cls', None)
    sile = get_sile_class(file, *args, cls=cls, **kwargs)
    return sile(str_spec(file)[0], *args, **kwargs)
示例#3
0
文件: sile.py 项目: sjumzw/sisl
def get_sile(file, *args, **kwargs):
    """ Retrieve an object from the global lookup table via filename and the extension

    Internally this is roughly equivalent to ``get_sile_class(...)()``.

    Parameters
    ----------
    file : str or pathlib.Path
       the file to be quried for a correct `Sile` object.
       This file name may contain {<class-name>} which sets
       `cls` in case `cls` is not set.
       For instance ``get_sile("water.dat{xyzSile}")``
       will read the file ``water.dat`` using the `xyzSile` class.
    cls : class
       In case there are several files with similar file-suffixes
       you may query the exact base-class that should be chosen.
       If there are several files with similar file-endings this
       function returns a random one.
    """
    cls = kwargs.pop('cls', None)
    sile = get_sile_class(file, *args, cls=cls, **kwargs)
    return sile(Path(str_spec(str(file))[0]), *args, **kwargs)
示例#4
0
文件: sile.py 项目: sjumzw/sisl
def get_sile_class(filename, *args, **kwargs):
    """ Retrieve a class from the global lookup table via filename and the extension

    Parameters
    ----------
    filename : str
       the file to be quried for a correct file object.
       This file name may contain {<class-name>} which sets
       `cls` in case `cls` is not set.
       For instance:

          water.xyz

       will return an `xyzSile`.
    cls : class, optional
       In case there are several files with similar file-suffixes
       you may query the exact base-class that should be chosen.
       If there are several files with similar file-endings this
       function returns a random one.
    """
    global __sile_rules, __siles

    # This ensures that the first argument need not be cls
    cls = kwargs.pop('cls', None)

    # Split filename into proper file name and
    # the Specification of the type
    tmp_file, fcls = str_spec(str(filename))

    if cls is None and not fcls is None:
        # cls has not been set, and fcls is found
        # Figure out if fcls is a valid sile, if not
        # do nothing (it may be part of the file name)
        # Which is REALLY obscure... but....)
        fclsl = fcls.lower()
        for sr in __sile_rules:
            if sr.in_class(fclsl):
                cls = sr.cls
            else:
                cls = sr.get_base(fclsl)
            if cls is not None:
                filename = tmp_file
                break

    try:
        # Create list of endings on this file
        f = basename(filename)
        end_list = []
        end = ''

        # Check for files without ending, or that they are directly zipped
        lext = splitext(f)
        while len(lext[1]) > 0:
            end = lext[1] + end
            if end[0] == '.':
                end_list.append(end[1:])
            else:
                end_list.append(end)
            lext = splitext(lext[0])

        # We also check the entire file name
        #  (mainly for VASP)
        end_list.append(f)
        # Reverse to start by the longest extension
        # (allows grid.nc extensions, etc.)
        end_list = list(reversed(end_list))

        # First we check for class AND file ending
        clss = None
        for end in end_list:
            for sr in __sile_rules:
                if sr.is_class(cls):
                    # class-specification has precedence
                    # This should only occur when the
                    # class-specification is exact (i.e. xyzSile)
                    return sr.cls
                elif sr.is_suffix(end):
                    if cls is None:
                        return sr.cls
                    elif sr.is_subclass(cls):
                        return sr.cls
                    clss = sr.cls
            if clss is not None:
                return clss

        if clss is None:
            raise NotImplementedError(
                "Sile for file '{}' could not be found, "
                "possibly the file has not been implemented.".format(filename))
        return clss

    except Exception as e:
        raise e
示例#5
0
文件: sile.py 项目: cationly/sisl
def get_sile_class(file, *args, **kwargs):
    """ Guess the ``Sile`` class corresponding to the input file and return the class

    Parameters
    ----------
    file : str
       the file to be quried for a correct `Sile` object.
       This file name may contain {<class-name>} which sets
       `cls` in case `cls` is not set.
       For instance:
          water.xyz
       will return an ``XYZSile``. 
    cls : class
       In case there are several files with similar file-suffixes
       you may query the exact base-class that should be chosen.
       If there are several ``Sile``s with similar file-endings this
       function returns a random one.
    """
    global __sile_rules, __siles

    # This ensures that the first argument need not be cls
    cls = kwargs.pop('cls', None)

    # Split filename into proper file name and
    # the specification of the type
    tmp_file, fcls = str_spec(file)

    if cls is None and not fcls is None:
        # cls has not been set, and fcls is found
        # Figure out if fcls is a valid sile, if not
        # do nothing (it may be part of the file name)
        # Which is REALLY obscure... but....)
        for sile in __siles:
            if sile.__name__.lower().startswith(fcls.lower()):
                cls = sile
                # Make sure that {class-name} is
                # removed from the file name
                file = tmp_file
                break

    try:
        # Create list of endings on this file
        f = file
        end_list = []
        end = ''

        # Check for files without ending, or that they are directly zipped
        lext = splitext(f)
        while len(lext[1]) > 0:
            end = lext[1] + end
            if end[0] == '.':
                end_list.append(end[1:])
            else:
                end_list.append(end)
            lext = splitext(lext[0])

        # We also check the entire file name
        #  (mainly for VASP)
        end_list.append(f)
        # Reverse to start by the longest extension
        # (allows grid.nc extensions, etc.)
        end_list = list(reversed(end_list))

        # First we check for class AND file ending
        for end in end_list:
            for suf, base, fobj in __sile_rules:
                if end != suf:
                    continue
                if cls is None:
                    return fobj
                elif cls == base:
                    return fobj

        # Now we skip the limitation of the suffix,
        # now only the base-class is necessary.
        for end in end_list:

            # Check for object
            for suf, base, fobj in __sile_rules:
                if cls == base:
                    return fobj

        del end_list

        raise NotImplementedError('sile not implemented: {}'.format(file))
    except NotImplementedError as e:
        pass
    except Exception as e:
        import traceback as t
        t.print_exc()
        raise e
    raise NotImplementedError(
        "Sile for file '" + file +
        "' could not be found, possibly the file has not been implemented.")