Esempio n. 1
0
def save(filename, signal, overwrite=None, **kwds):
    extension = os.path.splitext(filename)[1][1:]
    if extension == '':
        extension = "hspy"
        filename = filename + '.' + extension
    writer = None
    for plugin in io_plugins:
        if extension.lower() in plugin.file_extensions:
            writer = plugin
            break

    if writer is None:
        raise ValueError(
            ('.%s does not correspond to any supported format. Supported ' +
             'file extensions are: %s') %
            (extension, strlist2enumeration(default_write_ext)))
    else:
        # Check if the writer can write
        sd = signal.axes_manager.signal_dimension
        nd = signal.axes_manager.navigation_dimension
        if writer.writes is False:
            raise ValueError('Writing to this format is not '
                             'supported, supported file extensions are: %s ' %
                             strlist2enumeration(default_write_ext))
        if writer.writes is not True and (sd, nd) not in writer.writes:
            yes_we_can = [
                plugin.format_name for plugin in io_plugins
                if plugin.writes is True or plugin.writes is not False and
                (sd, nd) in plugin.writes
            ]
            raise IOError('This file format cannot write this data. '
                          'The following formats can: %s' %
                          strlist2enumeration(yes_we_can))
        ensure_directory(filename)
        is_file = os.path.isfile(filename)
        if overwrite is None:
            write = overwrite_method(filename)  # Ask what to do
        elif overwrite is True or (overwrite is False and not is_file):
            write = True  # Write the file
        elif overwrite is False and is_file:
            write = False  # Don't write the file
        else:
            raise ValueError("`overwrite` parameter can only be None, True or "
                             "False.")
        if write:
            writer.file_writer(filename, signal, **kwds)
            _logger.info('The %s file was created' % filename)
            folder, filename = os.path.split(os.path.abspath(filename))
            signal.tmp_parameters.set_item('folder', folder)
            signal.tmp_parameters.set_item('filename',
                                           os.path.splitext(filename)[0])
            signal.tmp_parameters.set_item('extension', extension)
Esempio n. 2
0
def save(filename, signal, overwrite=None, **kwds):
    """Save hyperspy signal to a file.

    A list of plugins supporting file saving can be found here:
    http://hyperspy.org/hyperspy-doc/current/user_guide/io.html#supported-formats

    Any extra keywords are passed to the corresponding save method in the
    io_plugin. For available options, see their individual documentation.

    Parameters
    ----------
    filename : None or str or pathlib.Path
        The filename to save the signal to.
    signal : Hyperspy signal
        The signal to be saved to file.
    overwrite : None or bool, default None
        If None and a file exists the user will be prompted to on whether to
        overwrite. If False and a file exists the file will not be written.
        If True and a file exists the file will be overwritten without
        prompting

    Returns
    -------
    None

    """
    filename = Path(filename).resolve()
    extension = filename.suffix
    if extension == '':
        extension = ".hspy"
        filename = filename.with_suffix(extension)

    writer = None
    for plugin in io_plugins:
        # Drop the "." separator from the suffix
        if extension[1:].lower() in plugin.file_extensions:
            writer = plugin
            break

    if writer is None:
        raise ValueError(
            f"{extension} does not correspond to any supported format. "
            f"Supported file extensions are: {strlist2enumeration(default_write_ext)}"
        )

    # Check if the writer can write
    sd = signal.axes_manager.signal_dimension
    nd = signal.axes_manager.navigation_dimension

    if writer.writes is False:
        raise ValueError(
            "Writing to this format is not supported. "
            f"Supported file extensions are: {strlist2enumeration(default_write_ext)}"
        )

    if writer.writes is not True and (sd, nd) not in writer.writes:
        yes_we_can = [plugin.format_name for plugin in io_plugins
                      if plugin.writes is True or
                      plugin.writes is not False and
                      (sd, nd) in plugin.writes]

        raise IOError(
            "This file format does not support this data. "
            f"Please try one of {strlist2enumeration(yes_we_can)}"
        )

    # Create the directory if it does not exist
    ensure_directory(filename.parent)
    is_file = filename.is_file()

    if overwrite is None:
        write = overwrite_method(filename)  # Ask what to do
    elif overwrite is True or (overwrite is False and not is_file):
        write = True  # Write the file
    elif overwrite is False and is_file:
        write = False  # Don't write the file
    else:
        raise ValueError(
            "`overwrite` parameter can only be None, True or False."
        )

    if write:
        # Pass as a string for now, pathlib.Path not
        # properly supported in io_plugins
        writer.file_writer(str(filename), signal, **kwds)

        _logger.info(f'{filename} was created')
        signal.tmp_parameters.set_item('folder', filename.parent)
        signal.tmp_parameters.set_item('filename', filename.stem)
        signal.tmp_parameters.set_item('extension', extension)
Esempio n. 3
0
File: io.py Progetto: pc494/hyperspy
def save(filename, signal, overwrite=None, **kwds):
    """
    Save hyperspy signal to a file.

    A list of plugins supporting file saving can be found here: 
    http://hyperspy.org/hyperspy-doc/current/user_guide/io.html#supported-formats

    Any extra keyword is passed to the corresponding save method in the
    io_plugin. 
    For available options see their individual documentation.

    Parameters
    ----------
    filename :  None or str
        The filename to save the signal to. 
    signal :  Hyperspy signal
        The signal to be saved to file     
    overwrite : None or Bool (default, None)
        If None and a file exists the user will be prompted to on whether to 
        overwrite. If False and a file exists the file will not be written.
        If True and a file exists the file will be overwritten without 
        prompting
    
    """
    extension = os.path.splitext(filename)[1][1:]
    if extension == '':
        extension = "hspy"
        filename = filename + '.' + extension
    writer = None
    for plugin in io_plugins:
        if extension.lower() in plugin.file_extensions:
            writer = plugin
            break

    if writer is None:
        raise ValueError(
            ('.%s does not correspond to any supported format. Supported ' +
             'file extensions are: %s') %
            (extension, strlist2enumeration(default_write_ext)))
    else:
        # Check if the writer can write
        sd = signal.axes_manager.signal_dimension
        nd = signal.axes_manager.navigation_dimension
        if writer.writes is False:
            raise ValueError('Writing to this format is not '
                             'supported, supported file extensions are: %s ' %
                             strlist2enumeration(default_write_ext))
        if writer.writes is not True and (sd, nd) not in writer.writes:
            yes_we_can = [
                plugin.format_name for plugin in io_plugins
                if plugin.writes is True or plugin.writes is not False and
                (sd, nd) in plugin.writes
            ]
            raise IOError('This file format cannot write this data. '
                          'The following formats can: %s' %
                          strlist2enumeration(yes_we_can))
        ensure_directory(filename)
        is_file = os.path.isfile(filename)
        if overwrite is None:
            write = overwrite_method(filename)  # Ask what to do
        elif overwrite is True or (overwrite is False and not is_file):
            write = True  # Write the file
        elif overwrite is False and is_file:
            write = False  # Don't write the file
        else:
            raise ValueError("`overwrite` parameter can only be None, True or "
                             "False.")
        if write:
            writer.file_writer(filename, signal, **kwds)
            _logger.info('The %s file was created' % filename)
            folder, filename = os.path.split(os.path.abspath(filename))
            signal.tmp_parameters.set_item('folder', folder)
            signal.tmp_parameters.set_item('filename',
                                           os.path.splitext(filename)[0])
            signal.tmp_parameters.set_item('extension', extension)
Esempio n. 4
0
def save(filename, signal, overwrite=None, add_scan=None, **kwargs):
    """Write electron backscatter patterns to file.

    Parameters
    ----------
    filename : str
        File path including name of new file.
    signal : {kikuchipy.signals.EBSD, kikuchipy.lazy_signals.LazyEBSD}
        Signal instance.
    overwrite : {bool, None}, optional
        Whether to overwrite file or not if it already exists.
    add_scan : {bool, None}, optional
        Whether to add the signal to an already existing h5ebsd file or
        not. If the file does not exist the signal is written to a new
        file.
    **kwargs :
        Keyword arguments passed to the writer.
    """
    from hyperspy.misc.io.tools import overwrite as overwrite_method
    ext = os.path.splitext(filename)[1][1:]
    if ext == '':  # Will write to HyperSpy's HDF5 format
        ext = 'hspy'
        filename = filename + '.' + ext

    writer = None
    for plugin in io_plugins:
        if ext.lower() in plugin.file_extensions:
            writer = plugin
            break

    if writer is None:
        raise ValueError(
            (".%s does not correspond to any supported format. Supported "
             "file extensions are: %s") %
            (ext, strlist2enumeration(default_write_ext)))
    else:  # Check if the writer can write
        sd = signal.axes_manager.signal_dimension
        nd = signal.axes_manager.navigation_dimension
        if writer.writes is False:
            raise ValueError("Writing to this format is not "
                             "supported, supported file extensions are: %s " %
                             strlist2enumeration(default_write_ext))
        if writer.writes is not True and (sd, nd) not in writer.writes:
            yes_we_can = [
                plugin.format_name for plugin in io_plugins
                if plugin.writes is True or plugin.writes is not False and
                (sd, nd) in plugin.writes
            ]
            raise IOError("This file format cannot write this data. "
                          "The following formats "
                          "can: {}".format(strlist2enumeration(yes_we_can)))

        # Check possibilities for overwriting file and/or datasets within file
        ensure_directory(filename)
        is_file = os.path.isfile(filename)
        if writer.format_name == 'h5ebsd' and overwrite is not True and is_file:
            if add_scan is None:
                q = "Add scan to '{}' (y/n)?\n".format(filename)
                add_scan = get_input_bool(q)
            if add_scan:
                overwrite = True  # So that the 2nd statement below triggers
            kwargs['add_scan'] = add_scan
        if overwrite is None:
            write = overwrite_method(filename)  # Ask what to do
        elif overwrite is True or (overwrite is False and not is_file):
            write = True  # Write the file
        elif overwrite is False and is_file:
            write = False  # Don't write the file
        else:
            raise ValueError("`overwrite` parameter can only be None, True or "
                             "False, and not {}".format(overwrite))
        if write:
            writer.file_writer(filename, signal, **kwargs)
            folder, filename = os.path.split(os.path.abspath(filename))
            signal.tmp_parameters.set_item('folder', folder)
            signal.tmp_parameters.set_item('filename',
                                           os.path.splitext(filename)[0])
            signal.tmp_parameters.set_item('extension', ext)
Esempio n. 5
0
def save(filename, signal, overwrite=None, **kwds):
    """Save hyperspy signal to a file.

    A list of plugins supporting file saving can be found here:
    http://hyperspy.org/hyperspy-doc/current/user_guide/io.html#supported-formats

    Any extra keywords are passed to the corresponding save method in the
    io_plugin. For available options, see their individual documentation.

    Parameters
    ----------
    filename : None, str, pathlib.Path
        The filename to save the signal to.
    signal : Hyperspy signal
        The signal to be saved to the file.
    overwrite : None, bool, optional
        If None (default) and a file exists, the user will be prompted whether
        to overwrite. If False and a file exists, the file will not be written.
        If True and a file exists, the file will be overwritten without
        prompting

    Returns
    -------
    None

    """
    if isinstance(filename, MutableMapping):
        extension = ".zspy"
    else:
        filename = Path(filename).resolve()
        extension = filename.suffix
        if extension == '':
            extension = ".hspy"
            filename = filename.with_suffix(extension)

    writer = None
    for plugin in io_plugins:
        # Drop the "." separator from the suffix
        if extension[1:].lower() in plugin.file_extensions:
            writer = plugin
            break

    if writer is None:
        raise ValueError(
            f"{extension} does not correspond to any supported format. "
            f"Supported file extensions are: {strlist2enumeration(default_write_ext)}"
        )

    # Check if the writer can write
    sd = signal.axes_manager.signal_dimension
    nd = signal.axes_manager.navigation_dimension

    if writer.writes is False:
        raise ValueError(
            "Writing to this format is not supported. "
            f"Supported file extensions are: {strlist2enumeration(default_write_ext)}"
        )

    if writer.writes is not True and (sd, nd) not in writer.writes:
        compatible_writers = [
            plugin.format_name for plugin in io_plugins
            if plugin.writes is True or plugin.writes is not False and
            (sd, nd) in plugin.writes
        ]

        raise TypeError(
            "This file format does not support this data. "
            f"Please try one of {strlist2enumeration(compatible_writers)}")

    if not writer.non_uniform_axis and not signal.axes_manager.all_uniform:
        compatible_writers = [
            plugin.format_name for plugin in io_plugins
            if plugin.non_uniform_axis is True
        ]
        raise TypeError("Writing to this format is not supported for "
                        "non-uniform axes. Use one of the following "
                        f"formats: {strlist2enumeration(compatible_writers)}")

    # Create the directory if it does not exist
    if not isinstance(filename, MutableMapping):
        ensure_directory(filename.parent)
        is_file = filename.is_file() or (
            filename.is_dir() and os.path.splitext(filename)[1] == '.zspy')

        if overwrite is None:
            write = overwrite_method(filename)  # Ask what to do
        elif overwrite is True or (overwrite is False and not is_file):
            write = True  # Write the file
        elif overwrite is False and is_file:
            write = False  # Don't write the file
        else:
            raise ValueError("`overwrite` parameter can only be None, True or "
                             "False.")
    else:
        write = True  # file does not exist (creating it)
    if write:
        # Pass as a string for now, pathlib.Path not
        # properly supported in io_plugins
        signal = _add_file_load_save_metadata('save', signal, writer)
        if not isinstance(filename, MutableMapping):
            writer.file_writer(str(filename), signal, **kwds)
            _logger.info(f'{filename} was created')
            signal.tmp_parameters.set_item('folder', filename.parent)
            signal.tmp_parameters.set_item('filename', filename.stem)
            signal.tmp_parameters.set_item('extension', extension)
        else:
            writer.file_writer(filename, signal, **kwds)
            if hasattr(filename, "path"):
                file = Path(filename.path).resolve()
                signal.tmp_parameters.set_item('folder', file.parent)
                signal.tmp_parameters.set_item('filename', file.stem)
                signal.tmp_parameters.set_item('extension', extension)
Esempio n. 6
0
def _save(
    filename: str,
    signal,
    overwrite: Optional[bool] = None,
    add_scan: Optional[bool] = None,
    **kwargs,
):
    """Write signal to a file in a supported format.

    This function is a modified version of :func:`hyperspy.io.save`.

    Parameters
    ----------
    filename
        File path including name of new file.
    signal : EBSD or LazyEBSD
        Signal instance.
    overwrite
        Whether to overwrite file or not if it already exists.
    add_scan
        Whether to add the signal to an already existing h5ebsd file or
        not. If the file does not exist the signal is written to a new
        file.
    **kwargs :
        Keyword arguments passed to the writer.
    """
    ext = os.path.splitext(filename)[1][1:]
    if ext == "":  # Will write to kikuchipy's h5ebsd format
        ext = "h5"
        filename = filename + "." + ext

    writer = None
    for plugin in plugins:
        if ext.lower() in plugin.file_extensions and plugin.writes:
            writer = plugin
            break

    if writer is None:
        raise ValueError(
            f"'{ext}' does not correspond to any supported format. Supported "
            f"file extensions are: '{strlist2enumeration(default_write_ext)}'"
        )
    else:
        sd = signal.axes_manager.signal_dimension
        nd = signal.axes_manager.navigation_dimension
        if writer.writes is not True and (sd, nd) not in writer.writes:
            # Get writers that can write this data
            writing_plugins = []
            for plugin in plugins:
                if (
                    plugin.writes is True
                    or plugin.writes is not False
                    and (sd, nd) in plugin.writes
                ):
                    writing_plugins.append(plugin)
            raise ValueError(
                "This file format cannot write this data. The following "
                f"formats can: {strlist2enumeration(writing_plugins)}"
            )

        _ensure_directory(filename)
        is_file = os.path.isfile(filename)

        # Check if we are to add signal to an already existing h5ebsd file
        if writer.format_name == "h5ebsd" and overwrite is not True and is_file:
            if add_scan is None:
                q = "Add scan to '{}' (y/n)?\n".format(filename)
                add_scan = _get_input_bool(q)
            if add_scan:
                overwrite = True  # So that the 2nd statement below triggers
            kwargs["add_scan"] = add_scan

        # Determine if signal is to be written to file or not
        if overwrite is None:
            write = overwrite_method(filename)  # Ask what to do
        elif overwrite is True or (overwrite is False and not is_file):
            write = True  # Write the file
        elif overwrite is False and is_file:
            write = False  # Don't write the file
        else:
            raise ValueError(
                "overwrite parameter can only be None, True or False, and "
                f"not {overwrite}"
            )

        # Finally, write file
        if write:
            writer.file_writer(filename, signal, **kwargs)
            directory, filename = os.path.split(os.path.abspath(filename))
            signal.tmp_parameters.set_item("folder", directory)
            signal.tmp_parameters.set_item(
                "filename", os.path.splitext(filename)[0]
            )
            signal.tmp_parameters.set_item("extension", ext)