# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Mathieu Blondel <mathieu@mblondel.org>
#          Olivier Grisel <olivier.grisel@ensta.org>
#          Andreas Mueller <amueller@ais.uni-bonn.de>
#          Eric Martin <eric@ericmart.in>
# License: BSD 3 clause

from itertools import chain, combinations
import numbers
import warnings

import numpy as np
from scipy import sparse

from ..base import BaseEstimator, TransformerMixin
from ..externals import six
from ..utils import check_array
from ..utils.extmath import row_norms
from ..utils.fixes import combinations_with_replacement as combinations_w_r
from ..utils.sparsefuncs_fast import (inplace_csr_row_normalize_l1,
                                      inplace_csr_row_normalize_l2)
from ..utils.sparsefuncs import (inplace_column_scale, mean_variance_axis,
                                 min_max_axis, inplace_row_scale)
from ..utils.validation import check_is_fitted, FLOAT_DTYPES

zip = six.moves.zip
map = six.moves.map
range = six.moves.range

__all__ = [
    'Binarizer',
    'KernelCenterer',
    'MinMaxScaler',
    'MaxAbsScaler',
    'Normalizer',
    'OneHotEncoder',
    'RobustScaler',
    'StandardScaler',
    'add_dummy_feature',
    'binarize',
    'normalize',
    'scale',
    'robust_scale',
    'maxabs_scale',
    'minmax_scale',
]

def _mean_and_std(X, axis=0, with_mean=True, with_std=True):
    """Compute mean and std deviation for centering, scaling.

    Zero valued std components are reset to 1.0 to avoid NaNs when scaling.
    """
    X = np.asarray(X)
    Xr = np.rollaxis(X, axis)

    if with_mean:
        mean_ = Xr.mean(axis=0)
    else:
        mean_ = None

    if with_std:
        std_ = Xr.std(axis=0)
        std_ = _handle_zeros_in_scale(std_)
    else:
        std_ = None

    return mean_, std_

def _handle_zeros_in_scale(scale):
    ''' Makes sure that whenever scale is zero, we handle it correctly.

    This happens in most scalers when we have constant features.'''

    # if we are fitting on 1D arrays, scale might be a scalar
    if np.isscalar(scale):
        if scale == 0:
            scale = 1.
    elif isinstance(scale, np.ndarray):
        scale[scale == 0.0] = 1.0
        scale[~np.isfinite(scale)] = 1.0
    return scale

def scale(X, axis=0, with_mean=True, with_std=True, copy=True):
    """Standardize a dataset along any axis

    Center to the mean and component wise scale to unit variance.

    Read more in the :ref:`User Guide <preprocessing_scaler>`.

    Parameters
    ----------
    X : array-like or CSR matrix.
        The data to center and scale.

    axis : int (0 by default)
        axis used to compute the means and standard deviations along. If 0,
        independently standardize each feature, otherwise (if 1) standardize
        each sample.

    with_mean : boolean, True by default
        If True, center the data before scaling.

    with_std : boolean, True by default
        If True, scale the data to unit variance (or equivalently,
        unit standard deviation).

    copy : boolean, optional, default True
        set to False to perform inplace row normalization and avoid a
        copy (if the input is already a numpy array or a scipy.sparse
        CSR matrix and if axis is 1).

    Notes
    -----
    This implementation will refuse to center scipy.sparse matrices
    since it would make them non-sparse and would potentially crash the
    program with memory exhaustion problems.

    Instead the caller is expected to either set explicitly
    `with_mean=False` (in that case, only variance scaling will be
    performed on the features of the CSR matrix) or to call `X.toarray()`
    if he/she expects the materialized dense array to fit in memory.

    To avoid memory copy the caller should pass a CSR matrix.

    See also
    --------
    :class:`sklearn.preprocessing.StandardScaler` to perform centering and
    scaling using the ``Transformer`` API (e.g. as part of a preprocessing
    :class:`sklearn.pipeline.Pipeline`)
    """
    X = check_array(X, accept_sparse='csr', copy=copy, ensure_2d=False,
                    warn_on_dtype=True, estimator='the scale function',
                    dtype=FLOAT_DTYPES)
    if sparse.issparse(X):
        if with_mean:
            raise ValueError(
                "Cannot center sparse matrices: pass `with_mean=False` instead"
                " See docstring for motivation and alternatives.")
        if axis != 0:
            raise ValueError("Can only scale sparse matrix on axis=0, "
                             " got axis=%d" % axis)
        if not sparse.isspmatrix_csr(X):
            X = X.tocsr()
            copy = False
        if copy:
            X = X.copy()
        _, var = mean_variance_axis(X, axis=0)
        var = _handle_zeros_in_scale(var)
        inplace_column_scale(X, 1 / np.sqrt(var))
    else:
        X = np.asarray(X)
        mean_, std_ = _mean_and_std(
            X, axis, with_mean=with_mean, with_std=with_std)
        if copy:
            X = X.copy()
        # Xr is a view on the original array that enables easy use of
        # broadcasting on the axis in which we are interested in
        Xr = np.rollaxis(X, axis)
        if with_mean:
            Xr -= mean_
            mean_1 = Xr.mean(axis=0)
            # Verify that mean_1 is 'close to zero'. If X contains very
            # large values, mean_1 can also be very large, due to a lack of
            # precision of mean_. In this case, a pre-scaling of the
            # concerned feature is efficient, for instance by its mean or
            # maximum.
            if not np.allclose(mean_1, 0):
                warnings.warn("Numerical issues were encountered "
                              "when centering the data "
                              "and might not be solved. Dataset may "
                              "contain too large values. You may need "
                              "to prescale your features.")
                Xr -= mean_1
        if with_std:
            Xr /= std_
            if with_mean:
                mean_2 = Xr.mean(axis=0)
                # If mean_2 is not 'close to zero', it comes from the fact that
                # std_ is very small so that mean_2 = mean_1/std_ > 0, even if
                # mean_1 was close to zero. The problem is thus essentially due
                # to the lack of precision of mean_. A solution is then to
                # substract the mean again:
                if not np.allclose(mean_2, 0):
                    warnings.warn("Numerical issues were encountered "
                                  "when scaling the data "
                                  "and might not be solved. The standard "
                                  "deviation of the data is probably "
                                  "very close to 0. ")
                    Xr -= mean_2
    return X

class MinMaxScaler(BaseEstimator, TransformerMixin):
    """Transforms features by scaling each feature to a given range.

    This estimator scales and translates each feature individually such
    that it is in the given range on the training set, i.e. between
    zero and one.

    The transformation is given by::

        X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
        X_scaled = X_std * (max - min) + min

    where min, max = feature_range.

    This transformation is often used as an alternative to zero mean,
    unit variance scaling.

    Read more in the :ref:`User Guide <preprocessing_scaler>`.

    Parameters
    ----------
    feature_range: tuple (min, max), default=(0, 1)
        Desired range of transformed data.

    copy : boolean, optional, default True
        Set to False to perform inplace row normalization and avoid a
        copy (if the input is already a numpy array).

    Attributes
    ----------
    min_ : ndarray, shape (n_features,)
        Per feature adjustment for minimum.

    scale_ : ndarray, shape (n_features,)
        Per feature relative scaling of the data.
    """

    def __init__(self, feature_range=(0, 1), copy=True):
        self.feature_range = feature_range
        self.copy = copy

    def fit(self, X, y=None):
        """Compute the minimum and maximum to be used for later scaling.

        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            The data used to compute the per-feature minimum and maximum
            used for later scaling along the features axis.
        """
        X = check_array(X, copy=self.copy, ensure_2d=False, warn_on_dtype=True,
                        estimator=self, dtype=FLOAT_DTYPES)
        feature_range = self.feature_range
        if feature_range[0] >= feature_range[1]:
            raise ValueError("Minimum of desired feature range must be smaller"
                             " than maximum. Got %s." % str(feature_range))
        data_min = np.min(X, axis=0)
        data_range = np.max(X, axis=0) - data_min
        data_range = _handle_zeros_in_scale(data_range)
        self.scale_ = (feature_range[1] - feature_range[0]) / data_range
        self.min_ = feature_range[0] - data_min * self.scale_
        self.data_range = data_range
        self.data_min = data_min
        return self

    def transform(self, X):
        """Scaling features of X according to feature_range.

        Parameters
        ----------
        X : array-like with shape [n_samples, n_features]
            Input data that will be transformed.
        """
        check_is_fitted(self, 'scale_')

        X = check_array(X, copy=self.copy, ensure_2d=False)
        X *= self.scale_
        X += self.min_
        return X

    def inverse_transform(self, X):
        """Undo the scaling of X according to feature_range.

        Parameters
        ----------
        X : array-like with shape [n_samples, n_features]
            Input data that will be transformed.
        """
        check_is_fitted(self, 'scale_')

        X = check_array(X, copy=self.copy, ensure_2d=False)
        X -= self.min_
        X /= self.scale_
        return X

def minmax_scale(X, feature_range=(0, 1), axis=0, copy=True):
    """Transforms features by scaling each feature to a given range.

    This estimator scales and translates each feature individually such
    that it is in the given range on the training set, i.e. between
    zero and one.

    The transformation is given by::

        X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
        X_scaled = X_std * (max - min) + min

    where min, max = feature_range.

    This transformation is often used as an alternative to zero mean,
    unit variance scaling.

    Read more in the :ref:`User Guide <preprocessing_scaler>`.

    Parameters
    ----------
    feature_range: tuple (min, max), default=(0, 1)
        Desired range of transformed data.

    axis : int (0 by default)
        axis used to scale along. If 0, independently scale each feature,
        otherwise (if 1) scale each sample.

    copy : boolean, optional, default is True
        Set to False to perform inplace scaling and avoid a copy (if the input
        is already a numpy array).
    """
    s = MinMaxScaler(feature_range=feature_range, copy=copy)
    if axis == 0:
        return s.fit_transform(X)
    else:
        return s.fit_transform(X.T).T

class StandardScaler(BaseEstimator, TransformerMixin):
    """Standardize features by removing the mean and scaling to unit variance

    Centering and scaling happen independently on each feature by computing
    the relevant statistics on the samples in the training set. Mean and
    standard deviation are then stored to be used on later data using the
    `transform` method.

    Standardization of a dataset is a common requirement for many
    machine learning estimators: they might behave badly if the
    individual feature do not more or less look like standard normally
    distributed data (e.g. Gaussian with 0 mean and unit variance).

    For instance many elements used in the objective function of
    a learning algorithm (such as the RBF kernel of Support Vector
    Machines or the L1 and L2 regularizers of linear models) assume that
    all features are centered around 0 and have variance in the same
    order. If a feature has a variance that is orders of magnitude larger
    that others, it might dominate the objective function and make the
    estimator unable to learn from other features correctly as expected.

    Read more in the :ref:`User Guide <preprocessing_scaler>`.

    Parameters
    ----------
    with_mean : boolean, True by default
        If True, center the data before scaling.
        This does not work (and will raise an exception) when attempted on
        sparse matrices, because centering them entails building a dense
        matrix which in common use cases is likely to be too large to fit in
        memory.

    with_std : boolean, True by default
        If True, scale the data to unit variance (or equivalently,
        unit standard deviation).

    copy : boolean, optional, default True
        If False, try to avoid a copy and do inplace scaling instead.
        This is not guaranteed to always work inplace; e.g. if the data is
        not a NumPy array or scipy.sparse CSR matrix, a copy may still be
        returned.

    Attributes
    ----------
    mean_ : array of floats with shape [n_features]
        The mean value for each feature in the training set.

    std_ : array of floats with shape [n_features]
        The standard deviation for each feature in the training set.
        Set to one if the standard deviation is zero for a given feature.

    See also
    --------
    :func:`sklearn.preprocessing.scale` to perform centering and
    scaling without using the ``Transformer`` object oriented API

    :class:`sklearn.decomposition.RandomizedPCA` with `whiten=True`
    to further remove the linear correlation across features.
    """

    def __init__(self, copy=True, with_mean=True, with_std=True):
        self.with_mean = with_mean
        self.with_std = with_std
        self.copy = copy

    def fit(self, X, y=None):
        """Compute the mean and std to be used for later scaling.

        Parameters
        ----------
        X : array-like or CSR matrix with shape [n_samples, n_features]
            The data used to compute the mean and standard deviation
            used for later scaling along the features axis.
        """
        X = check_array(X, accept_sparse='csr', copy=self.copy,
                        ensure_2d=False, warn_on_dtype=True,
                        estimator=self, dtype=FLOAT_DTYPES)
        if sparse.issparse(X):
            if self.with_mean:
                raise ValueError(
                    "Cannot center sparse matrices: pass `with_mean=False` "
                    "instead. See docstring for motivation and alternatives.")
            self.mean_ = None

            if self.with_std:
                var = mean_variance_axis(X, axis=0)[1]
                self.std_ = np.sqrt(var)
                self.std_ = _handle_zeros_in_scale(self.std_)
            else:
                self.std_ = None
            return self
        else:
            self.mean_, self.std_ = _mean_and_std(
                X, axis=0, with_mean=self.with_mean, with_std=self.with_std)
            return self

    def transform(self, X, y=None, copy=None):
        """Perform standardization by centering and scaling

        Parameters
        ----------
        X : array-like with shape [n_samples, n_features]
            The data used to scale along the features axis.
        """
        check_is_fitted(self, 'std_')

        copy = copy if copy is not None else self.copy
        X = check_array(X, accept_sparse='csr', copy=copy,
                        ensure_2d=False, warn_on_dtype=True,
                        estimator=self, dtype=FLOAT_DTYPES)
        if sparse.issparse(X):
            if self.with_mean:
                raise ValueError(
                    "Cannot center sparse matrices: pass `with_mean=False` "
                    "instead. See docstring for motivation and alternatives.")
            if self.std_ is not None:
                inplace_column_scale(X, 1 / self.std_)
        else:
            if self.with_mean:
                X -= self.mean_
            if self.with_std:
                X /= self.std_
        return X

    def inverse_transform(self, X, copy=None):
        """Scale back the data to the original representation

        Parameters
        ----------
        X : array-like with shape [n_samples, n_features]
            The data used to scale along the features axis.
        """
        check_is_fitted(self, 'std_')

        copy = copy if copy is not None else self.copy
        if sparse.issparse(X):
            if self.with_mean:
                raise ValueError(
                    "Cannot uncenter sparse matrices: pass `with_mean=False` "
                    "instead See docstring for motivation and alternatives.")
            if not sparse.isspmatrix_csr(X):
                X = X.tocsr()
                copy = False
            if copy:
                X = X.copy()
            if self.std_ is not None:
                inplace_column_scale(X, self.std_)
        else:
            X = np.asarray(X)
            if copy:
                X = X.copy()
            if self.with_std:
                X *= self.std_
            if self.with_mean:
                X += self.mean_
        return X

class MaxAbsScaler(BaseEstimator, TransformerMixin):
    """Scale each feature by its maximum absolute value.

    This estimator scales and translates each feature individually such
    that the maximal absolute value of each feature in the
    training set will be 1.0. It does not shift/center the data, and
    thus does not destroy any sparsity.

    This scaler can also be applied to sparse CSR or CSC matrices.

    Parameters
    ----------
    copy : boolean, optional, default is True
        Set to False to perform inplace scaling and avoid a copy (if the input
        is already a numpy array).

    Attributes
    ----------
    scale_ : ndarray, shape (n_features,)
        Per feature relative scaling of the data.
    """

    def __init__(self, copy=True):
        self.copy = copy

    def fit(self, X, y=None):
        """Compute the minimum and maximum to be used for later scaling.

        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            The data used to compute the per-feature minimum and maximum
            used for later scaling along the features axis.
        """
        X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy,
                        ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES)
        if sparse.issparse(X):
            mins, maxs = min_max_axis(X, axis=0)
            scales = np.maximum(np.abs(mins), np.abs(maxs))
        else:
            scales = np.abs(X).max(axis=0)
        scales = np.array(scales)
        scales = scales.reshape(-1)
        self.scale_ = _handle_zeros_in_scale(scales)
        return self

    def transform(self, X, y=None):
        """Scale the data

        Parameters
        ----------
        X : array-like or CSR matrix.
            The data that should be scaled.
        """
        check_is_fitted(self, 'scale_')
        X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy,
                        ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES)
        if sparse.issparse(X):
            if X.shape[0] == 1:
                inplace_row_scale(X, 1.0 / self.scale_)
            else:
                inplace_column_scale(X, 1.0 / self.scale_)
        else:
            X /= self.scale_
        return X

    def inverse_transform(self, X):
        """Scale back the data to the original representation

        Parameters
        ----------
        X : array-like or CSR matrix.
            The data that should be transformed back.
        """
        check_is_fitted(self, 'scale_')
        X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy,
                        ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES)
        if sparse.issparse(X):
            if X.shape[0] == 1:
                inplace_row_scale(X, self.scale_)
            else:
                inplace_column_scale(X, self.scale_)
        else:
            X *= self.scale_
        return X

def maxabs_scale(X, axis=0, copy=True):
    """Scale each feature to the [-1, 1] range without breaking the sparsity.

    This estimator scales each feature individually such
    that the maximal absolute value of each feature in the
    training set will be 1.0.

    This scaler can also be applied to sparse CSR or CSC matrices.

    Parameters
    ----------
    axis : int (0 by default)
        axis used to scale along. If 0, independently scale each feature,
        otherwise (if 1) scale each sample.

    copy : boolean, optional, default is True
        Set to False to perform inplace scaling and avoid a copy (if the input
        is already a numpy array).
    """
    s = MaxAbsScaler(copy=copy)
    if axis == 0:
        return s.fit_transform(X)
    else:
        return s.fit_transform(X.T).T

class RobustScaler(BaseEstimator, TransformerMixin):
    """Scale features using statistics that are robust to outliers.

    This Scaler removes the median and scales the data according to
    the Interquartile Range (IQR). The IQR is the range between the 1st
    quartile (25th quantile) and the 3rd quartile (75th quantile).

    Centering and scaling happen independently on each feature (or each
    sample, depending on the `axis` argument) by computing the relevant
    statistics on the samples in the training set. Median and  interquartile
    range are then stored to be used on later data using the `transform`
    method.

    Standardization of a dataset is a common requirement for many
    machine learning estimators. Typically this is done by removing the mean
    and scaling to unit variance. However, outliers can often influence the
    sample mean / variance in a negative way. In such cases, the median and
    the interquartile range often give better results.

    Read more in the :ref:`User Guide <preprocessing_scaler>`.

    Parameters
    ----------
    with_centering : boolean, True by default
        If True, center the data before scaling.
        This does not work (and will raise an exception) when attempted on
        sparse matrices, because centering them entails building a dense
        matrix which in common use cases is likely to be too large to fit in
        memory.

    with_scaling : boolean, True by default
        If True, scale the data to interquartile range.

    copy : boolean, optional, default is True
        If False, try to avoid a copy and do inplace scaling instead.
        This is not guaranteed to always work inplace; e.g. if the data is
        not a NumPy array or scipy.sparse CSR matrix, a copy may still be
        returned.

    Attributes
    ----------
    center_ : array of floats
        The median value for each feature in the training set.

    scale_ : array of floats
        The (scaled) interquartile range for each feature in the training set.

    See also
    --------
    :class:`sklearn.preprocessing.StandardScaler` to perform centering
    and scaling using mean and variance.

    :class:`sklearn.decomposition.RandomizedPCA` with `whiten=True`
    to further remove the linear correlation across features.

    Notes
    -----
    See examples/preprocessing/plot_robust_scaling.py for an example.

    http://en.wikipedia.org/wiki/Median_(statistics)
    http://en.wikipedia.org/wiki/Interquartile_range
    """

    def __init__(self, with_centering=True, with_scaling=True, copy=True):
        self.with_centering = with_centering
        self.with_scaling = with_scaling
        self.copy = copy

    def _check_array(self, X, copy):
        """Makes sure centering is not enabled for sparse matrices."""
        X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy,
                        ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES)
        if sparse.issparse(X):
            if self.with_centering:
                raise ValueError(
                    "Cannot center sparse matrices: use `with_centering=False`"
                    " instead. See docstring for motivation and alternatives.")
        return X

    def fit(self, X, y=None):
        """Compute the median and quantiles to be used for scaling.

        Parameters
        ----------
        X : array-like with shape [n_samples, n_features]
            The data used to compute the median and quantiles
            used for later scaling along the features axis.
        """
        if sparse.issparse(X):
            raise TypeError("RobustScaler cannot be fitted on sparse inputs")

        X = self._check_array(X, self.copy)
        if self.with_centering:
            self.center_ = np.median(X, axis=0)

        if self.with_scaling:
            q = np.percentile(X, (25, 75), axis=0)
            self.scale_ = (q[1] - q[0])
            self.scale_ = _handle_zeros_in_scale(self.scale_)
        return self

    def transform(self, X, y=None):
        """Center and scale the data

        Parameters
        ----------
        X : array-like or CSR matrix.
            The data used to scale along the specified axis.
        """
        if self.with_centering:
            check_is_fitted(self, 'center_')
        if self.with_scaling:
            check_is_fitted(self, 'scale_')
        X = self._check_array(X, self.copy)
        if sparse.issparse(X):
            if self.with_scaling:
                if X.shape[0] == 1:
                    inplace_row_scale(X, 1.0 / self.scale_)
                elif self.axis == 0:
                    inplace_column_scale(X, 1.0 / self.scale_)
        else:
            if self.with_centering:
                X -= self.center_
            if self.with_scaling:
                X /= self.scale_
        return X

    def inverse_transform(self, X):
        """Scale back the data to the original representation

        Parameters
        ----------
        X : array-like or CSR matrix.
            The data used to scale along the specified axis.
        """
        if self.with_centering:
            check_is_fitted(self, 'center_')
        if self.with_scaling:
            check_is_fitted(self, 'scale_')
        X = self._check_array(X, self.copy)
        if sparse.issparse(X):
            if self.with_scaling:
                if X.shape[0] == 1:
                    inplace_row_scale(X, self.scale_)
                else:
                    inplace_column_scale(X, self.scale_)
        else:
            if self.with_scaling:
                X *= self.scale_
            if self.with_centering:
                X += self.center_
        return X

def robust_scale(X, axis=0, with_centering=True, with_scaling=True, copy=True):
    """Standardize a dataset along any axis

    Center to the median and component wise scale
    according to the interquartile range.

    Read more in the :ref:`User Guide <preprocessing_scaler>`.

    Parameters
    ----------
    X : array-like.
        The data to center and scale.

    axis : int (0 by default)
        axis used to compute the medians and IQR along. If 0,
        independently scale each feature, otherwise (if 1) scale
        each sample.

    with_centering : boolean, True by default
        If True, center the data before scaling.

    with_scaling : boolean, True by default
        If True, scale the data to unit variance (or equivalently,
        unit standard deviation).

    copy : boolean, optional, default is True
        set to False to perform inplace row normalization and avoid a
        copy (if the input is already a numpy array or a scipy.sparse
        CSR matrix and if axis is 1).

    Notes
    -----
    This implementation will refuse to center scipy.sparse matrices
    since it would make them non-sparse and would potentially crash the
    program with memory exhaustion problems.

    Instead the caller is expected to either set explicitly
    `with_centering=False` (in that case, only variance scaling will be
    performed on the features of the CSR matrix) or to call `X.toarray()`
    if he/she expects the materialized dense array to fit in memory.

    To avoid memory copy the caller should pass a CSR matrix.

    See also
    --------
    :class:`sklearn.preprocessing.RobustScaler` to perform centering and
    scaling using the ``Transformer`` API (e.g. as part of a preprocessing
    :class:`sklearn.pipeline.Pipeline`)
    """
    s = RobustScaler(with_centering=with_centering, with_scaling=with_scaling,
                     copy=copy)
    if axis == 0:
        return s.fit_transform(X)
    else:
        return s.fit_transform(X.T).T

class PolynomialFeatures(BaseEstimator, TransformerMixin):
    """Generate polynomial and interaction features.

    Generate a new feature matrix consisting of all polynomial combinations
    of the features with degree less than or equal to the specified degree.
    For example, if an input sample is two dimensional and of the form
    [a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2].

    Parameters
    ----------
    degree : integer
        The degree of the polynomial features. Default = 2.

    interaction_only : boolean, default = False
        If true, only interaction features are produced: features that are
        products of at most ``degree`` *distinct* input features (so not
        ``x[1] ** 2``, ``x[0] * x[2] ** 3``, etc.).

    include_bias : boolean
        If True (default), then include a bias column, the feature in which
        all polynomial powers are zero (i.e. a column of ones - acts as an
        intercept term in a linear model).

    Examples
    --------
    >>> X = np.arange(6).reshape(3, 2)
    >>> X
    array([[0, 1],
           [2, 3],
           [4, 5]])
    >>> poly = PolynomialFeatures(2)
    >>> poly.fit_transform(X)
    array([[ 1,  0,  1,  0,  0,  1],
           [ 1,  2,  3,  4,  6,  9],
           [ 1,  4,  5, 16, 20, 25]])
    >>> poly = PolynomialFeatures(interaction_only=True)
    >>> poly.fit_transform(X)
    array([[ 1,  0,  1,  0],
           [ 1,  2,  3,  6],
           [ 1,  4,  5, 20]])

    Attributes
    ----------
    powers_ : array, shape (n_input_features, n_output_features)
        powers_[i, j] is the exponent of the jth input in the ith output.

    n_input_features_ : int
        The total number of input features.

    n_output_features_ : int
        The total number of polynomial output features. The number of output
        features is computed by iterating over all suitably sized combinations
        of input features.

    Notes
    -----
    Be aware that the number of features in the output array scales
    polynomially in the number of features of the input array, and
    exponentially in the degree. High degrees can cause overfitting.

    See :ref:`examples/linear_model/plot_polynomial_interpolation.py
    <example_linear_model_plot_polynomial_interpolation.py>`
    """
    def __init__(self, degree=2, interaction_only=False, include_bias=True):
        self.degree = degree
        self.interaction_only = interaction_only
        self.include_bias = include_bias

    @staticmethod
    def _combinations(n_features, degree, interaction_only, include_bias):
        comb = (combinations if interaction_only else combinations_w_r)
        start = int(not include_bias)
        return chain.from_iterable(comb(range(n_features), i)
                                   for i in range(start, degree + 1))

    @property
    def powers_(self):
        check_is_fitted(self, 'n_input_features_')

        combinations = self._combinations(self.n_input_features_, self.degree,
                                          self.interaction_only,
                                          self.include_bias)
        return np.vstack(np.bincount(c, minlength=self.n_input_features_)
                         for c in combinations)

    def fit(self, X, y=None):
        """
        Compute number of output features.
        """
        n_samples, n_features = check_array(X).shape
        combinations = self._combinations(n_features, self.degree,
                                          self.interaction_only,
                                          self.include_bias)
        self.n_input_features_ = n_features
        self.n_output_features_ = sum(1 for _ in combinations)
        return self

    def transform(self, X, y=None):
        """Transform data to polynomial features

        Parameters
        ----------
        X : array with shape [n_samples, n_features]
            The data to transform, row by row.

        Returns
        -------
        XP : np.ndarray shape [n_samples, NP]
            The matrix of features, where NP is the number of polynomial
            features generated from the combination of inputs.
        """
        check_is_fitted(self, ['n_input_features_', 'n_output_features_'])

        X = check_array(X)
        n_samples, n_features = X.shape

        if n_features != self.n_input_features_:
            raise ValueError("X shape does not match training shape")

        # allocate output data
        XP = np.empty((n_samples, self.n_output_features_), dtype=X.dtype)

        combinations = self._combinations(n_features, self.degree,
                                          self.interaction_only,
                                          self.include_bias)
        for i, c in enumerate(combinations):
            XP[:, i] = X[:, c].prod(1)

        return XP

def normalize(X, norm='l2', axis=1, copy=True):
    """Scale input vectors individually to unit norm (vector length).

    Read more in the :ref:`User Guide <preprocessing_normalization>`.

    Parameters
    ----------
    X : array or scipy.sparse matrix with shape [n_samples, n_features]
        The data to normalize, element by element.
        scipy.sparse matrices should be in CSR format to avoid an
        un-necessary copy.

    norm : 'l1', 'l2', or 'max', optional ('l2' by default)
        The norm to use to normalize each non zero sample (or each non-zero
        feature if axis is 0).

    axis : 0 or 1, optional (1 by default)
        axis used to normalize the data along. If 1, independently normalize
        each sample, otherwise (if 0) normalize each feature.

    copy : boolean, optional, default True
        set to False to perform inplace row normalization and avoid a
        copy (if the input is already a numpy array or a scipy.sparse
        CSR matrix and if axis is 1).

    See also
    --------
    :class:`sklearn.preprocessing.Normalizer` to perform normalization
    using the ``Transformer`` API (e.g. as part of a preprocessing
    :class:`sklearn.pipeline.Pipeline`)
    """
    if norm not in ('l1', 'l2', 'max'):
        raise ValueError("'%s' is not a supported norm" % norm)

    if axis == 0:
        sparse_format = 'csc'
    elif axis == 1:
        sparse_format = 'csr'
    else:
        raise ValueError("'%d' is not a supported axis" % axis)

    X = check_array(X, sparse_format, copy=copy, warn_on_dtype=True,
                    estimator='the normalize function', dtype=FLOAT_DTYPES)
    if axis == 0:
        X = X.T

    if sparse.issparse(X):
        if norm == 'l1':
            inplace_csr_row_normalize_l1(X)
        elif norm == 'l2':
            inplace_csr_row_normalize_l2(X)
        elif norm == 'max':
            _, norms = min_max_axis(X, 1)
            norms = norms.repeat(np.diff(X.indptr))
            mask = norms != 0
            X.data[mask] /= norms[mask]
    else:
        if norm == 'l1':
            norms = np.abs(X).sum(axis=1)
        elif norm == 'l2':
            norms = row_norms(X)
        elif norm == 'max':
            norms = np.max(X, axis=1)
        norms = _handle_zeros_in_scale(norms)
        X /= norms[:, np.newaxis]

    if axis == 0:
        X = X.T

    return X

class Normalizer(BaseEstimator, TransformerMixin):
    """Normalize samples individually to unit norm.

    Each sample (i.e. each row of the data matrix) with at least one
    non zero component is rescaled independently of other samples so
    that its norm (l1 or l2) equals one.

    This transformer is able to work both with dense numpy arrays and
    scipy.sparse matrix (use CSR format if you want to avoid the burden of
    a copy / conversion).

    Scaling inputs to unit norms is a common operation for text
    classification or clustering for instance. For instance the dot
    product of two l2-normalized TF-IDF vectors is the cosine similarity
    of the vectors and is the base similarity metric for the Vector
    Space Model commonly used by the Information Retrieval community.

    Read more in the :ref:`User Guide <preprocessing_normalization>`.

    Parameters
    ----------
    norm : 'l1', 'l2', or 'max', optional ('l2' by default)
        The norm to use to normalize each non zero sample.

    copy : boolean, optional, default True
        set to False to perform inplace row normalization and avoid a
        copy (if the input is already a numpy array or a scipy.sparse
        CSR matrix).

    Notes
    -----
    This estimator is stateless (besides constructor parameters), the
    fit method does nothing but is useful when used in a pipeline.

    See also
    --------
    :func:`sklearn.preprocessing.normalize` equivalent function
    without the object oriented API
    """

    def __init__(self, norm='l2', copy=True):
        self.norm = norm
        self.copy = copy

    def fit(self, X, y=None):
        """Do nothing and return the estimator unchanged

        This method is just there to implement the usual API and hence
        work in pipelines.
        """
        X = check_array(X, accept_sparse='csr')
        return self

    def transform(self, X, y=None, copy=None):
        """Scale each non zero row of X to unit norm

        Parameters
        ----------
        X : array or scipy.sparse matrix with shape [n_samples, n_features]
            The data to normalize, row by row. scipy.sparse matrices should be
            in CSR format to avoid an un-necessary copy.
        """
        copy = copy if copy is not None else self.copy
        X = check_array(X, accept_sparse='csr')
        return normalize(X, norm=self.norm, axis=1, copy=copy)

def binarize(X, threshold=0.0, copy=True):
    """Boolean thresholding of array-like or scipy.sparse matrix

    Read more in the :ref:`User Guide <preprocessing_binarization>`.

    Parameters
    ----------
    X : array or scipy.sparse matrix with shape [n_samples, n_features]
        The data to binarize, element by element.
        scipy.sparse matrices should be in CSR or CSC format to avoid an
        un-necessary copy.

    threshold : float, optional (0.0 by default)
        Feature values below or equal to this are replaced by 0, above it by 1.
        Threshold may not be less than 0 for operations on sparse matrices.

    copy : boolean, optional, default True
        set to False to perform inplace binarization and avoid a copy
        (if the input is already a numpy array or a scipy.sparse CSR / CSC
        matrix and if axis is 1).

    See also
    --------
    :class:`sklearn.preprocessing.Binarizer` to perform binarization
    using the ``Transformer`` API (e.g. as part of a preprocessing
    :class:`sklearn.pipeline.Pipeline`)
    """
    X = check_array(X, accept_sparse=['csr', 'csc'], copy=copy)
    if sparse.issparse(X):
        if threshold < 0:
            raise ValueError('Cannot binarize a sparse matrix with threshold '
                             '< 0')
        cond = X.data > threshold
        not_cond = np.logical_not(cond)
        X.data[cond] = 1
        X.data[not_cond] = 0
        X.eliminate_zeros()
    else:
        cond = X > threshold
        not_cond = np.logical_not(cond)
        X[cond] = 1
        X[not_cond] = 0
    return X

class Binarizer(BaseEstimator, TransformerMixin):
    """Binarize data (set feature values to 0 or 1) according to a threshold

    Values greater than the threshold map to 1, while values less than
    or equal to the threshold map to 0. With the default threshold of 0,
    only positive values map to 1.

    Binarization is a common operation on text count data where the
    analyst can decide to only consider the presence or absence of a
    feature rather than a quantified number of occurrences for instance.

    It can also be used as a pre-processing step for estimators that
    consider boolean random variables (e.g. modelled using the Bernoulli
    distribution in a Bayesian setting).

    Read more in the :ref:`User Guide <preprocessing_binarization>`.

    Parameters
    ----------
    threshold : float, optional (0.0 by default)
        Feature values below or equal to this are replaced by 0, above it by 1.
        Threshold may not be less than 0 for operations on sparse matrices.

    copy : boolean, optional, default True
        set to False to perform inplace binarization and avoid a copy (if
        the input is already a numpy array or a scipy.sparse CSR matrix).

    Notes
    -----
    If the input is a sparse matrix, only the non-zero values are subject
    to update by the Binarizer class.

    This estimator is stateless (besides constructor parameters), the
    fit method does nothing but is useful when used in a pipeline.
    """

    def __init__(self, threshold=0.0, copy=True):
        self.threshold = threshold
        self.copy = copy

    def fit(self, X, y=None):
        """Do nothing and return the estimator unchanged

        This method is just there to implement the usual API and hence
        work in pipelines.
        """
        check_array(X, accept_sparse='csr')
        return self

    def transform(self, X, y=None, copy=None):
        """Binarize each element of X

        Parameters
        ----------
        X : array or scipy.sparse matrix with shape [n_samples, n_features]
            The data to binarize, element by element.
            scipy.sparse matrices should be in CSR format to avoid an
            un-necessary copy.
        """
        copy = copy if copy is not None else self.copy
        return binarize(X, threshold=self.threshold, copy=copy)

class KernelCenterer(BaseEstimator, TransformerMixin):
    """Center a kernel matrix

    Let K(x, z) be a kernel defined by phi(x)^T phi(z), where phi is a
    function mapping x to a Hilbert space. KernelCenterer centers (i.e.,
    normalize to have zero mean) the data without explicitly computing phi(x).
    It is equivalent to centering phi(x) with
    sklearn.preprocessing.StandardScaler(with_std=False).

    Read more in the :ref:`User Guide <kernel_centering>`.
    """

    def fit(self, K, y=None):
        """Fit KernelCenterer

        Parameters
        ----------
        K : numpy array of shape [n_samples, n_samples]
            Kernel matrix.

        Returns
        -------
        self : returns an instance of self.
        """
        K = check_array(K)
        n_samples = K.shape[0]
        self.K_fit_rows_ = np.sum(K, axis=0) / n_samples
        self.K_fit_all_ = self.K_fit_rows_.sum() / n_samples
        return self

    def transform(self, K, y=None, copy=True):
        """Center kernel matrix.

        Parameters
        ----------
        K : numpy array of shape [n_samples1, n_samples2]
            Kernel matrix.

        copy : boolean, optional, default True
            Set to False to perform inplace computation.

        Returns
        -------
        K_new : numpy array of shape [n_samples1, n_samples2]
        """
        check_is_fitted(self, 'K_fit_all_')

        K = check_array(K)
        if copy:
            K = K.copy()

        K_pred_cols = (np.sum(K, axis=1) /
                       self.K_fit_rows_.shape[0])[:, np.newaxis]

        K -= self.K_fit_rows_
        K -= K_pred_cols
        K += self.K_fit_all_

        return K

def add_dummy_feature(X, value=1.0):
    """Augment dataset with an additional dummy feature.

    This is useful for fitting an intercept term with implementations which
    cannot otherwise fit it directly.

    Parameters
    ----------
    X : array or scipy.sparse matrix with shape [n_samples, n_features]
        Data.

    value : float
        Value to use for the dummy feature.

    Returns
    -------

    X : array or scipy.sparse matrix with shape [n_samples, n_features + 1]
        Same data with dummy feature added as first column.

    Examples
    --------

    >>> from sklearn.preprocessing import add_dummy_feature
    >>> add_dummy_feature([[0, 1], [1, 0]])
    array([[ 1.,  0.,  1.],
           [ 1.,  1.,  0.]])
    """
    X = check_array(X, accept_sparse=['csc', 'csr', 'coo'])
    n_samples, n_features = X.shape
    shape = (n_samples, n_features + 1)
    if sparse.issparse(X):
        if sparse.isspmatrix_coo(X):
            # Shift columns to the right.
            col = X.col + 1
            # Column indices of dummy feature are 0 everywhere.
            col = np.concatenate((np.zeros(n_samples), col))
            # Row indices of dummy feature are 0, ..., n_samples-1.
            row = np.concatenate((np.arange(n_samples), X.row))
            # Prepend the dummy feature n_samples times.
            data = np.concatenate((np.ones(n_samples) * value, X.data))
            return sparse.coo_matrix((data, (row, col)), shape)
        elif sparse.isspmatrix_csc(X):
            # Shift index pointers since we need to add n_samples elements.
            indptr = X.indptr + n_samples
            # indptr[0] must be 0.
            indptr = np.concatenate((np.array([0]), indptr))
            # Row indices of dummy feature are 0, ..., n_samples-1.
            indices = np.concatenate((np.arange(n_samples), X.indices))
            # Prepend the dummy feature n_samples times.
            data = np.concatenate((np.ones(n_samples) * value, X.data))
            return sparse.csc_matrix((data, indices, indptr), shape)
        else:
            klass = X.__class__
            return klass(add_dummy_feature(X.tocoo(), value))
    else:
        return np.hstack((np.ones((n_samples, 1)) * value, X))

def _transform_selected(X, transform, selected="all", copy=True):
    """Apply a transform function to portion of selected features

    Parameters
    ----------
    X : array-like or sparse matrix, shape=(n_samples, n_features)
        Dense array or sparse matrix.

    transform : callable
        A callable transform(X) -> X_transformed

    copy : boolean, optional
        Copy X even if it could be avoided.

    selected: "all" or array of indices or mask
        Specify which features to apply the transform to.

    Returns
    -------
    X : array or sparse matrix, shape=(n_samples, n_features_new)
    """
    if selected == "all":
        return transform(X)

    X = check_array(X, accept_sparse='csc', copy=copy)

    if len(selected) == 0:
        return X

    n_features = X.shape[1]
    ind = np.arange(n_features)
    sel = np.zeros(n_features, dtype=bool)
    sel[np.asarray(selected)] = True
    not_sel = np.logical_not(sel)
    n_selected = np.sum(sel)

    if n_selected == 0:
        # No features selected.
        return X
    elif n_selected == n_features:
        # All features selected.
        return transform(X)
    else:
        X_sel = transform(X[:, ind[sel]])
        X_not_sel = X[:, ind[not_sel]]

        if sparse.issparse(X_sel) or sparse.issparse(X_not_sel):
            return sparse.hstack((X_sel, X_not_sel))
        else:
            return np.hstack((X_sel, X_not_sel))

class OneHotEncoder(BaseEstimator, TransformerMixin):
    """Encode categorical integer features using a one-hot aka one-of-K scheme.

    The input to this transformer should be a matrix of integers, denoting
    the values taken on by categorical (discrete) features. The output will be
    a sparse matrix where each column corresponds to one possible value of one
    feature. It is assumed that input features take on values in the range
    [0, n_values).

    This encoding is needed for feeding categorical data to many scikit-learn
    estimators, notably linear models and SVMs with the standard kernels.

    Read more in the :ref:`User Guide <preprocessing_categorical_features>`.

    Parameters
    ----------
    n_values : 'auto', int or array of ints
        Number of values per feature.

        - 'auto' : determine value range from training data.
        - int : maximum value for all features.
        - array : maximum value per feature.

    categorical_features: "all" or array of indices or mask
        Specify what features are treated as categorical.

        - 'all' (default): All features are treated as categorical.
        - array of indices: Array of categorical feature indices.
        - mask: Array of length n_features and with dtype=bool.

        Non-categorical features are always stacked to the right of the matrix.

    dtype : number type, default=np.float
        Desired dtype of output.

    sparse : boolean, default=True
        Will return sparse matrix if set True else will return an array.

    handle_unknown : str, 'error' or 'ignore'
        Whether to raise an error or ignore if a unknown categorical feature is
        present during transform.

    Attributes
    ----------
    active_features_ : array
        Indices for active features, meaning values that actually occur
        in the training set. Only available when n_values is ``'auto'``.

    feature_indices_ : array of shape (n_features,)
        Indices to feature ranges.
        Feature ``i`` in the original data is mapped to features
        from ``feature_indices_[i]`` to ``feature_indices_[i+1]``
        (and then potentially masked by `active_features_` afterwards)

    n_values_ : array of shape (n_features,)
        Maximum number of values per feature.

    Examples
    --------
    Given a dataset with three features and two samples, we let the encoder
    find the maximum value per feature and transform the data to a binary
    one-hot encoding.

    >>> from sklearn.preprocessing import OneHotEncoder
    >>> enc = OneHotEncoder()
    >>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], \
[1, 0, 2]])  # doctest: +ELLIPSIS
    OneHotEncoder(categorical_features='all', dtype=<... 'float'>,
           handle_unknown='error', n_values='auto', sparse=True)
    >>> enc.n_values_
    array([2, 3, 4])
    >>> enc.feature_indices_
    array([0, 2, 5, 9])
    >>> enc.transform([[0, 1, 1]]).toarray()
    array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])

    See also
    --------
    sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding of
      dictionary items (also handles string-valued features).
    sklearn.feature_extraction.FeatureHasher : performs an approximate one-hot
      encoding of dictionary items or strings.
    """
    def __init__(self, n_values="auto", categorical_features="all",
                 dtype=np.float, sparse=True, handle_unknown='error'):
        self.n_values = n_values
        self.categorical_features = categorical_features
        self.dtype = dtype
        self.sparse = sparse
        self.handle_unknown = handle_unknown

    def fit(self, X, y=None):
        """Fit OneHotEncoder to X.

        Parameters
        ----------
        X : array-like, shape=(n_samples, n_feature)
            Input array of type int.

        Returns
        -------
        self
        """
        self.fit_transform(X)
        return self

    def _fit_transform(self, X):
        """Assumes X contains only categorical features."""
        X = check_array(X, dtype=np.int)
        if np.any(X < 0):
            raise ValueError("X needs to contain only non-negative integers.")
        n_samples, n_features = X.shape
        if self.n_values == 'auto':
            n_values = np.max(X, axis=0) + 1
        elif isinstance(self.n_values, numbers.Integral):
            if (np.max(X, axis=0) >= self.n_values).any():
                raise ValueError("Feature out of bounds for n_values=%d"
                                 % self.n_values)
            n_values = np.empty(n_features, dtype=np.int)
            n_values.fill(self.n_values)
        else:
            try:
                n_values = np.asarray(self.n_values, dtype=int)
            except (ValueError, TypeError):
                raise TypeError("Wrong type for parameter `n_values`. Expected"
                                " 'auto', int or array of ints, got %r"
                                % type(X))
            if n_values.ndim < 1 or n_values.shape[0] != X.shape[1]:
                raise ValueError("Shape mismatch: if n_values is an array,"
                                 " it has to be of shape (n_features,).")

        self.n_values_ = n_values
        n_values = np.hstack([[0], n_values])
        indices = np.cumsum(n_values)
        self.feature_indices_ = indices

        column_indices = (X + indices[:-1]).ravel()
        row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),
                                n_features)
        data = np.ones(n_samples * n_features)
        out = sparse.coo_matrix((data, (row_indices, column_indices)),
                                shape=(n_samples, indices[-1]),
                                dtype=self.dtype).tocsr()

        if self.n_values == 'auto':
            mask = np.array(out.sum(axis=0)).ravel() != 0
            active_features = np.where(mask)[0]
            out = out[:, active_features]
            self.active_features_ = active_features

        return out if self.sparse else out.toarray()

    def fit_transform(self, X, y=None):
        """Fit OneHotEncoder to X, then transform X.

        Equivalent to self.fit(X).transform(X), but more convenient and more
        efficient. See fit for the parameters, transform for the return value.
        """
        return _transform_selected(X, self._fit_transform,
                                   self.categorical_features, copy=True)

    def _transform(self, X):
        """Assumes X contains only categorical features."""
        X = check_array(X, dtype=np.int)
        if np.any(X < 0):
            raise ValueError("X needs to contain only non-negative integers.")
        n_samples, n_features = X.shape

        indices = self.feature_indices_
        if n_features != indices.shape[0] - 1:
            raise ValueError("X has different shape than during fitting."
                             " Expected %d, got %d."
                             % (indices.shape[0] - 1, n_features))

        # We use only those catgorical features of X that are known using fit.
        # i.e lesser than n_values_ using mask.
        # This means, if self.handle_unknown is "ignore", the row_indices and
        # col_indices corresponding to the unknown categorical feature are
        # ignored.
        mask = (X < self.n_values_).ravel()
        if np.any(~mask):
            if self.handle_unknown not in ['error', 'ignore']:
                raise ValueError("handle_unknown should be either error or "
                                 "unknown got %s" % self.handle_unknown)
            if self.handle_unknown == 'error':
                raise ValueError("unknown categorical feature present %s "
                                 "during transform." % X[~mask])

        column_indices = (X + indices[:-1]).ravel()[mask]
        row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),
                                n_features)[mask]
        data = np.ones(np.sum(mask))
        out = sparse.coo_matrix((data, (row_indices, column_indices)),
                                shape=(n_samples, indices[-1]),
                                dtype=self.dtype).tocsr()
        if self.n_values == 'auto':
            out = out[:, self.active_features_]

        return out if self.sparse else out.toarray()

    def transform(self, X):
        """Transform X using one-hot encoding.

        Parameters
        ----------
        X : array-like, shape=(n_samples, n_features)
            Input array of type int.

        Returns
        -------
        X_out : sparse matrix if sparse=True else a 2-d array, dtype=int
            Transformed input.
        """
        return _transform_selected(X, self._transform,
                                   self.categorical_features, copy=True)


#=====================================================================================================================================
#Copyright
#=====================================================================================================================================

#Copyright (C) 2014 Alexander Blaessle, Patrick Mueller and the Friedrich Miescher Laboratory of the Max Planck Society
#This software is distributed under the terms of the GNU General Public License.

#This file is part of PyFRAP.

#PyFRAP is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#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.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

#===========================================================================================================================================================================
#Module Description
#===========================================================================================================================================================================

"""Optimization module for PyFRAP toolbox.

Currently contains all functions necessary to transform a constrained FRAP optimization problem into
a unconstrained one, making it suitable to Nelder-Mead optimization algorithm.

"""

#===========================================================================================================================================================================
#Importing necessary modules
#===========================================================================================================================================================================

#Numpy/Scipy
import numpy as np

#PyFRAP
import pyfrp_fit_module

from pyfrp_term_module import *

#===========================================================================================================================================================================
#Module Functions
#===========================================================================================================================================================================

def constrObjFunc(x,fit,debug,ax,returnFit):

	"""Objective function when using Constrained Nelder-Mead.

	Calls :py:func:`pyfrp.modules.pyfrp_optimization_module.xTransform` to transform x into
	constrained version, then uses :py:func:`pyfrp.modules.pyfrp_fit_module.FRAPObjFunc` to
	find SSD.

	Args:
		x (list): Input vector, consiting of [D,(prod),(degr)].
		fit (pyfrp.subclasses.pyfrp_fit): Fit object.
		debug (bool): Display debugging output and plots.
		ax (matplotlib.axes): Axes to display plots in.
		returnFit (bool): Return fit instead of SSD.

	Returns:
		 float: SSD of fit. Except ``returnFit==True``, then will return fit itself.
	"""

	LBs, UBs = buildBoundLists(fit)

	x=xTransform(x,LBs,UBs)

	ssd=pyfrp_fit_module.FRAPObjFunc(x,fit,debug,ax,returnFit)

	return ssd

def xTransform(x,LB,UB):

	"""Transforms ``x`` into constrained form, obeying upper
	bounds ``UB`` and lower bounds ``LB``.

	.. note:: Will add tiny offset to LB(D), to avoid singularities.

	Idea taken from http://www.mathworks.com/matlabcentral/fileexchange/8277-fminsearchbnd--fminsearchcon

	Args:
		x (list): Input vector, consiting of [D,(prod),(degr)].
		LB (list): List of lower bounds for ``D,prod,degr``.
		UB (list): List of upper bounds for ``D,prod,degr``.

	Returns:
		list: Transformed x-values.
	"""

	#Make sure everything is float
	x=np.asarray(x,dtype=np.float64)
	LB=np.asarray(LB,dtype=np.float64)
	UB=np.asarray(UB,dtype=np.float64)

	#Check if LB_D==0, then add a little noise to it so we do not end up with xtrans[D]==0 and later have singularities when scaling tvec
	if LB[0]==0:
		LB[0]=1E-10

	#Determine number of parameters to be fitted
	nparams=len(x)

	#Make empty vector
	xtrans = np.zeros(np.shape(x))

	# k allows some variables to be fixed, thus dropped from the
	# optimization.
	k=0

	for i in range(nparams):

		#Upper bound only
		if UB[i]!=None and LB[i]==None:

			xtrans[i]=UB[i]-x[k]**2
			k=k+1

		#Lower bound only
		elif UB[i]==None and LB[i]!=None:

			xtrans[i]=LB[i]+x[k]**2
			k=k+1

		#Both bounds
		elif UB[i]!=None and LB[i]!=None:

			xtrans[i] = (np.sin(x[k])+1.)/2.*(UB[i] - LB[i]) + LB[i]
			xtrans[i] = max([LB[i],min([UB[i],xtrans[i]])])
			k=k+1

		#No bounds
		elif UB[i]==None and LB[i]==None:

			xtrans[i] = x[k]
			k=k+1

		#Note: The original file has here another case for fixed variable, but since we made the decision earlier which when we call frap_fitting, we don't need this here.

	return xtrans

def transformX0(x0,LB,UB):

	"""Transforms ``x0`` into constrained form, obeying upper
	bounds ``UB`` and lower bounds ``LB``.

	Idea taken from http://www.mathworks.com/matlabcentral/fileexchange/8277-fminsearchbnd--fminsearchcon

	Args:
		x0 (list): Input initial vector, consiting of [D,(prod),(degr)].
		LB (list): List of lower bounds for ``D,prod,degr``.
		UB (list): List of upper bounds for ``D,prod,degr``.

	Returns:
		list: Transformed x-values.
	"""

	x0u = list(x0)

	nparams=len(x0)

	k=0
	for i in range(nparams):

		#Upper bound only
		if UB[i]!=None and LB[i]==None:
			if UB[i]<=x0[i]:
				x0u[k]=0
			else:
				x0u[k]=sqrt(UB[i]-x0[i])
			k=k+1

		#Lower bound only
		elif UB[i]==None and LB[i]!=None:
			if LB[i]>=x0[i]:
				x0u[k]=0
			else:
				x0u[k]=np.sqrt(x0[i]-LB[i])
			k=k+1

		#Both bounds
		elif UB[i]!=None and LB[i]!=None:
			if UB[i]<=x0[i]:
				x0u[k]=np.pi/2
			elif LB[i]>=x0[i]:
				x0u[k]=-np.pi/2
			else:
				x0u[k] = 2*(x0[i] - LB[i])/(UB[i]-LB[i]) - 1;
				#shift by 2*pi to avoid problems at zero in fminsearch otherwise, the initial simplex is vanishingly small
				x0u[k] = 2*np.pi+np.arcsin(max([-1,min(1,x0u[k])]));
			k=k+1

		#No bounds
		elif UB[i]==None and LB[i]==None:
			x0u[k] = x[i]
			k=k+1

	return x0u

def buildBoundLists(fit):

	"""Builds list of lower bounds and upper bounds.

	Args:
		fit (pyfrp.subclasses.pyfrp_fit): Fit object.

	Returns:
		tuple: Tuple containing:

			* LBs (list): List of lower bounds.
			* UBs (list): List of upper bounds.

	"""

	LBs=[fit.LBD]+int(fit.fitProd)*[fit.LBProd]+int(fit.fitDegr)*[fit.LBDegr]+len(fit.ROIsFitted)*[fit.LBEqu]
	UBs=[fit.UBD]+int(fit.fitProd)*[fit.UBProd]+int(fit.fitDegr)*[fit.UBDegr]+len(fit.ROIsFitted)*[fit.UBEqu]

	return LBs,UBs


from oldowan.mtconvert import seq2sites, sites2seq, str2sites
from string import translate
import pandas as pd
import sys

sys.path.append('../../scripts')
from utils import *

## load metadata
metadata = pd.read_csv('metadata.csv', index_col=0)

regionparts = metadata.ix[0,'SeqRange'].split(';')
region1 = range2region(regionparts[0])
region2 = range2region(regionparts[1])

with open('coelho2009_haplotypes.csv', 'rU') as f:
	f.readline() # skip past header
	data = f.readlines()

hids = []
hvr1sites = []
hvr2sites = []

for l in data:
	parts = l.strip().split(',')
	if int(parts[3]) == 377 and int(parts[7]) == 268:
		hids.append(parts[0])
		hvr1sites.append(parts[4])
		hvr2sites.append(parts[8])

## need to preprocess sites data for some nonstandard notation in hvr2
hvr1 = []
hvr2 = []
for i in range(len(hids)):
	s1 = str2sites(hvr1sites[i], add16k=True)
	hvr1.append(s1)

	s2 = hvr2sites[i].split()
	s2new = []
	for j in range(len(s2)):
		if s2[j].endswith('.2C'):
			parts = s2[j].split('.')
			s2new.append('%s.1C' % parts[0])
			s2new.append('%s.2C' % parts[0])
		else:
			s2new.append(s2[j])
	s2 = str2sites(' '.join(s2new))
	hvr2.append(s2)

newsites = []
for i in range(len(hvr1)):
	newsites.append(hvr1[i] + hvr2[i])

## Validate
passed_validation = True

for i in range(len(newsites)):
	curr_sites = newsites[i]
	seq1 = translate(sites2seq(curr_sites, region1), None, '-')
	seq2 = translate(sites2seq(curr_sites, region2), None, '-')
	mysites = seq2sites(seq1) + seq2sites(seq1)
	if not mysites == curr_sites:
		myseq1 = translate(sites2seq(mysites, region1), None, '-')
		myseq2 = translate(sites2seq(mysites, region2), None, '-')
		if not seq1 == myseq1 and seq2 == myseq2:
			passed_validation = False
			print i, hids[i]

if passed_validation:
	counts = pd.read_csv('coelho2009_counts.csv', index_col=0)
	counts = counts.fillna(0)
	counter = [0] * 5
	with open('processed.csv', 'w') as f:
		for i in range(len(newsites)):
			hid = hids[i]
			curr_sites = newsites[i]
			seq1 = translate(sites2seq(curr_sites, region1), None, '-')
			seq2 = translate(sites2seq(curr_sites, region2), None, '-')
			mysites = seq2sites(seq1) + seq2sites(seq2)
			mysites = ' '.join([str(x) for x in mysites])
			for j in range(len(metadata.index)):
				prefix = metadata.ix[metadata.index[j],'NewPrefix']
				for k in range(int(counts.ix[hid, metadata.index[j]])):
					counter[j] += 1
					num = str(counter[j]).zfill(3)
					newid = prefix + num
					f.write('%s,%s,%s\n' % (newid, hid, mysites))


#!/usr/bin/env python
#
# Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS.  All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.

import psutil
import sys

import numpy
from matplotlib import pyplot

class CpuSnapshot(object):
  def __init__(self, label):
    self.label = label
    self.samples = []

  def Capture(self, sample_count):
    print ('Capturing %d CPU samples for %s...' %
           ((sample_count - len(self.samples)), self.label))
    while len(self.samples) < sample_count:
      self.samples.append(psutil.cpu_percent(1.0, False))

  def Text(self):
    return ('%s: avg=%s, median=%s, min=%s, max=%s' %
            (self.label, numpy.average(self.samples),
             numpy.median(self.samples),
             numpy.min(self.samples), numpy.max(self.samples)))

  def Max(self):
    return numpy.max(self.samples)

def GrabCpuSamples(sample_count):
  print 'Label for snapshot (enter to quit): '
  label = raw_input().strip()
  if len(label) == 0:
    return None

  snapshot = CpuSnapshot(label)
  snapshot.Capture(sample_count)

  return snapshot

def main():
  print 'How many seconds to capture per snapshot (enter for 60)?'
  sample_count = raw_input().strip()
  if len(sample_count) > 0 and int(sample_count) > 0:
    sample_count = int(sample_count)
  else:
    print 'Defaulting to 60 samples.'
    sample_count = 60

  snapshots = []
  while True:
    snapshot = GrabCpuSamples(sample_count)
    if snapshot == None:
      break
    snapshots.append(snapshot)

  if len(snapshots) == 0:
    print 'no samples captured'
    return -1

  pyplot.title('CPU usage')

  for s in snapshots:
    pyplot.plot(s.samples, label=s.Text(), linewidth=2)

  pyplot.legend()

  pyplot.show()
  return 0

if __name__ == '__main__':
  sys.exit(main())


from galaxy_analysis.plot.plot_styles import *
import matplotlib.pyplot as plt
import glob
import deepdish as dd
import yt
from galaxy_analysis.utilities import utilities
import numpy as np
from matplotlib.ticker import NullFormatter
from galaxy_analysis.particle_analysis.abundances import single_MDF
#
from galaxy_analysis.analysis import Galaxy

from mpl_toolkits.axes_grid1 import make_axes_locatable
import h5py

# grab the most recent file
workdir = '/mnt/ceph/users/emerick/enzo_runs/pleiades/starIC/run11_30km/final_sndriving/'
#workdir = '/home/emerick/work/enzo_runs/pleiades/starIC/run11_30km/final_sndriving/'
data_files = np.sort(glob.glob(workdir + 'DD????'))
name = data_files[-1].split('final_sndriving/')[1]
gal = Galaxy(name, wdir = workdir)

#
#
#
def plot_alpha_vs_fe():
    fig,ax = plt.subplots()
    fig.set_size_inches(8,7)

    ptype     = gal.df['particle_type']
    fe_over_h = gal.df[('io','particle_Fe_over_H')]
    alpha     = gal.df[('io','particle_alpha_over_Fe')]
    age       = (gal.ds.current_time - gal.df[('io','creation_time')]).convert_to_units('Myr')

    age = age - np.min(age)

    p = ax.scatter(fe_over_h[ptype==11], alpha[ptype==11],
                  s = point_size, lw = 2, c = age[ptype==11], cmap = 'plasma_r', alpha = 0.75)
    p.set_clim([0.0, np.max(age)])
    cb = fig.colorbar(p)
    cb.set_label(r'Stellar Age (Myr)')

    ax.set_xlim(-9,-1)
    ax.set_ylim(-1.75,1.75)

    ax.set_xlabel(r'[Fe/H]')
    ax.set_ylabel(r'[$\rm \alpha$/Fe]')

    plt.minorticks_on()
    plt.tight_layout()
    fig.savefig('alpha_over_fe.png')
    plt.close()

    return

def plot_alpha_vs_fe_movie():
    times = np.arange(0, 245, 1)
    for i, t in enumerate(times):
        plot_alpha_vs_fe_with_histograms(t_f = t, image_num = i)

def plot_alpha_vs_fe_with_histograms(t_f = None, image_num = 0):

    sep = 0.02
    left, width = 0.125, 0.65
    bottom, height = 0.1, 0.65
    left_h = left + width + sep
    bottom_h = bottom + height + sep

    rect_scatter = [left,bottom,width,height]
#    rect_colorbar =
#    rect_histx   = [left, bottom_h, width, 0.95 - bottom_h - (left-bottom)]
#    rect_histy   = [left_h, bottom, 0.95 - left_h, height]

#    fig,ax = plt.subplots()
    fig = plt.figure(1, figsize=(8,8))
#    fig.set_size_inches(8,8)

    ax_scatter = plt.axes(rect_scatter)
#    ax_hist_x  = plt.axes(rect_histx)
#    ax_hist_y  = plt.axes(rect_histy)
#    ax_color   = plt.axes(rect_colorbar)

    ptype     = gal.df['particle_type']
    fe_over_h = gal.df[('io','particle_Fe_over_H')]
    alpha     = gal.df[('io','particle_alpha_over_Fe')]
    creation_time = gal.df[('io','creation_time')].convert_to_units('Myr')
    age       = (gal.ds.current_time - creation_time)

    if t_f is None: # plot normally all MS stars
        age = age - np.min(age)

        # scatter plot
        p = ax_scatter.scatter(fe_over_h[ptype==11], alpha[ptype==11],
                      s = point_size, lw = 2, c = age[ptype==11], cmap = 'plasma_r', alpha = 0.75)
        p.set_clim([0.0, np.max(age)])
    else:
        min_clim = 0.0
        max_clim = np.max( age - np.min(age))

        particle_lifetimes = gal.df[('io','particle_model_lifetime')].convert_to_units('Myr')
        selection          = (t_f >= creation_time) * ( t_f < creation_time + particle_lifetimes)
        age                =  t_f - creation_time

        if np.size(fe_over_h[selection]) < 1:
            plot_fe_over_h = np.ones(np.size(fe_over_h))*(-10000) # make dummy values so plot still diplays, but is empty
            plot_alpha     = np.ones(np.size(alpha))*(-10000)
            plot_age       = np.ones(np.size(age))*(-10000)
        else:
            plot_fe_over_h  = fe_over_h[selection]
            plot_alpha      = alpha[selection]
            plot_age        = age[selection]

        p = ax_scatter.scatter(plot_fe_over_h, plot_alpha, s = point_size, lw = 2,
                               c = plot_age, cmap = 'plasma_r', alpha = 0.75)
        p.set_clim([min_clim,max_clim])

    cb = fig.colorbar(p, ax = ax_scatter, orientation = 'horizontal', pad = 0.125, fraction = 0.046,
                         aspect = 40)
    cb.set_label(r'Stellar Age (Myr)')
#
#
    ax_scatter.set_xlim(-9,-1)
    ax_scatter.set_ylim(-1.75,1.75)
    ax_scatter.tick_params(axis='x',which='minor',bottom='on')
    ax_scatter.tick_params(axis='y',which='minor',bottom='on')

    ax_scatter.set_xlabel(r'[Fe/H]')
    ax_scatter.set_ylabel(r'[$\rm \alpha$/Fe]')
    plt.minorticks_on()
    ax_scatter.plot( ax_scatter.get_xlim(), [0.0,0.0], lw = line_width, color = 'black', ls = '--')

    #
    # find main plot and construct histograms
    #
    divider = make_axes_locatable(ax_scatter)
    left, bottom, width, height  = divider.get_position()
#    width, height = divider.get_horizontal(), divider.get_vertical()
    sep = 0.01
    thickness = np.min( np.array([0.95 - left - width - sep, 0.95 - bottom - height - sep]))
    rect_histx = [left, bottom + height + sep, width, thickness]
    rect_histy = [left + width + sep, bottom, thickness, height]
    ax_hist_x  = plt.axes(rect_histx)
    ax_hist_y  = plt.axes(rect_histy)

    nbins = 100
    hist,bins = np.histogram(fe_over_h, bins = nbins)
    weights   = np.ones(np.size(fe_over_h)) * (1.0 / (1.0*np.max(hist)))
    ax_hist_x.hist(fe_over_h, color = 'C0', bins = nbins, weights = weights)
    if not (t_f is None):
        if np.max(plot_fe_over_h) > -1000:
            hist,bins = np.histogram(plot_fe_over_h, bins = nbins)
            weights = np.ones(np.size(plot_fe_over_h)) * (1.0 / (1.0*np.max(hist)))
            ax_hist_x.hist(plot_fe_over_h, color = 'black', bins = nbins, weights = weights,
                           histtype = 'step', lw = 2.0)

#    plot_histogram(ax_hist_x, bins, hist / (1.0*np.max(hist)), color = 'black')
    plt.minorticks_on()
#    hist,bins = np.histogram(alpha, bins = 24)
#    plot_histogram(ax_hist_y, bins, hist / (1.0*np.max(hist)), color = 'black', orientation = 'horizontal')
    nbins = 50
    hist,bins = np.histogram(alpha, bins = nbins)
    weights = np.ones(np.size(fe_over_h)) * (1.0 / (1.0*np.max(hist)))
    ax_hist_y.hist(alpha, orientation='horizontal', color = 'C0', bins = nbins, weights = weights)
    if not (t_f is None):
        if np.max(plot_alpha) > -1000:
            hist,bins = np.histogram(plot_alpha, bins = nbins)
            weights = np.ones(np.size(plot_alpha)) * (1.0 / (1.0*np.max(hist)))
            ax_hist_y.hist(plot_alpha, orientation = 'horizontal', color = 'black', bins = nbins,
                                    weights = weights, histtype='step', lw = 2.0)

    ax_hist_x.xaxis.set_major_formatter(NullFormatter())
    ax_hist_y.yaxis.set_major_formatter(NullFormatter())
    ax_hist_x.set_xlim(ax_scatter.get_xlim())
    ax_hist_y.set_ylim(ax_scatter.get_ylim())
    ticks = [0.0,0.25,0.5,0.75,1.0]
    ax_hist_x.set_yticks(ticks)
    ax_hist_y.set_xticks(ticks)
    ax_hist_y.set_xticklabels(ticks, rotation = 270)

    plt.minorticks_on()
#    plt.tight_layout()
    if t_f is None:
        fig.savefig('alpha_over_fe_hist.png')
    else:
        fig.savefig('alpha_movie/alpha_over_fe_hist_%0004i.png'%(image_num))

    plt.close()

    return

def plot_panel(A = 'Fe', B = 'Fe', C = 'H', color = True):
    """
    Make panel plots of  X/A vs. B/C where "X" is a loop through all elements available,
    and A, B, C are fixed for all plots, chosen by user. Defualt will plot
    [X/Fe] vs. [Fe/H]. Default behavior is to color points by age.
    """
    filename = workdir + '/abundances/abundances/abundances.h5'

    hdf5_data   = h5py.File(filename, 'r')
    dfiles = hdf5_data.keys()
    dfile  = dfiles[-1]  # do this with most recent data file

    data = dd.io.load(filename, '/' + str(dfile))
    elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)])
    elements = elements + ['alpha']
    age = data['Time'] - data['creation_time'] # age of all particles in this data set

    for base in ['H','Fe']:
        fig, ax = plt.subplots(4,4, sharex = True, sharey = True)
        fig.set_size_inches(4*4,4*4)
        fig.subplots_adjust(hspace=0.0, wspace = 0.0)

        if base == 'Fe':
            bins = np.arange(-3,3.1,0.1)
        else:
            bins = np.arange(-9,0,0.1)

        i,j = 0,0
        for e in elements:
            if (A == e): # skip
                continue

            index = (i,j)
            y = np.array(data['abundances'][e][A])
            x = np.array(data['abundances'][B][C])

            p = ax[index].scatter(x, y, s = point_size*0.5,
                               lw = 2, c = age, cmap = 'plasma_r', alpha = 0.75)
            p.set_clim([0.0, np.max(age)])
            xy = (0.8,0.8)
            ax[index].annotate(e, xy=xy, xytext=xy, xycoords = 'axes fraction',
                                                    textcoords = 'axes fraction')
#            cb = fig.colorbar(p)
#            cb.set_label(r'Stellar Age (Myr)')
            j = j + 1
            if j >= 4:
                j = 0
                i = i + 1

        for i in np.arange(4):
            ax[(3,i)].set_xlabel(r'log([' + B + '/' + C + '])')
            ax[(i,0)].set_ylabel(r'log([X/' + A + '])')

            if C == 'H':
                ax[(i,0)].set_xlim(-10.25, 0.125)
            else:
                ax[(i,0)].set_xlim(-3.25, 3.25)

            if A == 'H':
                ax[(0,i)].set_ylim(-10.25, 0.125)
            else:
                ax[(0,i)].set_ylim(-3.25, 3.25)
                for j in np.arange(4):
                    ax[(j,i)].plot([-10,10], [0.0,0.0], lw = 0.5 * line_width, ls = ':', color = 'black')

        plt.minorticks_on()
        fig.savefig('X_over_' + A +'_vs_' + B + '_over_' + C + '_panel.png')
        plt.close()

    return

def plot_spatial_profiles(field = 'metallicity', abundance = False,
                          bins = None, spatial_type = 'cylindrical_radius'):

    filename = workdir + '/abundances/abundances/abundances.h5'

    hdf5_data   = h5py.File(filename, 'r')
    dfiles = hdf5_data.keys()
    dfile  = dfiles[-1]  # do this with most recent data file

    data = dd.io.load(filename, '/' + str(dfile))
    elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)])
    elements = elements + ['alpha']

    if spatial_type == 'cylindrical_radius':
        bin_field    = np.sqrt(data['kinematics']['x']**2 + data['kinematics']['y']**2)
        xlabel = r'Radius (pc)'
    elif spatial_type == 'z':
        bin_field    = np.abs( data['kinematics']['z'] )
        xlabel = r'Z (pc)'

    if bins is None:
        bins = np.linspace(np.floor(np.min(bin_field)), np.ceil(np.max(bin_field)), 100)
    centers = 0.5 * (bins[1:] + bins[:-1])
    nbins = np.size(bins)

    hist_index = np.digitize(bin_field, bins = bins)
    median, q1, q3 = np.zeros(nbins-1), np.zeros(nbins-1), np.zeros(nbins-1)

    if field == 'metallicity':
        # make a single plot
        # bin the data
        for i in np.arange(nbins-1):
            x = data['metallicity'][hist_index == i + 1]
            median[i] = np.median(x)

            if np.size(x) > 1:
                q1[i]     = np.percentile(x, 25.0)
                q3[i]     = np.percentile(x, 75.0)
            elif np.size(x) == 1:
                q1[i] = median[i]
                q3[i] = median[i]

        # now plot
        fig, ax = plt.subplots()
        fig.set_size_inches(8,8)

        plot_histogram(ax, bins, median, lw = line_width, color = 'black', ls = '-')
        ax.fill_between(centers, q1, q3, lw = 1.5, color = 'grey')

        ax.set_ylabel(r'Metallicity Fraction')
        ax.set_xlabel(xlabel)
        ax.set_xlim( np.min(bins), np.max(bins))
        plt.tight_layout()
        plt.minorticks_on()
        fig.savefig('metallicity_' + spatial_type + '_profile.png')
        plt.close()

    elif abundance:

        fig, ax = plt.subplots(4,4, sharex = True, sharey = True)
        fig.set_size_inches(16,16)
        fig.subplots_adjust(hspace = 0.0, wspace = 0.0)

        axi, axj = 0,0
        for e in elements:
            if field == e:
                continue
            index = (axi,axj)

            for i in np.arange(nbins-1):
                x = np.array(data['abundances'][e][field])
                x = x[ hist_index == (i + 1)]

                if np.size(x) > 0:
                    median[i] = np.median(x)
                    q1[i]     = np.percentile(x, 25)
                    q3[i]     = np.percentile(x, 75)
                else:
                    median[i] = None; q1[i] = None; q3[i] = None

            ax[index].annotate(e, xy=(0.8,0.8),xytext=(0.8,0.8),
                                 xycoords='axes fraction',textcoords = 'axes fraction')
            plot_histogram(ax[index], bins, median, lw = line_width, color = 'black', ls = '-')
            ax[index].fill_between(centers,q1,q3,lw=1.5,color='grey')

            axj = axj+1
            if axj>=4:
                axj = 0
                axi = axi + 1

        for i in np.arange(4):
            ax[(3,i)].set_xlabel(xlabel)
            ax[(i,0)].set_ylabel(r'log[X/' + field +'])')

            if field == 'H':
                ax[(0,i)].set_ylim(-10.25,0.125)
            else:
                ax[(0,i)].set_ylim(-3.25,3.25)
                for j in np.arange(4):
                    ax[(j,i)].plot([bins[0],bins[-1]], [0.0,0.0], lw = 0.5 * line_width, ls = '--',color ='black')

            ax[(i,0)].set_xlim(np.min(bins), np.max(bins))

        plt.minorticks_on()
        fig.savefig(field + '_' + spatial_type + '_profile_panel.png')

        plt.close()
    return

def plot_MDF(plot_base = ['H','Fe']):
    """
    Make a panel plot of the time evolution of all elemental abundance ratios
    with respect to both H and Fe (as separate plots)
    """
    if (not (type(plot_base) is list)):
        plot_base = [plot_base]

    filename = workdir + '/abundances/abundances/abundances.h5'

    hdf5_data   = h5py.File(filename, 'r')
    dfiles = hdf5_data.keys()
    dfile  = dfiles[-1]  # do this with most recent data file

    data = dd.io.load(filename, '/' + str(dfile))
    elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)])
    elements = elements + ['alpha']

    for base in plot_base:
        fig, ax = plt.subplots(4,4, sharex = True, sharey = True)
        fig.set_size_inches(4*4,4*4)
        fig.subplots_adjust(hspace=0.0, wspace = 0.0)

        if base == 'Fe':
            bins = np.arange(-3,3.1,0.1)
        else:
            bins = np.arange(-9,0,0.1)

        i,j = 0,0
        for e in elements:
            if (base == e):
                continue
            index = (i,j)

            points = np.array(data['abundances'][e][base])

            single_MDF(points, bins = bins, norm = 'peak', ax = ax[index],
                               label = False, lw = line_width)
            x = np.max(bins) - (0.25/6.0 * (bins[-1] - bins[0]))
            y = 0.9
            ax[index].annotate(e, xy = (x,y), xytext =(x,y))
            ax[index].plot([0,0], [0.0,1.0], ls = ':', lw = 0.5 * line_width, color = 'black')

            j = j + 1
            if j >= 4:
                j = 0
                i = i + 1

        for i in np.arange(4):
            ax[(3,i)].set_xlabel(r'log([X/' + base + '])')
            ax[(i,0)].set_ylabel(r'N/N$_{\rm peak}$')

            if base == 'H':
                ax[(i,0)].set_xlim(-10.25, 0.125)
            elif base == 'Fe':
                ax[(i,0)].set_xlim(-3.25, 3.25)

        plt.minorticks_on()
        fig.savefig(base + '_MDF.png')
        plt.close()

    return

def plot_time_evolution():
    """
    Make a panel plot of the time evolution of all elemental abundance ratios
    with respect to both H and Fe (as separate plots)
    """
    filename = workdir + '/abundances/abundances/abundances.h5'

    hdf5_data   = h5py.File(filename, 'r')
    dfiles = hdf5_data.keys()
    dfile  = dfiles[-1]  # do this with most recent data file

    data = dd.io.load(filename, '/' + str(dfile))
    elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)])
    elements = elements + ['alpha']

    for time_type in ['cumulative','10Myr']:
        for base in ['H','Fe']:
            fig, ax = plt.subplots(4,4, sharex = True, sharey = True)
            fig.set_size_inches(4*4,4*4)
            fig.subplots_adjust(hspace=0.0, wspace = 0.0)

            i,j = 0,0
            for e in elements:
                if (base == e):
                    continue
                print("plotting " + e + "/" + base + " time evolution")
                index = (i,j)

                t  = data['statistics'][time_type]['bins']
                y  = data['statistics'][time_type][e][base]['median']
                Q1 = data['statistics'][time_type][e][base]['Q1']
                Q3 = data['statistics'][time_type][e][base]['Q3']
                select = (y*0 == 0) # remove nan values

                t  = t[select]
                t  = t - t[0]

                ax[index].plot( t, y[select], lw = line_width, ls = '-', color = 'black', label = r' ' + e +' ')
                ax[index].fill_between(t, Q1[select], Q3[select], color = 'black', alpha = 0.5, lw = 0.5 * line_width)
                ax[index].set_xlim(0.0, np.max(t))
                ax[index].plot( [0.0,1000.0], [0.0,0.0], ls = ':', color = 'black', lw = line_width)
                ax[index].legend(loc = 'upper right')

                j = j + 1
                if j >= 4:
                    j = 0
                    i = i + 1

            for i in np.arange(4):
                ax[(3,i)].set_xlabel(r'Time (Myr)')
                ax[(i,0)].set_ylabel(r'[X/' + base +']')

                if base == 'H':
                    ax[(i,0)].set_ylim(-12.25, 0.125)
                elif base == 'Fe':
                    ax[(i,0)].set_ylim(-3.25, 3.25)

#            for j in np.arange(3):
#                ax[(j,i)].set_xticklabels([])
#                ax[(i,j+1)].set_yticklabels([])
#            ax[(3,i)].set_xticklabels(np.arange(0,np.max(t)+20,20))
#            if base == 'Fe':
#                ax[(i,0)].set_yticklabels([-3,-2,-1,0,1,2,3,])
#            else:
#                ax[(i,0)].set_yticklabels([-12, -10, -8, -6, -4, -2, 0])

            plt.minorticks_on()
            fig.savefig('stellar_x_over_' + base + '_' + time_type +'_evolution.png')
            plt.close()

    return

def plot_mass_fraction_time_evolution():
    """
    Make a panel plot of the time evolution of all elemental abundance ratios
    with respect to both H and Fe (as separate plots)
    """
    filename = workdir + '/abundances/abundances/abundances.h5'

    hdf5_data   = h5py.File(filename, 'r')
    dfiles = hdf5_data.keys()
    dfile  = dfiles[-1]  # do this with most recent data file

    data = dd.io.load(filename, '/' + str(dfile))
    elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)])
#    elements = elements + ['alpha']

    for time_type in ['cumulative','10Myr']:
        fig, ax = plt.subplots(4,4, sharex = True, sharey = True)
        fig.set_size_inches(4*4,4*4)
        fig.subplots_adjust(hspace=0.0, wspace = 0.0)

        i,j = 0,0
        for e in elements:
            print("plotting " + e + "mass fraction time evolution")
            index = (i,j)

            t  = data['mass_fraction_statistics'][time_type]['bins']
            y  = data['mass_fraction_statistics'][time_type][e]['median']
            Q1 = data['mass_fraction_statistics'][time_type][e]['Q1']
            Q3 = data['mass_fraction_statistics'][time_type][e]['Q3']
            select = (y*0 == 0) # remove nan values

            t  = t[select]
            t  = t - t[0]

            ax[index].plot( t, y[select], lw = line_width, ls = '-', color = 'black', label = r' ' + e +' ')
            ax[index].fill_between(t, Q1[select], Q3[select], color = 'black', alpha = 0.5, lw = 0.5 * line_width)
            ax[index].set_xlim(0.0, np.max(t))
            ax[index].plot( [0.0,1000.0], [0.0,0.0], ls = ':', color = 'black', lw = line_width)
            ax[index].legend(loc = 'upper right')

            j = j + 1
            if j >= 4:
                j = 0
                i = i + 1

        for i in np.arange(4):
            ax[(3,i)].set_xlabel(r'Time (Myr)')
            ax[(i,0)].set_ylabel(r'log(X Mass Fraction)')

            ax[(i,0)].set_ylim(1.0E-10, 1.0E-4)
            ax[(i,0)].semilogy()

#            for j in np.arange(3):
#                ax[(j,i)].set_xticklabels([])
#                ax[(i,j+1)].set_yticklabels([])
#            ax[(3,i)].set_xticklabels(np.arange(0,np.max(t)+20,20))
#            if base == 'Fe':
#                ax[(i,0)].set_yticklabels([-3,-2,-1,0,1,2,3,])
#            else:
#                ax[(i,0)].set_yticklabels([-12, -10, -8, -6, -4, -2, 0])

        plt.minorticks_on()
        fig.savefig('stellar_mass_fraction_' + time_type +'_evolution.png')
        plt.close()

    return

def plot_ratios_with_histograms(X='alpha',A='Fe',B='Fe',C='H'):
    filename = workdir + '/abundances/abundances/abundances.h5'

    hdf5_data   = h5py.File(filename, 'r')
    dfiles = hdf5_data.keys()
    dfile  = dfiles[-1]  # do this with most recent data file

    data = dd.io.load(filename, '/' + str(dfile))
    elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)])
    elements = elements + ['alpha'] + ['H']
    age = data['Time'] - data['creation_time'] # age of all particles in this data set

    # --------------------
    check_elements = [x for x in [X,A,B,C] if (not (x in elements))]
    if len(check_elements) > 0:
        print(check_elements, " not in elements list")
        print("available: ", elements)
        raise ValueError

    sep = 0.02
    left, width = 0.125, 0.65
    bottom, height = 0.1, 0.65
    left_h = left + width + sep
    bottom_h = bottom + height + sep

    rect_scatter = [left,bottom,width,height]
#    rect_colorbar =
#    rect_histx   = [left, bottom_h, width, 0.95 - bottom_h - (left-bottom)]
#    rect_histy   = [left_h, bottom, 0.95 - left_h, height]

#    fig,ax = plt.subplots()
    fig = plt.figure(1, figsize=(8,8))
#    fig.set_size_inches(8,8)

    ax_scatter = plt.axes(rect_scatter)
#    ax_hist_x  = plt.axes(rect_histx)
#    ax_hist_y  = plt.axes(rect_histy)
#    ax_color   = plt.axes(rect_colorbar)

    x_values  = data['abundances'][B][C]
    y_values  = data['abundances'][X][A]

    age = age - np.min(age) # normalize

    # scatter plot
    p = ax_scatter.scatter(x_values, y_values,
                  s = point_size, lw = 2, c = age, cmap = 'plasma_r', alpha = 0.75)
    p.set_clim([0.0, np.max(age)])

    cb = fig.colorbar(p, ax = ax_scatter, orientation = 'horizontal', pad = 0.125, fraction = 0.046,
                         aspect = 40)
    cb.set_label(r'Stellar Age (Myr)')
#
#
#
    ax_scatter.set_xlim(-9,-1)
    ax_scatter.set_ylim(-1.75,1.75)
    ax_scatter.tick_params(axis='x',which='minor',bottom='on')
    ax_scatter.tick_params(axis='y',which='minor',bottom='on')

    ax_scatter.set_xlabel(r'log([' + B + '/' + C + '])')
    ax_scatter.set_ylabel(r'log([' + X + '/' + A + '])')
    plt.minorticks_on()

    #
    # find main plot and construct histograms
    #
    divider = make_axes_locatable(ax_scatter)
    left, bottom, width, height  = divider.get_position()
#    width, height = divider.get_horizontal(), divider.get_vertical()
    sep = 0.01
    thickness = np.min( np.array([0.95 - left - width - sep, 0.95 - bottom - height - sep]))
    rect_histx = [left, bottom + height + sep, width, thickness]
    rect_histy = [left + width + sep, bottom, thickness, height]
    ax_hist_x  = plt.axes(rect_histx)
    ax_hist_y  = plt.axes(rect_histy)

    # construct the histogram for the horizontal axis (goes up top)
    nbins = 100
    hist,bins = np.histogram(x_values, bins = nbins)
    weights   = np.ones(np.size(x_values)) * (1.0 / (1.0*np.max(hist)))
    ax_hist_x.hist(x_values, color = 'C0', bins = nbins, weights = weights)
#    plot_histogram(ax_hist_x, bins, hist / (1.0*np.max(hist)), color = 'black')
    plt.minorticks_on()
#    hist,bins = np.histogram(alpha, bins = 24)
#    plot_histogram(ax_hist_y, bins, hist / (1.0*np.max(hist)), color = 'black', orientation = 'horizontal')

    # now do the same for the vertical axis histogram
    nbins = 50
    hist,bins = np.histogram(y_values, bins = nbins)
    weights = np.ones(np.size(y_values)) * (1.0 / (1.0*np.max(hist)))
    ax_hist_y.hist(y_values, orientation='horizontal', color = 'C0', bins = nbins, weights = weights)

    ax_hist_x.xaxis.set_major_formatter(NullFormatter())
    ax_hist_y.yaxis.set_major_formatter(NullFormatter())
    ax_hist_x.set_xlim(ax_scatter.get_xlim())
    ax_hist_y.set_ylim(ax_scatter.get_ylim())
    ticks = [0.0,0.25,0.5,0.75,1.0]
    ax_hist_x.set_yticks(ticks)
    ax_hist_y.set_xticks(ticks)
    ax_hist_y.set_xticklabels(ticks, rotation = 270)

    plt.minorticks_on()
#    plt.tight_layout()
    fig.savefig(X + '_over_' + A + '_vs_' + B + '_over_' + C + '_hist.png')

    plt.close()

    return

if __name__ == '__main__':
    plot_mass_fraction_time_evolution() #

#    plot_ratios_with_histograms('C','O','Fe','H') # C/O vs Fe/H
#    plot_ratios_with_histograms('alpha','Mg','Mg','H')
#    plot_ratios_with_histograms('alpha','Fe','Fe','H')

#    plot_panel() # default [X/Fe] vs [Fe/H]
#    plot_panel(A = 'Mg', B = 'Fe', C = 'H')
#    plot_panel(A = 'Mg', B = 'Mg', C = 'Fe')
#    plot_panel(A = 'O',  B = 'Fe', C = 'H')
#    plot_panel(A = 'O',  B = 'O',  C = 'Fe')
#    plot_panel(A = 'Ba', B = 'Ba', C = 'Fe')

#    plot_MDF(plot_base = ['H','Fe','O','Ba'])

#    plot_time_evolution()

#    plot_alpha_vs_fe_with_histograms()

#    plot_alpha_vs_fe()

#    plot_alpha_vs_fe_movie()
#    plot_spatial_profiles(bins=np.arange(0,505,10))
#    plot_spatial_profiles(field = 'Fe',abundance=True, bins = np.arange(0,505,10))
#    plot_spatial_profiles(field = 'H', abundance=True, bins = np.arange(0,505,10))