# Copyright (C) 2015-2016 Tomasz Miasko
#               2020 Michael Nowotny
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

import deepdish as dd
import numpy as np
import typing as tp


def save_samples_dictionary_to_file(
        filename: str,
        samples: tp.Dict[str, np.ndarray],
        compression: bool = True):
    """
    This function saves a python dictionary of samples that has been generated
    by sample method of a model instance to an HDF5 file.

    Parameters
    ----------
    filename: the path the HDF5 file should be saved to
    samples: a dictionary mapping variable names to Numpy arrays with shape
             (parameter_dimension, chain_length, number_of_chains)
    compression: boolean indicating whether or not to use data compression

    """
    if compression:
        dd.io.save(filename, samples, compression='blosc')
    else:
        dd.io.save(filename, samples, compression=None)


def load_samples_dictionary_from_file(filename: str) \
        -> tp.Dict[str, np.ndarray]:
    """
    This function restores a saved a python dictionary of samples that has been
    generated by sample method of a model instance from an HDF5 file.

    Parameters
    ----------
    filename: the path the HDF5 file is located at

    Returns
    -------
    a dictionary mapping variable names to Numpy arrays with shape
             (parameter_dimension, chain_length, number_of_chains)
    """
    return dd.io.load(filename)
