# -*- encoding: utf-8 -*-
from __future__ import division, print_function, absolute_import, unicode_literals

import itertools

import h2o
from h2o.job import H2OJob
from h2o.frame import H2OFrame
from h2o.exceptions import H2OValueError
from h2o.estimators.estimator_base import H2OEstimator
from h2o.two_dim_table import H2OTwoDimTable
from h2o.display import H2ODisplay
from h2o.grid.metrics import *  # NOQA
from h2o.utils.backward_compatibility import backwards_compatible
from h2o.utils.shared_utils import deprecated, quoted
from h2o.utils.compatibility import *  # NOQA
from h2o.utils.typechecks import assert_is_type, is_type

class H2OGridSearch(backwards_compatible()):
    """
    Grid Search of a Hyper-Parameter Space for a Model

    :param model: The type of model to be explored initialized with optional parameters that will be
        unchanged across explored models.
    :param hyper_params: A dictionary of string parameters (keys) and a list of values to be explored by grid
        search (values).
    :param str grid_id: The unique id assigned to the resulting grid object. If none is given, an id will
        automatically be generated.
    :param search_criteria:  A dictionary of directives which control the search of the hyperparameter space.
        The default strategy "Cartesian" covers the entire space of hyperparameter combinations. Specify the
        "RandomDiscrete" strategy to get random search of all the combinations of your hyperparameters.
        RandomDiscrete should usually be combined with at least one early stopping criterion: max_models
        and/or max_runtime_secs, e.g::

            >>> criteria = {"strategy": "RandomDiscrete", "max_models": 42,
            ...             "max_runtime_secs": 28800, "seed": 1234}
            >>> criteria = {"strategy": "RandomDiscrete", "stopping_metric": "AUTO",
            ...             "stopping_tolerance": 0.001, "stopping_rounds": 10}
            >>> criteria = {"strategy": "RandomDiscrete", "stopping_rounds": 5,
            ...             "stopping_metric": "misclassification",
            ...             "stopping_tolerance": 0.00001}
    :returns: a new H2OGridSearch instance

    Examples
    --------
        >>> from h2o.grid.grid_search import H2OGridSearch
        >>> from h2o.estimators.glm import H2OGeneralizedLinearEstimator
        >>> hyper_parameters = {'alpha': [0.01,0.5], 'lambda': [1e-5,1e-6]}
        >>> gs = H2OGridSearch(H2OGeneralizedLinearEstimator(family='binomial'), hyper_parameters)
        >>> training_data = h2o.import_file("smalldata/logreg/benign.csv")
        >>> gs.train(x=range(3) + range(4,11),y=3, training_frame=training_data)
        >>> gs.show()
    """

    def __init__(self, model, hyper_params, grid_id=None, search_criteria=None, export_checkpoints_dir=None):
        super(H2OGridSearch, self).__init__()
        assert_is_type(model, None, H2OEstimator, lambda mdl: issubclass(mdl, H2OEstimator))
        assert_is_type(hyper_params, dict)
        assert_is_type(grid_id, None, str)
        assert_is_type(search_criteria, None, dict)
        if not (model is None or is_type(model, H2OEstimator)): model = model()
        self._id = grid_id
        self.model = model
        self.hyper_params = dict(hyper_params)
        self.search_criteria = None if search_criteria is None else dict(search_criteria)
        self.export_checkpoints_dir = export_checkpoints_dir
        self._grid_json = None
        self.models = None  # list of H2O Estimator instances
        self._parms = {}  # internal, for object recycle #
        self.parms = {}  # external#
        self._future = False  # used by __repr__/show to query job state#
        self._job = None  # used when _future is True#

    @property
    def grid_id(self):
        """A key that identifies this grid search object in H2O."""
        return self._id

    @grid_id.setter
    def grid_id(self, value):
        oldname = self.grid_id
        self._id = value
        h2o.rapids('(rename "{}" "{}")'.format(oldname, value))

    @property
    def model_ids(self):
        return [i['name'] for i in self._grid_json["model_ids"]]

    @property
    def hyper_names(self):
        return self._grid_json["hyper_names"]

    @property
    def failed_params(self):
        return self._grid_json.get("failed_params", None)

    @property
    def failure_details(self):
        return self._grid_json.get("failure_details", None)

    @property
    def failure_stack_traces(self):
        return self._grid_json.get("failure_stack_traces", None)

    @property
    def failed_raw_params(self):
        return self._grid_json.get("failed_raw_params", None)

    def start(self, x, y=None, training_frame=None, offset_column=None, fold_column=None, weights_column=None,
              validation_frame=None, **params):
        """
        Asynchronous model build by specifying the predictor columns, response column, and any
        additional frame-specific values.

        To block for results, call :meth:`join`.

        :param x: A list of column names or indices indicating the predictor columns.
        :param y: An index or a column name indicating the response column.
        :param training_frame: The H2OFrame having the columns indicated by x and y (as well as any
            additional columns specified by fold, offset, and weights).
        :param offset_column: The name or index of the column in training_frame that holds the offsets.
        :param fold_column: The name or index of the column in training_frame that holds the per-row fold
            assignments.
        :param weights_column: The name or index of the column in training_frame that holds the per-row weights.
        :param validation_frame: H2OFrame with validation data to be scored on while training.
        """
        self._future = True
        self.train(x=x,
                   y=y,
                   training_frame=training_frame,
                   offset_column=offset_column,
                   fold_column=fold_column,
                   weights_column=weights_column,
                   validation_frame=validation_frame,
                   **params)

    def join(self):
        """Wait until grid finishes computing."""
        self._future = False
        self._job.poll()
        self._job = None

    def train(self, x=None, y=None, training_frame=None, offset_column=None, fold_column=None, weights_column=None,
              validation_frame=None, **params):
        """
        Train the model synchronously (i.e. do not return until the model finishes training).

        To train asynchronously call :meth:`start`.

        :param x: A list of column names or indices indicating the predictor columns.
        :param y: An index or a column name indicating the response column.
        :param training_frame: The H2OFrame having the columns indicated by x and y (as well as any
            additional columns specified by fold, offset, and weights).
        :param offset_column: The name or index of the column in training_frame that holds the offsets.
        :param fold_column: The name or index of the column in training_frame that holds the per-row fold
            assignments.
        :param weights_column: The name or index of the column in training_frame that holds the per-row weights.
        :param validation_frame: H2OFrame with validation data to be scored on while training.
        """
        algo_params = locals()
        parms = self._parms.copy()
        parms.update({k: v for k, v in algo_params.items() if k not in ["self", "params", "algo_params", "parms"]})
        # dictionaries have special handling in grid search, avoid the implicit conversion
        parms["search_criteria"] = None if self.search_criteria is None else str(self.search_criteria)
        parms["export_checkpoints_dir"] = self.export_checkpoints_dir
        parms["hyper_parameters"] = None if self.hyper_params  is None else str(self.hyper_params) # unique to grid search
        parms.update({k: v for k, v in list(self.model._parms.items()) if v is not None})  # unique to grid search
        parms.update(params)
        if '__class__' in parms:  # FIXME: hackt for PY3
            del parms['__class__']
        y = algo_params["y"]
        tframe = algo_params["training_frame"]
        if tframe is None: raise ValueError("Missing training_frame")
        if y is not None:
            if is_type(y, list, tuple):
                if len(y) == 1:
                    parms["y"] = y[0]
                else:
                    raise ValueError('y must be a single column reference')
        if x is None:
            if(isinstance(y, int)):
                xset = set(range(training_frame.ncols)) - {y}
            else:
                xset = set(training_frame.names) - {y}
        else:
            xset = set()
            if is_type(x, int, str): x = [x]
            for xi in x:
                if is_type(xi, int):
                    if not (-training_frame.ncols <= xi < training_frame.ncols):
                        raise H2OValueError("Column %d does not exist in the training frame" % xi)
                    xset.add(training_frame.names[xi])
                else:
                    if xi not in training_frame.names:
                        raise H2OValueError("Column %s not in the training frame" % xi)
                    xset.add(xi)
        x = list(xset)
        parms["x"] = x
        self.build_model(parms)

    def build_model(self, algo_params):
        """(internal)"""
        if algo_params["training_frame"] is None: raise ValueError("Missing training_frame")
        x = algo_params.pop("x")
        y = algo_params.pop("y", None)
        training_frame = algo_params.pop("training_frame")
        validation_frame = algo_params.pop("validation_frame", None)
        is_auto_encoder = (algo_params is not None) and ("autoencoder" in algo_params and algo_params["autoencoder"])
        algo = self.model._compute_algo()  # unique to grid search
        is_unsupervised = is_auto_encoder or algo == "pca" or algo == "svd" or algo == "kmeans" or algo == "glrm"
        if is_auto_encoder and y is not None: raise ValueError("y should not be specified for autoencoder.")
        if not is_unsupervised and y is None: raise ValueError("Missing response")
        if not is_unsupervised:
            y = y if y in training_frame.names else training_frame.names[y]
            self.model._estimator_type = "classifier" if training_frame.types[y] == "enum" else "regressor"
        self._model_build(x, y, training_frame, validation_frame, algo_params)

    def _model_build(self, x, y, tframe, vframe, kwargs):
        kwargs['training_frame'] = tframe
        if vframe is not None: kwargs["validation_frame"] = vframe
        if is_type(y, int): y = tframe.names[y]
        if y is not None: kwargs['response_column'] = y
        if not is_type(x, list, tuple): x = [x]
        if is_type(x[0], int):
            x = [tframe.names[i] for i in x]
        offset = kwargs["offset_column"]
        folds = kwargs["fold_column"]
        weights = kwargs["weights_column"]
        ignored_columns = list(set(tframe.names) - set(x + [y, offset, folds, weights]))
        kwargs["ignored_columns"] = None if not ignored_columns else [quoted(col) for col in ignored_columns]
        kwargs = dict([(k, kwargs[k].frame_id if isinstance(kwargs[k], H2OFrame) else kwargs[k]) for k in kwargs if
                       kwargs[k] is not None])  # gruesome one-liner
        algo = self.model._compute_algo()  # unique to grid search
        if self.grid_id is not None: kwargs["grid_id"] = self.grid_id
        rest_ver = kwargs.pop("_rest_version") if "_rest_version" in kwargs else None

        grid = H2OJob(h2o.api("POST /99/Grid/%s" % algo, data=kwargs), job_type=(algo + " Grid Build"))

        if self._future:
            self._job = grid
            return

        grid.poll()

        grid_json = h2o.api("GET /99/Grids/%s" % (grid.dest_key))
        failure_messages_stacks = ""
        error_index = 0
        if len(grid_json["failure_details"]) > 0:
            print("Errors/Warnings building gridsearch model\n")
# will raise error if no grid model is returned, store error messages here

            for error_message in grid_json["failure_details"]:
                if isinstance(grid_json["failed_params"][error_index], dict):
                    for h_name in grid_json['hyper_names']:
                        print("Hyper-parameter: {0}, {1}".format(h_name,
                                                                 grid_json['failed_params'][error_index][h_name]))

                if len(grid_json["failure_stack_traces"]) > error_index:
                    print("failure_details: {0}\nfailure_stack_traces: "
                          "{1}\n".format(error_message, grid_json['failure_stack_traces'][error_index]))
                    failure_messages_stacks += error_message+'\n'
                error_index += 1

        self.models = [h2o.get_model(key['name']) for key in grid_json['model_ids']]
        for model in self.models:
            model._estimator_type = self.model._estimator_type

        # get first model returned in list of models from grid search to get model class (binomial, multinomial, etc)
        # sometimes no model is returned due to bad parameter values provided by the user.
        if len(grid_json['model_ids']) > 0:
            first_model_json = h2o.api("GET /%d/Models/%s" %
                                       (rest_ver or 3, grid_json['model_ids'][0]['name']))['models'][0]
            self._resolve_grid(grid.dest_key, grid_json, first_model_json)
        else:
            if len(failure_messages_stacks)>0:
                raise ValueError(failure_messages_stacks)
            else:
                raise ValueError("Gridsearch returns no model due to bad parameter values or other reasons....")

    def _resolve_grid(self, grid_id, grid_json, first_model_json):
        model_class = H2OGridSearch._metrics_class(first_model_json)
        m = model_class()
        m._id = grid_id
        m._grid_json = grid_json
        # m._metrics_class = metrics_class
        m._parms = self._parms
        self.export_checkpoints_dir = m._grid_json["export_checkpoints_dir"]
        H2OEstimator.mixin(self, model_class)
        self.__dict__.update(m.__dict__.copy())

    def __getitem__(self, item):
        return self.models[item]

    def __iter__(self):
        nmodels = len(self.models)
        return (self[i] for i in range(nmodels))

    def __len__(self):
        return len(self.models)

    def __repr__(self):
        self.show()
        return ""

    def predict(self, test_data):
        """
        Predict on a dataset.

        :param H2OFrame test_data: Data to be predicted on.
        :returns: H2OFrame filled with predictions.
        """
        return {model.model_id: model.predict(test_data) for model in self.models}

    def is_cross_validated(self):
        """Return True if the model was cross-validated."""
        return {model.model_id: model.is_cross_validated() for model in self.models}

    def xval_keys(self):
        """Model keys for the cross-validated model."""
        return {model.model_id: model.xval_keys() for model in self.models}

    def get_xval_models(self, key=None):
        """
        Return a Model object.

        :param str key: If None, return all cross-validated models; otherwise return the model
            specified by the key.
        :returns: A model or a list of models.
        """
        return {model.model_id: model.get_xval_models(key) for model in self.models}

    def xvals(self):
        """Return the list of cross-validated models."""
        return {model.model_id: model.xvals for model in self.models}

    def deepfeatures(self, test_data, layer):
        """
        Obtain a hidden layer's details on a dataset.

        :param test_data: Data to create a feature space on.
        :param int layer: Index of the hidden layer.
        :returns: A dictionary of hidden layer details for each model.
        """
        return {model.model_id: model.deepfeatures(test_data, layer) for model in self.models}

    def weights(self, matrix_id=0):
        """
        Return the frame for the respective weight matrix.

        :param: matrix_id: an integer, ranging from 0 to number of layers, that specifies the weight matrix to return.
        :returns: an H2OFrame which represents the weight matrix identified by matrix_id
        """
        return {model.model_id: model.weights(matrix_id) for model in self.models}

    def biases(self, vector_id=0):
        """
        Return the frame for the respective bias vector.

        :param: vector_id: an integer, ranging from 0 to number of layers, that specifies the bias vector to return.
        :returns: an H2OFrame which represents the bias vector identified by vector_id
        """
        return {model.model_id: model.biases(vector_id) for model in self.models}

    def normmul(self):
        """Normalization/Standardization multipliers for numeric predictors."""
        return {model.model_id: model.normmul() for model in self.models}

    def normsub(self):
        """Normalization/Standardization offsets for numeric predictors."""
        return {model.model_id: model.normsub() for model in self.models}

    def respmul(self):
        """Normalization/Standardization multipliers for numeric response."""
        return {model.model_id: model.respmul() for model in self.models}

    def respsub(self):
        """Normalization/Standardization offsets for numeric response."""
        return {model.model_id: model.respsub() for model in self.models}

    def catoffsets(self):
        """
        Categorical offsets for one-hot encoding
        """
        return {model.model_id: model.catoffsets() for model in self.models}

    def model_performance(self, test_data=None, train=False, valid=False, xval=False):
        """
        Generate model metrics for this model on test_data.

        :param test_data: Data set for which model metrics shall be computed against. All three of train, valid
            and xval arguments are ignored if test_data is not None.
        :param train: Report the training metrics for the model.
        :param valid: Report the validation metrics for the model.
        :param xval: Report the validation metrics for the model.
        :return: An object of class H2OModelMetrics.
        """
        return {model.model_id: model.model_performance(test_data, train, valid, xval) for model in self.models}

    def scoring_history(self):
        """
        Retrieve model scoring history.

        :returns: Score history (H2OTwoDimTable)
        """
        return {model.model_id: model.scoring_history() for model in self.models}

    def summary(self, header=True):
        """Print a detailed summary of the explored models."""
        table = []
        for model in self.models:
            model_summary = model._model_json["output"]["model_summary"]
            r_values = list(model_summary.cell_values[0])
            r_values[0] = model.model_id
            table.append(r_values)

        # if h2o.can_use_pandas():
        #  import pandas
        #  pandas.options.display.max_rows = 20
        #  print pandas.DataFrame(table,columns=self.col_header)
        #  return
        print()
        if header:
            print('Grid Summary:')
        print()
        H2ODisplay(table, header=['Model Id'] + model_summary.col_header[1:], numalign="left", stralign="left")

    def show(self):
        """Print models sorted by metric."""
        hyper_combos = itertools.product(*list(self.hyper_params.values()))
        if not self.models:
            c_values = [[idx + 1, list(val)] for idx, val in enumerate(hyper_combos)]
            print(H2OTwoDimTable(
                col_header=['Model', 'Hyperparameters: [' + ', '.join(list(self.hyper_params.keys())) + ']'],
                table_header='Grid Search of Model ' + self.model.__class__.__name__, cell_values=c_values))
        else:
            print(self.sorted_metric_table())

    def varimp(self, use_pandas=False):
        """
        Pretty print the variable importances, or return them in a list/pandas DataFrame.

        :param bool use_pandas: If True, then the variable importances will be returned as a pandas data frame.

        :returns: A dictionary of lists or Pandas DataFrame instances.
        """
        return {model.model_id: model.varimp(use_pandas) for model in self.models}

    def residual_deviance(self, train=False, valid=False, xval=False):
        """
        Retreive the residual deviance if this model has the attribute, or None otherwise.

        :param bool train: Get the residual deviance for the training set. If both train and valid are False,
            then train is selected by default.
        :param bool valid: Get the residual deviance for the validation set. If both train and valid are True,
            then train is selected by default.
        :param bool xval: Get the residual deviance for the cross-validated models.

        :returns: the residual deviance, or None if it is not present.
        """
        return {model.model_id: model.residual_deviance(train, valid, xval) for model in self.models}

    def residual_degrees_of_freedom(self, train=False, valid=False, xval=False):
        """
        Retreive the residual degress of freedom if this model has the attribute, or None otherwise.

        :param bool train: Get the residual dof for the training set. If both train and valid are False, then
            train is selected by default.
        :param bool valid: Get the residual dof for the validation set. If both train and valid are True, then
            train is selected by default.
        :param bool xval: Get the residual dof for the cross-validated models.

        :returns: the residual degrees of freedom, or None if they are not present.
        """
        return {model.model_id: model.residual_degrees_of_freedom(train, valid, xval) for model in self.models}

    def null_deviance(self, train=False, valid=False, xval=False):
        """
        Retreive the null deviance if this model has the attribute, or None otherwise.

        :param bool train: Get the null deviance for the training set. If both train and valid are False, then
            train is selected by default.
        :param bool valid: Get the null deviance for the validation set. If both train and valid are True, then
            train is selected by default.
        :param bool xval: Get the null deviance for the cross-validated models.

        :returns: the null deviance, or None if it is not present.
        """
        return {model.model_id: model.null_deviance(train, valid, xval) for model in self.models}

    def null_degrees_of_freedom(self, train=False, valid=False, xval=False):
        """
        Retreive the null degress of freedom if this model has the attribute, or None otherwise.

        :param bool train: Get the null dof for the training set. If both train and valid are False, then train is
            selected by default.
        :param bool valid: Get the null dof for the validation set. If both train and valid are True, then train is
            selected by default.
        :param bool xval: Get the null dof for the cross-validated models.

        :returns: the null dof, or None if it is not present.
        """
        return {model.model_id: model.null_degrees_of_freedom(train, valid, xval) for model in self.models}

    def pprint_coef(self):
        """Pretty print the coefficents table (includes normalized coefficients)."""
        for i, model in enumerate(self.models):
            print('Model', i)
            model.pprint_coef()
            print()

    def coef(self):
        """Return the coefficients that can be applied to the non-standardized data.

        Note: standardize = True by default. If set to False, then coef() returns the coefficients that are fit directly.

        """
        return {model.model_id: model.coef() for model in self.models}

    def coef_norm(self):
        """Return coefficients fitted on the standardized data (requires standardize = True, which is on by default). These coefficients can be used to evaluate variable importance.

        """
        return {model.model_id: model.coef_norm() for model in self.models}

    def r2(self, train=False, valid=False, xval=False):
        """
        Return the R^2 for this regression model.

        The R^2 value is defined to be ``1 - MSE/var``, where ``var`` is computed as ``sigma^2``.

        If all are False (default), then return the training metric value.
        If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
        "valid", and "xval".

        :param bool train: If train is True, then return the R^2 value for the training data.
        :param bool valid: If valid is True, then return the R^2 value for the validation data.
        :param bool xval:  If xval is True, then return the R^2 value for the cross validation data.

        :returns: The R^2 for this regression model.
        """
        return {model.model_id: model.r2(train, valid, xval) for model in self.models}

    def mse(self, train=False, valid=False, xval=False):
        """
        Get the MSE(s).

        If all are False (default), then return the training metric value.
        If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
        "valid", and "xval".

        :param bool train: If train is True, then return the MSE value for the training data.
        :param bool valid: If valid is True, then return the MSE value for the validation data.
        :param bool xval:  If xval is True, then return the MSE value for the cross validation data.
        :returns: The MSE for this regression model.
        """
        return {model.model_id: model.mse(train, valid, xval) for model in self.models}

    def logloss(self, train=False, valid=False, xval=False):
        """
        Get the Log Loss(s).

        If all are False (default), then return the training metric value.
        If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
        "valid", and "xval".

        :param bool train: If train is True, then return the Log Loss value for the training data.
        :param bool valid: If valid is True, then return the Log Loss value for the validation data.
        :param bool xval:  If xval is True, then return the Log Loss value for the cross validation data.

        :returns: The Log Loss for this binomial model.
        """
        return {model.model_id: model.logloss(train, valid, xval) for model in self.models}

    def mean_residual_deviance(self, train=False, valid=False, xval=False):
        """
        Get the Mean Residual Deviances(s).

        If all are False (default), then return the training metric value.
        If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
        "valid", and "xval".

        :param bool train: If train is True, then return the Mean Residual Deviance value for the training data.
        :param bool valid: If valid is True, then return the Mean Residual Deviance value for the validation data.
        :param bool xval:  If xval is True, then return the Mean Residual Deviance value for the cross validation data.
        :returns: The Mean Residual Deviance for this regression model.
        """
        return {model.model_id: model.mean_residual_deviance(train, valid, xval) for model in self.models}

    def auc(self, train=False, valid=False, xval=False):
        """
        Get the AUC(s).

        If all are False (default), then return the training metric value.
        If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
        "valid", and "xval".

        :param bool train: If train is True, then return the AUC value for the training data.
        :param bool valid: If valid is True, then return the AUC value for the validation data.
        :param bool xval:  If xval is True, then return the AUC value for the validation data.

        :returns: The AUC.
        """
        return {model.model_id: model.auc(train, valid, xval) for model in self.models}

    def aic(self, train=False, valid=False, xval=False):
        """
        Get the AIC(s).

        If all are False (default), then return the training metric value.
        If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
        "valid", and "xval".

        :param bool train: If train is True, then return the AIC value for the training data.
        :param bool valid: If valid is True, then return the AIC value for the validation data.
        :param bool xval:  If xval is True, then return the AIC value for the validation data.

        :returns: The AIC.
        """
        return {model.model_id: model.aic(train, valid, xval) for model in self.models}

    def gini(self, train=False, valid=False, xval=False):
        """
        Get the Gini Coefficient(s).

        If all are False (default), then return the training metric value.
        If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
        "valid", and "xval".

        :param bool train: If train is True, then return the Gini Coefficient value for the training data.
        :param bool valid: If valid is True, then return the Gini Coefficient value for the validation data.
        :param bool xval:  If xval is True, then return the Gini Coefficient value for the cross validation data.

        :returns: The Gini Coefficient for this binomial model.
        """
        return {model.model_id: model.gini(train, valid, xval) for model in self.models}

    def get_hyperparams(self, id, display=True):
        """
        Get the hyperparameters of a model explored by grid search.

        :param str id: The model id of the model with hyperparameters of interest.
        :param bool display: Flag to indicate whether to display the hyperparameter names.

        :returns: A list of the hyperparameters for the specified model.
        """
        idx = id if is_type(id, int) else self.model_ids.index(id)
        model = self[idx]

        # if cross-validation is turned on, parameters in one of the fold model actuall contains the max_runtime_secs
        # parameter and not the main model that is returned.
        if model._is_xvalidated:
            model = h2o.get_model(model._xval_keys[0])

        res = [model.params[h]['actual'][0] if isinstance(model.params[h]['actual'], list)
               else model.params[h]['actual']
               for h in self.hyper_params]
        if display: print('Hyperparameters: [' + ', '.join(list(self.hyper_params.keys())) + ']')
        return res

    def get_hyperparams_dict(self, id, display=True):
        """
        Derived and returned the model parameters used to train the particular grid search model.

        :param str id: The model id of the model with hyperparameters of interest.
        :param bool display: Flag to indicate whether to display the hyperparameter names.

        :returns: A dict of model pararmeters derived from the hyper-parameters used to train this particular model.
        """
        idx = id if is_type(id, int) else self.model_ids.index(id)
        model = self[idx]

        model_params = dict()

        # if cross-validation is turned on, parameters in one of the fold model actual contains the max_runtime_secs
        # parameter and not the main model that is returned.
        if model._is_xvalidated:
            model = h2o.get_model(model._xval_keys[0])

        for param_name in self.hyper_names:
            model_params[param_name] = model.params[param_name]['actual'][0] if \
                isinstance(model.params[param_name]['actual'], list) else model.params[param_name]['actual']

        if display: print('Hyperparameters: [' + ', '.join(list(self.hyper_params.keys())) + ']')
        return model_params

    def sorted_metric_table(self):
        """
        Retrieve summary table of an H2O Grid Search.

        :returns: The summary table as an H2OTwoDimTable or a Pandas DataFrame.
        """
        summary = self._grid_json["summary_table"]
        if summary is not None: return summary.as_data_frame()
        print("No sorted metric table for this grid search")

    @staticmethod
    def _metrics_class(model_json):
        model_type = model_json["output"]["model_category"]
        if model_type == "Binomial":
            model_class = H2OBinomialGridSearch
        elif model_type == "Clustering":
            model_class = H2OClusteringGridSearch
        elif model_type == "Regression":
            model_class = H2ORegressionGridSearch
        elif model_type == "Multinomial":
            model_class = H2OMultinomialGridSearch
        elif model_type == "Ordinal":
            model_class = H2OOrdinalGridSearch
        elif model_type == "AutoEncoder":
            model_class = H2OAutoEncoderGridSearch
        elif model_type == "DimReduction":
            model_class = H2ODimReductionGridSearch
        else:
            raise NotImplementedError(model_type)
        return model_class

    def get_grid(self, sort_by=None, decreasing=None):
        """
        Retrieve an H2OGridSearch instance.

        Optionally specify a metric by which to sort models and a sort order.
        Note that if neither cross-validation nor a validation frame is used in the grid search, then the
        training metrics will display in the "get grid" output. If a validation frame is passed to the grid, and
        ``nfolds = 0``, then the validation metrics will display. However, if ``nfolds`` > 1, then cross-validation
        metrics will display even if a validation frame is provided.

        :param str sort_by: A metric by which to sort the models in the grid space. Choices are: ``"logloss"``,
            ``"residual_deviance"``, ``"mse"``, ``"auc"``, ``"r2"``, ``"accuracy"``, ``"precision"``, ``"recall"``,
            ``"f1"``, etc.
        :param bool decreasing: Sort the models in decreasing order of metric if true, otherwise sort in increasing
            order (default).

        :returns: A new H2OGridSearch instance optionally sorted on the specified metric.
        """
        if sort_by is None and decreasing is None: return self

        grid_json = h2o.api("GET /99/Grids/%s" % self._id, data={"sort_by": sort_by, "decreasing": decreasing})
        grid = H2OGridSearch(self.model, self.hyper_params, self._id)
        grid.models = [h2o.get_model(key['name']) for key in grid_json['model_ids']]  # reordered
        first_model_json = h2o.api("GET /99/Models/%s" % grid_json['model_ids'][0]['name'])['models'][0]
        model_class = H2OGridSearch._metrics_class(first_model_json)
        m = model_class()
        m._id = self._id
        m._grid_json = grid_json
        # m._metrics_class = metrics_class
        m._parms = grid._parms
        H2OEstimator.mixin(grid, model_class)
        grid.__dict__.update(m.__dict__.copy())
        return grid

    # Deprecated functions; left here for backward compatibility
    _bcim = {
        "giniCoef": lambda self, *args, **kwargs: self.gini(*args, **kwargs)
    }

    @deprecated("grid.sort_by() is deprecated; use grid.get_grid() instead")
    def sort_by(self, metric, increasing=True):
        """Deprecated since 2016-12-12, use grid.get_grid() instead."""

        if metric[-1] != ')': metric += '()'
        c_values = [list(x) for x in zip(*sorted(eval('self.' + metric + '.items()'), key=lambda k_v: k_v[1]))]
        c_values.insert(1, [self.get_hyperparams(model_id, display=False) for model_id in c_values[0]])
        if not increasing:
            for col in c_values: col.reverse()
        if metric[-2] == '(': metric = metric[:-2]
        return H2OTwoDimTable(
            col_header=['Model Id', 'Hyperparameters: [' + ', '.join(list(self.hyper_params.keys())) + ']', metric],
            table_header='Grid Search Results for ' + self.model.__class__.__name__,
            cell_values=[list(x) for x in zip(*c_values)])


# -*- coding: utf-8 -*-

import os
from nbformat.v4.nbbase import new_notebook, new_code_cell, new_markdown_cell, new_raw_cell
from jupytext.compare import compare, compare_notebooks
import jupytext

def test_read_simple_file(script="""# ---
# title: Simple file
# ---

# %% [markdown]
# This is a markdown cell

# %% [md]
# This is also a markdown cell

# %% [raw]
# This is a raw cell

# %%% sub-cell title
# This is a sub-cell

# %%%% sub-sub-cell title
# This is a sub-sub-cell

# %% And now a code cell
1 + 2 + 3 + 4
5
6
# %%magic # this is a commented magic, not a cell

7
"""):
    nb = jupytext.reads(script, 'py:percent')
    compare_notebooks(new_notebook(cells=[
        new_raw_cell('---\ntitle: Simple file\n---'),
        new_markdown_cell('This is a markdown cell'),
        new_markdown_cell('This is also a markdown cell', metadata={'region_name': 'md'}),
        new_raw_cell('This is a raw cell'),
        new_code_cell('# This is a sub-cell', metadata={'title': 'sub-cell title', 'cell_depth': 1}),
        new_code_cell('# This is a sub-sub-cell', metadata={'title': 'sub-sub-cell title', 'cell_depth': 2}),
        new_code_cell('''1 + 2 + 3 + 4
5
6
%%magic # this is a commented magic, not a cell

7''', metadata={'title': 'And now a code cell'})]), nb)

    script2 = jupytext.writes(nb, 'py:percent')
    compare(script2, script)

def test_read_cell_with_metadata(
        script="""# %% a code cell with parameters {"tags": ["parameters"]}
a = 3
"""):
    nb = jupytext.reads(script, 'py:percent')
    assert len(nb.cells) == 1
    assert nb.cells[0].cell_type == 'code'
    assert nb.cells[0].source == 'a = 3'
    assert nb.cells[0].metadata == {
        'title': 'a code cell with parameters',
        'tags': ['parameters']}

    script2 = jupytext.writes(nb, 'py:percent')
    compare(script2, script)

def test_read_nbconvert_script(script="""
# coding: utf-8

# A markdown cell

# In[1]:

import pandas as pd

pd.options.display.max_rows = 6
pd.options.display.max_columns = 20

# Another markdown cell

# In[2]:

1 + 1

# Again, a markdown cell

# In[33]:

2 + 2

# <codecell>

3 + 3
"""):
    assert jupytext.formats.guess_format(script, '.py')[0] == 'percent'
    nb = jupytext.reads(script, '.py')
    assert len(nb.cells) == 5

def test_read_remove_blank_lines(script="""# %%
import pandas as pd

# %% Display a data frame
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]},
                  index=pd.Index(['x0', 'x1'], name='x'))
df

# %% Pandas plot {"tags": ["parameters"]}
df.plot(kind='bar')

# %% sample class
class MyClass:
    pass

# %% a function
def f(x):
    return 42 * x

"""):
    nb = jupytext.reads(script, 'py')
    assert len(nb.cells) == 5
    for i in range(5):
        assert nb.cells[i].cell_type == 'code'
        assert not nb.cells[i].source.startswith('\n')
        assert not nb.cells[i].source.endswith('\n')

    script2 = jupytext.writes(nb, 'py:percent')
    compare(script2, script)

def test_no_crash_on_square_bracket(script="""# %% In [2]
print('Hello')
"""):
    nb = jupytext.reads(script, 'py')
    script2 = jupytext.writes(nb, 'py:percent')
    compare(script2, script)

def test_nbconvert_cell(script="""# In[2]:
print('Hello')
"""):
    nb = jupytext.reads(script, 'py')
    script2 = jupytext.writes(nb, 'py:percent')
    expected = """# %%
print('Hello')
"""
    compare(script2, expected)

def test_nbformat_v3_nbpy_cell(script="""# <codecell>
print('Hello')
"""):
    nb = jupytext.reads(script, 'py')
    script2 = jupytext.writes(nb, 'py:percent')
    expected = """# %%
print('Hello')
"""
    compare(script2, expected)

def test_multiple_empty_cells():
    nb = new_notebook(cells=[new_code_cell(), new_code_cell(), new_code_cell()],
                      metadata={'jupytext': {'notebook_metadata_filter': '-all'}})
    text = jupytext.writes(nb, 'py:percent')
    expected = """# %%

# %%

# %%
"""
    compare(text, expected)
    nb2 = jupytext.reads(text, 'py:percent')
    nb2.metadata = nb.metadata
    compare(nb2, nb)

def test_first_cell_markdown_191():
    text = """# %% [markdown]
# Docstring

# %%
from math import pi

# %% [markdown]
# Another markdown cell
"""

    nb = jupytext.reads(text, 'py')
    assert nb.cells[0].cell_type == 'markdown'
    assert nb.cells[1].cell_type == 'code'
    assert nb.cells[2].cell_type == 'markdown'

def test_multiline_comments_in_markdown_1():
    text = """# %% [markdown]
'''
a
long
cell
'''
"""
    nb = jupytext.reads(text, 'py')
    assert len(nb.cells) == 1
    assert nb.cells[0].cell_type == 'markdown'
    assert nb.cells[0].source == "a\nlong\ncell"
    py = jupytext.writes(nb, 'py')
    compare(py, text)

def test_multiline_comments_in_markdown_2():
    text = '''# %% [markdown]
"""
a
long
cell
"""
'''
    nb = jupytext.reads(text, 'py')
    assert len(nb.cells) == 1
    assert nb.cells[0].cell_type == 'markdown'
    assert nb.cells[0].source == "a\nlong\ncell"
    py = jupytext.writes(nb, 'py')
    compare(py, text)

def test_multiline_comments_format_option():
    text = '''# %% [markdown]
"""
a
long
cell
"""
'''
    nb = new_notebook(cells=[new_markdown_cell("a\nlong\ncell")],
                      metadata={'jupytext': {'cell_markers': '"""',
                                             'notebook_metadata_filter': '-all'}})
    py = jupytext.writes(nb, 'py:percent')
    compare(py, text)

def test_multiline_comments_in_raw_cell():
    text = '''# %% [raw]
"""
some
text
"""
'''
    nb = jupytext.reads(text, 'py')
    assert len(nb.cells) == 1
    assert nb.cells[0].cell_type == 'raw'
    assert nb.cells[0].source == "some\ntext"
    py = jupytext.writes(nb, 'py')
    compare(py, text)

def test_multiline_comments_in_markdown_cell_no_line_return():
    text = '''# %% [markdown]
"""a
long
cell"""
'''
    nb = jupytext.reads(text, 'py')
    assert len(nb.cells) == 1
    assert nb.cells[0].cell_type == 'markdown'
    assert nb.cells[0].source == "a\nlong\ncell"

def test_multiline_comments_in_markdown_cell_is_robust_to_additional_cell_marker():
    text = '''# %% [markdown]
"""
some text, and a fake cell marker
# %% [raw]
"""
'''
    nb = jupytext.reads(text, 'py')
    assert len(nb.cells) == 1
    assert nb.cells[0].cell_type == 'markdown'
    assert nb.cells[0].source == "some text, and a fake cell marker\n# %% [raw]"
    py = jupytext.writes(nb, 'py')
    compare(py, text)

def test_cell_markers_option_in_contents_manager(tmpdir):
    tmp_ipynb = str(tmpdir.join('notebook.ipynb'))
    tmp_py = str(tmpdir.join('notebook.py'))

    cm = jupytext.TextFileContentsManager()
    cm.root_dir = str(tmpdir)

    nb = new_notebook(cells=[new_code_cell('1 + 1'), new_markdown_cell('a\nlong\ncell')],
                      metadata={'jupytext': {'formats': 'ipynb,py:percent',
                                             'notebook_metadata_filter': '-all',
                                             'cell_markers': "'''"}})
    cm.save(model=dict(type='notebook', content=nb), path='notebook.ipynb')

    assert os.path.isfile(tmp_ipynb)
    assert os.path.isfile(tmp_py)

    with open(tmp_py) as fp:
        text = fp.read()

    compare(text, """# %%
1 + 1

# %% [markdown]
'''
a
long
cell
'''
""")

    nb2 = jupytext.read(tmp_py)
    compare_notebooks(nb, nb2)

def test_default_cell_markers_in_contents_manager(tmpdir):
    tmp_ipynb = str(tmpdir.join('notebook.ipynb'))
    tmp_py = str(tmpdir.join('notebook.py'))

    cm = jupytext.TextFileContentsManager()
    cm.root_dir = str(tmpdir)
    cm.default_cell_markers = "'''"

    nb = new_notebook(cells=[new_code_cell('1 + 1'), new_markdown_cell('a\nlong\ncell')],
                      metadata={'jupytext': {'formats': 'ipynb,py:percent',
                                             'notebook_metadata_filter': '-all'}})
    cm.save(model=dict(type='notebook', content=nb), path='notebook.ipynb')

    assert os.path.isfile(tmp_ipynb)
    assert os.path.isfile(tmp_py)

    with open(tmp_py) as fp:
        text = fp.read()

    compare(text, """# %%
1 + 1

# %% [markdown]
'''
a
long
cell
'''
""")

    nb2 = jupytext.read(tmp_py)
    compare_notebooks(nb, nb2)

def test_default_cell_markers_in_contents_manager_does_not_impact_light_format(tmpdir):
    tmp_ipynb = str(tmpdir.join('notebook.ipynb'))
    tmp_py = str(tmpdir.join('notebook.py'))

    cm = jupytext.TextFileContentsManager()
    cm.root_dir = str(tmpdir)
    cm.default_cell_markers = "'''"

    nb = new_notebook(cells=[new_code_cell('1 + 1'), new_markdown_cell('a\nlong\ncell')],
                      metadata={'jupytext': {'formats': 'ipynb,py',
                                             'notebook_metadata_filter': '-all'}})
    cm.save(model=dict(type='notebook', content=nb), path='notebook.ipynb')

    assert os.path.isfile(tmp_ipynb)
    assert os.path.isfile(tmp_py)

    with open(tmp_py) as fp:
        text = fp.read()

    compare(text, """1 + 1

# a
# long
# cell
""")

    nb2 = jupytext.read(tmp_py)
    compare_notebooks(nb, nb2)

def test_single_triple_quote_works(no_jupytext_version_number, text='''# ---
# jupyter:
#   jupytext:
#     cell_markers: '"""'
#     formats: ipynb,py:percent
#     text_representation:
#       extension: .py
#       format_name: percent
# ---

# %%
print("hello")
''', notebook=new_notebook(cells=[new_code_cell('print("hello")')])):
    compare_notebooks(jupytext.reads(text, 'py'), notebook)

def test_docstring_with_quadruple_quote(nb=new_notebook(cells=[
    new_code_cell('''def fun_1(df):
  """"
  docstring starting with 4 double quotes and ending with 3
  """
  return df'''),
    new_code_cell('''def fun_2(df):
  """
  docstring
  """
  return df''')
])):
    """Reproduces https://github.com/mwouts/jupytext/issues/460"""
    py = jupytext.writes(nb, 'py:percent')
    nb2 = jupytext.reads(py, 'py')
    compare_notebooks(nb2, nb)


# Configuration file for the skipper script

intro_duration=60 # Duration in seconds, change this value


all_item_types = {
    'cards': 'createCard',
    'boards': 'createBoard',
    'lists': 'createList',
    'comments': 'commentCard',
    'createChecklist': 'addChecklistToCard',
    'updateCheck': 'updateCheckItemStateOnCard',
    'moveCard': 'updateCard'
}


if __name__ == "__main__":

    import os
    import sys

    sys.path.append(os.getcwd() + "/../../")

    import pandas as pd
    import itertools
    from kge_from_text import folder_definitions as fd
    import kge_from_text.models.term_embeddings as tt
    import kge_from_text.bridges.clean_bridge as bridge
    from kge_from_text.evaluators.evaluator_handler import EvaluatorHandler
    from kge_from_text.evaluators.analogy_evaluator import AnalogyEvaluator
    import kge_from_text.models.tee_embeddings as tee

    combinations = [(5, 400), (5, 500)]

    entity_vector_name = "2016_data/entity_vectors"
    type_vector_name = "2016_data/type_vectors"
    conactenated_name = "2016_data/concatenated_vectors"
    conactenated_name_time = "2016_data/concatenated_vectors_time"
    temporal_csv = "2016_data/temporal_vectors.csv"

    annotated_entity_file = "2016_data/annotated_text_with_entities"
    annotated_type_file = "2016_data/annotated_text_with_types"
    type_of_entity_file = "2016_data/type_to_entity_data.ttl"

    pure_text_model = "2016_data/text_with_words"

    # Declare An Evaluator
    evalu = EvaluatorHandler(fd.EVALUATION_RESULTS_ROOT, name="word_base")

    for w_e, s_e in combinations:

        # ENTITY
        model_w = tt.TermEmbedding("text")
        model_w.fit(input_text=fd.STARTING_DATA_ROOT + pure_text_model,
                    output_file_path=fd.PRODUCED_MODELS_ROOT + "2016_data/", _size=s_e, _window=w_e, load_model_if_exits = True)

        analogies = pd.read_csv(fd.GOLD_STANDARDS + "mikolov", names=["First", "Second", "Third", "Fourth"],
                                sep=" ")
        br = bridge.CleanBridge()

        analogy_eval = AnalogyEvaluator(br, model_w, analogies)

        evalu.run_evaluation(analogy_eval)

        analogies = pd.read_csv(fd.GOLD_STANDARDS + "currency", names=["First", "Second", "Third", "Fourth"],
                                sep=" ")

        analogy_eval = AnalogyEvaluator(br, model_w, analogies)

        evalu.run_evaluation(analogy_eval)


# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import six

import st2common.content.utils as content_utils

from st2common import log as logging
from st2common.constants.meta import ALLOWED_EXTS
from st2common.bootstrap.base import ResourceRegistrar
from st2common.models.api.action import ActionAliasAPI
from st2common.persistence.actionalias import ActionAlias

__all__ = [
    'AliasesRegistrar',
    'register_aliases'
]

LOG = logging.getLogger(__name__)

class AliasesRegistrar(ResourceRegistrar):
    ALLOWED_EXTENSIONS = ALLOWED_EXTS

    def register_aliases_from_packs(self, base_dirs):
        """
        Discover all the packs in the provided directory and register aliases from all of the
        discovered packs.

        :return: Number of aliases registered.
        :rtype: ``int``
        """
        registered_count = 0

        content = self._pack_loader.get_content(base_dirs=base_dirs,
                                                content_type='aliases')

        for pack, aliases_dir in six.iteritems(content):
            try:
                LOG.debug('Registering aliases from pack %s:, dir: %s', pack, aliases_dir)
                aliases = self._get_aliases_from_pack(aliases_dir)
                count = self._register_aliases_from_pack(pack=pack, aliases=aliases)
                registered_count += count
            except:
                LOG.exception('Failed registering all aliases from pack: %s', aliases_dir)

        return registered_count

    def register_aliases_from_pack(self, pack_dir):
        """
        Register all the aliases from the provided pack.

        :return: Number of aliases registered.
        :rtype: ``int``
        """
        pack_dir = pack_dir[:-1] if pack_dir.endswith('/') else pack_dir
        _, pack = os.path.split(pack_dir)
        aliases_dir = self._pack_loader.get_content_from_pack(pack_dir=pack_dir,
                                                              content_type='aliases')

        registered_count = 0

        if not aliases_dir:
            return registered_count

        LOG.debug('Registering aliases from pack %s:, dir: %s', pack, aliases_dir)

        try:
            aliases = self._get_aliases_from_pack(aliases_dir=aliases_dir)
            registered_count = self._register_aliases_from_pack(pack=pack, aliases=aliases)
        except:
            LOG.exception('Failed registering all aliases from pack: %s', aliases_dir)
            return 0

        return registered_count

    def _get_aliases_from_pack(self, aliases_dir):
        return self.get_resources_from_pack(resources_dir=aliases_dir)

    def _register_action_alias(self, pack, action_alias):
        content = self._meta_loader.load(action_alias)
        pack_field = content.get('pack', None)
        if not pack_field:
            content['pack'] = pack
            pack_field = pack
        if pack_field != pack:
            raise Exception('Model is in pack "%s" but field "pack" is different: %s' %
                            (pack, pack_field))

        action_alias_api = ActionAliasAPI(**content)
        action_alias_api.validate()
        action_alias_db = ActionAliasAPI.to_model(action_alias_api)

        try:
            action_alias_db.id = ActionAlias.get_by_name(action_alias_api.name).id
        except ValueError:
            LOG.info('ActionAlias %s not found. Creating new one.', action_alias)

        try:
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
            extra = {'action_alias_db': action_alias_db}
            LOG.audit('Action alias updated. Action alias %s from %s.', action_alias_db,
                      action_alias, extra=extra)
        except Exception:
            LOG.exception('Failed to create action alias %s.', action_alias_api.name)
            raise

    def _register_aliases_from_pack(self, pack, aliases):
        registered_count = 0

        for alias in aliases:
            try:
                LOG.debug('Loading alias from %s.', alias)
                self._register_action_alias(pack, alias)
            except Exception:
                LOG.exception('Unable to register alias: %s', alias)
                continue
            else:
                registered_count += 1

        return registered_count

def register_aliases(packs_base_paths=None, pack_dir=None):
    if packs_base_paths:
        assert(isinstance(packs_base_paths, list))

    if not packs_base_paths:
        packs_base_paths = content_utils.get_packs_base_paths()

    registrar = AliasesRegistrar()

    if pack_dir:
        result = registrar.register_aliases_from_pack(pack_dir=pack_dir)
    else:
        result = registrar.register_aliases_from_packs(base_dirs=packs_base_paths)

    return result


import sys
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import firebase_admin
from firebase_admin import credentials
import pandas as pd
import numpy as np
import random
# import google_cloud_firestore
from google.cloud import firestore as fs
cred = credentials.Certificate("./keys/firebaseAdminAuth.json")

def getRestaurants():
    db = firestore.client()

    rst_ref = db.collection(u'root/restaurants/rstList')

    docs = rst_ref.stream()

    rst_list = []

    for doc in docs:
        rst_list.append(doc.id)
        # print(f'{doc.id} => {doc.to_dict()}')

    return rst_list

def checkDocument(docPath):
    db = firestore.client()

    doc_ref = db.document(docPath)

    return doc_ref.get().exists


# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import tensorflow as tf

from tensorflow.python import ipu

from ipu_tensorflow_addons.keras.layers import Embedding, LSTM
from tensorflow.keras.layers import Dense
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.optimizers import Adam

if tf.__version__[0] != '2':
    raise ImportError("TensorFlow 2 is required for this example")

max_features = 20000
minibatch_size = 32

# Define the dataset.
def get_dataset():
    (x_train, y_train), (_, _) = imdb.load_data(num_words=max_features)

    x_train = sequence.pad_sequences(x_train, maxlen=80)

    ds = tf.data.Dataset.from_tensor_slices((x_train, y_train))
    ds = ds.repeat()
    ds = ds.map(lambda x, y: (x, tf.cast(y, tf.int32)))
    ds = ds.batch(minibatch_size, drop_remainder=True)
    return ds

# Define the model.
def get_model():
    return tf.keras.Sequential(
        [Embedding(max_features, 128),
         LSTM(128, dropout=0.2),
         Dense(1, activation='sigmoid')])

def main():
    # Configure IPUs.
    cfg = ipu.config.IPUConfig()
    cfg.auto_select_ipus = 1
    cfg.configure_ipu_system()

    # Set up IPU strategy.
    strategy = ipu.ipu_strategy.IPUStrategy()
    with strategy.scope():

        model = get_model()

        model.compile(steps_per_execution=384, loss='binary_crossentropy', optimizer=Adam(0.005))
        model.fit(get_dataset(), steps_per_epoch=768, epochs=3)

if __name__ == '__main__':
    main()


# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.

import re  # noqa: F401
import sys  # noqa: F401

from datadog_api_client.v2.model_utils import (  # noqa: F401
    ApiTypeError,
    ModelComposed,
    ModelNormal,
    ModelSimple,
    cached_property,
    change_keys_js_to_python,
    convert_js_args_to_python_args,
    date,
    datetime,
    file_type,
    none_type,
    validate_get_composed_info,
)

def lazy_import():
    from datadog_api_client.v2.model.dashboard_list_item_request import DashboardListItemRequest

    globals()["DashboardListItemRequest"] = DashboardListItemRequest

class DashboardListDeleteItemsRequest(ModelNormal):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.

    Attributes:
      allowed_values (dict): The key is the tuple path to the attribute
          and the for var_name this is (var_name,). The value is a dict
          with a capitalized key describing the allowed value and an allowed
          value. These dicts store the allowed enum values.
      attribute_map (dict): The key is attribute name
          and the value is json key in definition.
      discriminator_value_class_map (dict): A dict to go from the discriminator
          variable value to the discriminator class name.
      validations (dict): The key is the tuple path to the attribute
          and the for var_name this is (var_name,). The value is a dict
          that stores validations for max_length, min_length, max_items,
          min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
          inclusive_minimum, and regex.
      additional_properties_type (tuple): A tuple of classes accepted
          as additional properties values.
    """

    allowed_values = {}

    validations = {}

    additional_properties_type = None

    _nullable = False

    @cached_property
    def openapi_types():
        """
        This must be a method because a model may have properties that are
        of type self, this must run after the class is loaded

        Returns
            openapi_types (dict): The key is attribute name
                and the value is attribute type.
        """
        lazy_import()
        return {
            "dashboards": ([DashboardListItemRequest],),  # noqa: E501
        }

    @cached_property
    def discriminator():
        return None

    attribute_map = {
        "dashboards": "dashboards",  # noqa: E501
    }

    _composed_schemas = {}

    required_properties = set(
        [
            "_data_store",
            "_check_type",
            "_spec_property_naming",
            "_path_to_item",
            "_configuration",
            "_visited_composed_classes",
        ]
    )

    @convert_js_args_to_python_args
    def __init__(self, *args, **kwargs):  # noqa: E501
        """DashboardListDeleteItemsRequest - a model defined in OpenAPI

        Keyword Args:
            _check_type (bool): if True, values for parameters in openapi_types
                                will be type checked and a TypeError will be
                                raised if the wrong type is input.
                                Defaults to True
            _path_to_item (tuple/list): This is a list of keys or values to
                                drill down to the model in received_data
                                when deserializing a response
            _spec_property_naming (bool): True if the variable names in the input data
                                are serialized names, as specified in the OpenAPI document.
                                False if the variable names in the input data
                                are pythonic names, e.g. snake case (default)
            _configuration (Configuration): the instance to use when
                                deserializing a file_type parameter.
                                If passed, type conversion is attempted
                                If omitted no type conversion is done.
            _visited_composed_classes (tuple): This stores a tuple of
                                classes that we have traveled through so that
                                if we see that class again we will not use its
                                discriminator again.
                                When traveling through a discriminator, the
                                composed schema that is
                                is traveled through is added to this set.
                                For example if Animal has a discriminator
                                petType and we pass in "Dog", and the class Dog
                                allOf includes Animal, we move through Animal
                                once using the discriminator, and pick Dog.
                                Then in Dog, we will make an instance of the
                                Animal class but this time we won't travel
                                through its discriminator because we passed in
                                _visited_composed_classes = (Animal,)
            dashboards ([DashboardListItemRequest]): List of dashboards to delete from the dashboard list.. [optional]  # noqa: E501
        """

        _check_type = kwargs.pop("_check_type", True)
        _spec_property_naming = kwargs.pop("_spec_property_naming", False)
        _path_to_item = kwargs.pop("_path_to_item", ())
        _configuration = kwargs.pop("_configuration", None)
        _visited_composed_classes = kwargs.pop("_visited_composed_classes", ())

        if args:
            raise ApiTypeError(
                "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments."
                % (
                    args,
                    self.__class__.__name__,
                ),
                path_to_item=_path_to_item,
                valid_classes=(self.__class__,),
            )

        self._data_store = {}
        self._check_type = _check_type
        self._spec_property_naming = _spec_property_naming
        self._path_to_item = _path_to_item
        self._configuration = _configuration
        self._visited_composed_classes = _visited_composed_classes + (self.__class__,)

        for var_name, var_value in kwargs.items():
            if (
                var_name not in self.attribute_map
                and self._configuration is not None
                and self._configuration.discard_unknown_keys
                and self.additional_properties_type is None
            ):
                # discard variable.
                continue
            setattr(self, var_name, var_value)


from .claims import Claims
from .cose import COSE
from .cose_key import COSEKey
from .cwt import (
    CWT,
    decode,
    encode,
    encode_and_encrypt,
    encode_and_mac,
    encode_and_sign,
    set_private_claim_names,
)
from .encrypted_cose_key import EncryptedCOSEKey
from .exceptions import CWTError, DecodeError, EncodeError, VerifyError
from .helpers.hcert import load_pem_hcert_dsc
from .recipient import Recipient
from .signer import Signer

__version__ = "1.3.2"
__title__ = "cwt"
__description__ = "A Python implementation of CWT/COSE"
__url__ = "https://python-cwt.readthedocs.io"
__uri__ = __url__
__doc__ = __description__ + " <" + __uri__ + ">"
__author__ = "AJITOMI Daisuke"
__email__ = "ajitomi@gmail.com"
__license__ = "MIT"
__copyright__ = "Copyright 2021 AJITOMI Daisuke"
__all__ = [
    "encode",
    "encode_and_mac",
    "encode_and_sign",
    "encode_and_encrypt",
    "decode",
    "set_private_claim_names",
    "CWT",
    "COSE",
    "COSEKey",
    "EncryptedCOSEKey",
    "Claims",
    "Recipient",
    "Signer",
    "load_pem_hcert_dsc",
    "CWTError",
    "EncodeError",
    "DecodeError",
    "VerifyError",
]


# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Pacvim(MakefilePackage):
    """Pacvim is a command-line-based game based off of Pacman.
       The main purpose of this software is to familiarize individuals
       with Vim."""

    homepage = "https://github.com/jmoon018/PacVim"
    url      = "https://github.com/jmoon018/PacVim/archive/v1.1.1.tar.gz"

    version('1.1.1', sha256='c869c5450fbafdfe8ba8a8a9bba3718775926f276f0552052dcfa090d21acb28')

    depends_on('ncurses')

    def edit(self, stage, prefix):
        makefile = FileFilter('Makefile')

        makefile.filter(r'PREFIX = /usr/local',
                        'PREFIX={0}'.format(self.prefix))


#!/usr/bin/python3.6

activate_this = '/home/ubuntu/flaskapp/venv/bin/activate_this.py'
with open(activate_this) as f:
 exec(f.read(), dict(__file__=activate_this))

import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/home/ubuntu/flaskapp/flaskapp/")

from manage import app as application

if __name__ == "__main__":
    application.run()


# -*- coding: utf-8 -*-
from __future__ import absolute_import
import theano
import theano.tensor as T
import numpy as np

from .. import activations, initializations
from ..utils.theano_utils import shared_zeros, alloc_zeros_matrix
from ..layers.core import Layer
from .. import regularizers

from six.moves import range

class BLSTM(Layer):
    def __init__(self, input_dim, output_dim,
        init='glorot_uniform', inner_init='orthogonal',
        activation='tanh', inner_activation='hard_sigmoid',
        weights=None, truncate_gradient=-1, return_sequences=False,
        is_entity=False, regularize=False):

        self.is_entity = is_entity
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.truncate_gradient = truncate_gradient
        self.return_sequences = return_sequences

        self.init = initializations.get(init)
        self.inner_init = initializations.get(inner_init)
        self.activation = activations.get(activation)
        self.inner_activation = activations.get(inner_activation)
        self.input = T.tensor3()

        self.W_if = self.init((self.input_dim, self.output_dim))
        self.W_ib = self.init((self.input_dim, self.output_dim))
        self.U_if = self.inner_init((self.output_dim, self.output_dim))
        self.U_ib = self.inner_init((self.output_dim, self.output_dim))
        self.b_if = shared_zeros((self.output_dim))
        self.b_ib = shared_zeros((self.output_dim))

        self.W_ff = self.init((self.input_dim, self.output_dim))
        self.W_fb = self.init((self.input_dim, self.output_dim))
        self.U_ff = self.inner_init((self.output_dim, self.output_dim))
        self.U_fb = self.inner_init((self.output_dim, self.output_dim))
        self.b_ff = shared_zeros((self.output_dim))
        self.b_fb = shared_zeros((self.output_dim))

        self.W_cf = self.init((self.input_dim, self.output_dim))
        self.W_cb = self.init((self.input_dim, self.output_dim))
        self.U_cf = self.inner_init((self.output_dim, self.output_dim))
        self.U_cb = self.inner_init((self.output_dim, self.output_dim))
        self.b_cf = shared_zeros((self.output_dim))
        self.b_cb = shared_zeros((self.output_dim))

        self.W_of = self.init((self.input_dim, self.output_dim))
        self.W_ob = self.init((self.input_dim, self.output_dim))
        self.U_of = self.inner_init((self.output_dim, self.output_dim))
        self.U_ob = self.inner_init((self.output_dim, self.output_dim))
        self.b_of = shared_zeros((self.output_dim))
        self.b_ob = shared_zeros((self.output_dim))

        self.W_yf = self.init((self.output_dim, self.output_dim))
        self.W_yb = self.init((self.output_dim, self.output_dim))
        #self.W_y = self.init((self.output_dim, self.output_dim))
        self.b_y = shared_zeros((self.output_dim))

        self.params = [
            self.W_if, self.U_if, self.b_if,
            self.W_ib, self.U_ib, self.b_ib,

            self.W_cf, self.U_cf, self.b_cf,
            self.W_cb, self.U_cb, self.b_cb,

            self.W_ff, self.U_ff, self.b_ff,
            self.W_fb, self.U_fb, self.b_fb,

            self.W_of, self.U_of, self.b_of,
            self.W_ob, self.U_ob, self.b_ob,

            self.W_yf, self.W_yb, self.b_y
            #self.W_y, self.b_y
        ]
        if regularize:
            self.regularizers = []
            for i in self.params:
                self.regularizers.append(regularizers.my_l2)

        if weights is not None:
            self.set_weights(weights)

    def _step(self,
        xi_t, xf_t, xo_t, xc_t,
        h_tm1, c_tm1,
        u_i, u_f, u_o, u_c):
        i_t = self.inner_activation(xi_t + T.dot(h_tm1, u_i))
        f_t = self.inner_activation(xf_t + T.dot(h_tm1, u_f))
        c_t = f_t * c_tm1 + i_t * self.activation(xc_t + T.dot(h_tm1, u_c))
        o_t = self.inner_activation(xo_t + T.dot(h_tm1, u_o))
        h_t = o_t * self.activation(c_t)
        return h_t, c_t

    def output(self, train):
        X = self.get_input(train)
        X = X.dimshuffle((1,0,2))

        if self.is_entity:
            Entity = X[-1:].dimshuffle(1,0,2)
            X = X[:-1]

        b_y = self.b_y
        b_yn = T.repeat(T.repeat(b_y.reshape((1,self.output_dim)),X.shape[0],axis=0).reshape((1,X.shape[0],self.output_dim)), X.shape[1], axis=0)

        xif = T.dot(X, self.W_if) + self.b_if
        xib = T.dot(X, self.W_ib) + self.b_ib

        xff = T.dot(X, self.W_ff) + self.b_ff
        xfb = T.dot(X, self.W_fb) + self.b_fb

        xcf = T.dot(X, self.W_cf) + self.b_cf
        xcb = T.dot(X, self.W_cb) + self.b_cb

        xof = T.dot(X, self.W_of) + self.b_of
        xob = T.dot(X, self.W_ob) + self.b_ob

        [outputs_f, memories_f], updates_f = theano.scan(
            self._step,
            sequences=[xif, xff, xof, xcf],
            outputs_info=[
                alloc_zeros_matrix(X.shape[1], self.output_dim),
                alloc_zeros_matrix(X.shape[1], self.output_dim)
            ],
            non_sequences=[self.U_if, self.U_ff, self.U_of, self.U_cf],
            truncate_gradient=self.truncate_gradient
        )
        [outputs_b, memories_b], updates_b = theano.scan(
            self._step,
            sequences=[xib, xfb, xob, xcb],
            outputs_info=[
                alloc_zeros_matrix(X.shape[1], self.output_dim),
                alloc_zeros_matrix(X.shape[1], self.output_dim)
            ],
            non_sequences=[self.U_ib, self.U_fb, self.U_ob, self.U_cb],
            truncate_gradient=self.truncate_gradient
        )
        if self.return_sequences:
            y = T.add(T.add(
                    T.tensordot(outputs_f.dimshuffle((1,0,2)), self.W_yf, [[2],[0]]),
                    T.tensordot(outputs_b[::-1].dimshuffle((1,0,2)), self.W_yb, [[2],[0]])),
                b_yn)
            # y = T.add(T.tensordot(
            #     T.add(outputs_f.dimshuffle((1, 0, 2)),
            #           outputs_b[::-1].dimshuffle((1,0,2))),
            #     self.W_y,[[2],[0]]),b_yn)
            if self.is_entity:
                return T.concatenate([y, Entity], axis=1)
            else:
                return y
        return T.concatenate((outputs_f[-1], outputs_b[0]))

    def get_config(self):
        return {"name":self.__class__.__name__,
            "input_dim":self.input_dim,
            "output_dim":self.output_dim,
            "init":self.init.__name__,
            "inner_init":self.inner_init.__name__,
            "activation":self.activation.__name__,
            "truncate_gradient":self.truncate_gradient,
            "return_sequences":self.return_sequences}

class BRNN(Layer):
    '''
        Fully connected Bi-directional RNN where:
            Output at time=t is fed back to input for time=t+1 in a forward pass
            Output at time=t is fed back to input for time=t-1 in a backward pass
    '''
    def __init__(self, input_dim, output_dim,
        init='uniform', inner_init='orthogonal', activation='sigmoid', weights=None,
        truncate_gradient=-1,  return_sequences=False, is_entity=False, regularize=False):
        #whyjay
        self.is_entity = is_entity

        self.init = initializations.get(init)
        self.inner_init = initializations.get(inner_init)
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.truncate_gradient = truncate_gradient
        self.activation = activations.get(activation)
        self.return_sequences = return_sequences
        self.input = T.tensor3()
        self.W_o  =  self.init((self.input_dim, self.output_dim))
        self.W_if = self.init((self.input_dim, self.output_dim))    # Input -> Forward
        self.W_ib = self.init((self.input_dim, self.output_dim))    # Input -> Backward
        self.W_ff = self.init((self.output_dim, self.output_dim))   # Forward tm1 -> Forward t
        self.W_bb = self.init((self.output_dim, self.output_dim))   # Backward t -> Backward tm1
        self.b_if = shared_zeros((self.output_dim))
        self.b_ib = shared_zeros((self.output_dim))
        self.b_f = shared_zeros((self.output_dim))
        self.b_b = shared_zeros((self.output_dim))
        self.b_o =  shared_zeros((self.output_dim))
        self.params = [self.W_o,self.W_if,self.W_ib, self.W_ff, self.W_bb,self.b_if,self.b_ib, self.b_f, self.b_b, self.b_o]

        if regularize:
            self.regularizers = []
            for i in self.params:
                self.regularizers.append(regularizers.my_l2)

        if weights is not None:
            self.set_weights(weights)

    def _step(self, x_t, h_tm1, u,b):
        return self.activation(x_t + T.dot(h_tm1, u)+b)

    def output(self, train):
        X = self.get_input(train) # shape: (nb_samples, time (padded with zeros at the end), input_dim)
        # new shape: (time, nb_samples, input_dim) -> because theano.scan iterates over main dimension
        X = X.dimshuffle((1, 0, 2))

        if self.is_entity:
            lenX=X.shape[0]
            Entity=X[lenX-1:].dimshuffle(1,0,2)
            X=X[:lenX-1]

        xf = self.activation(T.dot(X, self.W_if) + self.b_if)
        xb = self.activation(T.dot(X, self.W_ib) + self.b_ib)
        b_o=self.b_o
        b_on= T.repeat(T.repeat(b_o.reshape((1,self.output_dim)),X.shape[0],axis=0).reshape((1,X.shape[0],self.output_dim)),X.shape[1],axis=0)

        # Iterate forward over the first dimension of the x array (=time).
        outputs_f, updates_f = theano.scan(
            self._step,  # this will be called with arguments (sequences[i], outputs[i-1], non_sequences[i])
            sequences=xf,  # tensors to iterate over, inputs to _step
            # initialization of the output. Input to _step with default tap=-1.
            outputs_info=alloc_zeros_matrix(X.shape[1], self.output_dim),
            non_sequences=[self.W_ff,self.b_f],  # static inputs to _step
            truncate_gradient=self.truncate_gradient
        )
        # Iterate backward over the first dimension of the x array (=time).
        outputs_b, updates_b = theano.scan(
            self._step,  # this will be called with arguments (sequences[i], outputs[i-1], non_sequences[i])
            sequences=xb,  # tensors to iterate over, inputs to _step
            # initialization of the output. Input to _step with default tap=-1.
            outputs_info=alloc_zeros_matrix(X.shape[1], self.output_dim),
            non_sequences=[self.W_bb,self.b_b],  # static inputs to _step
            truncate_gradient=self.truncate_gradient,
            go_backwards=True  # Iterate backwards through time
        )
        #return outputs_f.dimshuffle((1, 0, 2))
        if self.return_sequences:
            if self.is_entity:
                return T.concatenate([T.add(T.tensordot(T.add(outputs_f.dimshuffle((1, 0, 2)), outputs_b[::-1].dimshuffle((1,0,2))),self.W_o,[[2],[0]]),b_on),Entity],axis=1)
            else:
                return T.add(T.tensordot(T.add(outputs_f.dimshuffle((1, 0, 2)), outputs_b[::-1].dimshuffle((1,0,2))),self.W_o,[[2],[0]]),b_on)

        return T.concatenate((outputs_f[-1], outputs_b[0]))

    def get_config(self):
        return {"name":self.__class__.__name__,
            "input_dim":self.input_dim,
            "output_dim":self.output_dim,
            "init":self.init.__name__,
            "inner_init":self.inner_init.__name__,
            "activation":self.activation.__name__,
            "truncate_gradient":self.truncate_gradient,
            "return_sequences":self.return_sequences}


import _plotly_utils.basevalidators

class SmoothingValidator(_plotly_utils.basevalidators.NumberValidator):
    def __init__(self, plotly_name="smoothing", parent_name="carpet.aaxis", **kwargs):
        super(SmoothingValidator, self).__init__(
            plotly_name=plotly_name,
            parent_name=parent_name,
            edit_type=kwargs.pop("edit_type", "calc"),
            max=kwargs.pop("max", 1.3),
            min=kwargs.pop("min", 0),
            **kwargs,
        )


import numpy as np

from finitewave.core.model import CardiacModel
from finitewave.cpuwave2D.model.aliev_panfilov_2d.aliev_panfilov_kernels_2d \
    import AlievPanfilovKernels2D

_npfloat = "float64"

class AlievPanfilov2D(CardiacModel):
    def __init__(self):
        CardiacModel.__init__(self)
        self.v = np.ndarray
        self.w = np.ndarray
        self.state_vars = ["u", "v"]
        self.npfloat = 'float64'

    def initialize(self):
        super().initialize()
        weights_shape = self.cardiac_tissue.weights.shape
        shape = self.cardiac_tissue.mesh.shape
        self.diffuse_kernel = AlievPanfilovKernels2D().get_diffuse_kernel(weights_shape)
        self.ionic_kernel = AlievPanfilovKernels2D().get_ionic_kernel()
        self.v = np.zeros(shape, dtype=self.npfloat)

    def run_ionic_kernel(self):
        self.ionic_kernel(self.u_new, self.u, self.v, self.cardiac_tissue.mesh,
                          self.dt)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Main

Created on Tue Aug 17 14:16:44 2021
Version: 1.0
Universidad Santo Tomás Tunja
Simulation
@author: Juana Valentina Mendoza Santamaría
@author: Alix Ivonne Chaparro Vasquez
presented to: Martha Susana Contreras Ortiz
"""
from controllers.settings import config
from controllers.mainController import mainController

if __name__ == "__main__":
    simulator = config.PARAMETERS['simulator']
    mainController(simulator)   # True (simulation) - False (Demo)


# TIPS: only used to find the best epoch of MLP

# MLP
import csv
from itertools import islice
import random
import matplotlib.pyplot as plt
import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import KFold, train_test_split
import pandas as pd
from sklearn.utils import shuffle

import tensorflow as tf

def bit2attr(bitstr) -> list:
    attr_vec = list()
    for i in range(len(bitstr)):
        attr_vec.append(int(bitstr[i]))
    return attr_vec

def mean_relative_error(y_pred, y_test):
    assert len(y_pred) == len(y_test)
    mre = 0.0
    for i in range(len(y_pred)):
        mre = mre + abs((y_pred[i] - y_test[i]) / y_test[i])
    mre = mre * 100/ len(y_pred)
    return mre

Large_MRE_points = pd.DataFrame()
Large_MRE_X = []
Large_MRE_y_test = []
Large_MRE_y_pred = []
Large_MRE = []

'''
1) 数据预处理
'''
# filepath = 'data/fp/sjn/R+B+Cmorgan_fp1202.csv'
filepath = 'data/database/22-01-29-descriptor-train.csv'

data = pd.read_csv(filepath, encoding='gb18030')
print(data.shape)
data = data.dropna()

print(data.shape)
data = shuffle(data)

data_x_df = data.drop(['label'], axis=1)
data_y_df = data[['label']]

# 归一化
min_max_scaler_X = MinMaxScaler()
min_max_scaler_X.fit(data_x_df)
x_trans1 = min_max_scaler_X.transform(data_x_df)

min_max_scaler_y = MinMaxScaler()
min_max_scaler_y.fit(data_y_df)
y_trans1 = min_max_scaler_y.transform(data_y_df)

test_filepath = "data/database/22-01-29-descriptor-test-level-1.csv"
test_data = pd.read_csv(test_filepath, encoding='gb18030')
print('test data: ', test_data.shape)

test_data_x_df = test_data.drop(['label'], axis=1)
test_data_y_df = test_data[['label']]
x_trans1_test = min_max_scaler_X.transform(test_data_x_df)
y_trans1_test = min_max_scaler_y.transform(test_data_y_df)

'''
3) 构建模型
'''

from keras.layers import MaxPooling1D, Conv1D, Dense, Flatten, Dropout
from keras import models
from keras.optimizers import Adam, RMSprop, SGD

def buildModel():
    model = models.Sequential()

    l4 = Dense(512, activation='relu')
    l5 = Dropout(rate=0.2)
    l6 = Dense(128, activation='relu')
    l7 = Dense(30, activation='relu')
    l8 = Dense(1)

    layers = [l4, l5, l6, l7, l8]
    for i in range(len(layers)):
        model.add(layers[i])

    adam = Adam(lr=1e-3)
    model.compile(optimizer=adam, loss='logcosh', metrics=['mae', 'mape'])

    model_mlp = MLPRegressor(
        hidden_layer_sizes=(512, 128, 32), activation='relu', solver='lbfgs', alpha=0.0001,
        max_iter=5000,
        random_state=1, tol=0.0001, verbose=False, warm_start=False)

    return model

def scheduler(epoch, lr):
    if epoch > 0 and epoch % 500 == 0:
        return lr * 0.1
    else:
        return lr

'''
4) 训练模型
'''
from sklearn import metrics

# n_split = 10
mlp_scores = []
MAEs = []
out_MAEs = []

in_y_test = []
in_y_pred = []
out_y_test = []
out_y_pred = []

X_train = x_trans1
y_train = y_trans1

# 外部验证
X_test = x_trans1_test

y_trans1_test = np.reshape(y_trans1_test, (-1, 1))
y_test = y_trans1_test

callback = tf.keras.callbacks.LearningRateScheduler(scheduler, verbose=1)
model_mlp = buildModel()
history = model_mlp.fit(X_train, y_train, epochs=1, verbose=1, validation_data=(X_test, y_test), callbacks=[callback])
print(model_mlp.summary())
exit(0)

losses = history.history['loss']
eval_mres = history.history['val_mape']

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot([x for x in range(len(losses))], losses, 'b', label='loss')
ax1.set_ylabel('loss', color='b')
ax2.plot([x for x in range(len(eval_mres))], eval_mres, 'r', label='eval_mre')
ax2.set_ylabel('eval_mre', color='r')
ax1.set_xlabel('epochs')
plt.title('Training of MLP')
plt.savefig('pics/Training_of_MLP.png')

import os
outdir = 'Out/losses_and_mres'
os.makedirs(outdir, exist_ok=True)
with open(os.path.join(outdir, 'mlp_descriptor.txt'), 'w') as f:
    f.write('loss\n')
    f.write(' '.join([str(x) for x in losses]))
    f.write('\n')
    f.write('mres\n')
    f.write(' '.join([str(x) for x in eval_mres]))


import logging

from google.appengine.ext import db
from google.appengine.api import memcache
from app.utility.utils import memcached

import app.utility.utils as utils
import app.db.counter as counter

import web

QUESTIONS_PER_SITEMAP = 500

class Sitemap(db.Model):
    question_count = db.IntegerProperty(default = 0)
    question_keys = db.StringListProperty(default = [])
    content = db.TextProperty(default ='')
    archived = db.BooleanProperty(default = False)
    created = db.DateTimeProperty(auto_now_add = True)
    last_modified = db.DateTimeProperty(auto_now = True)

    @staticmethod
    def get_last_sitemap():
        entity = Sitemap.all().order('-created').get()
        if entity:
            if entity.question_count >= QUESTIONS_PER_SITEMAP:
                entity.content = unicode(web.render.sitemap_questions(entity.question_keys))
                entity.archived = True
                entity.put()
                entity = Sitemap()
                entity.put()
        else:
            entity = Sitemap()
            entity.put()
        return entity

    @staticmethod
    def update_last_sitemap(key):
        last_sitemap = Sitemap.get_last_sitemap()
        last_sitemap.question_count += 1
        last_sitemap.question_keys.insert(0, str(key))
        last_sitemap.put()

    @staticmethod
    def get_sitemaps():
        sitemaps = Sitemap.all().order('-created').fetch(500)
        return sitemaps

    @staticmethod
    @memcached('get_sitemap_by_id', 3600*24, lambda id : int(id) )
    def get_sitemap_by_id(id):
        entity = Sitemap.get_by_id(id)
        if entity:
            if entity.content:
                return entity.content
            else:
                return unicode(web.render.sitemap_questions(entity.question_keys))
        else:
            raise web.notfound()


from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import HttpResponse
from .models import Form
from .forms import ReqForm
from .filters import FormFilter
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import redirect

def form(request):
    return render(request,'form.html')
def status(request):
    return render(request,'status.html')
def about(request):
    return render(request,'about.html')
def index(request):
    return render(request,'index.html')
def showformdata(request):
    if request.method=='POST':
        fm=ReqForm(request.POST)
        if fm.is_valid():
            em=fm.cleaned_data['email']
            cn=fm.cleaned_data['ClubName']
            rn=fm.cleaned_data['RepresentativeName']
            cn=fm.cleaned_data['Contact']
            df=fm.cleaned_data['req_date_from']
            dt=fm.cleaned_data['req_date_to']
            rt=fm.cleaned_data['req_type']
            rp=fm.cleaned_data['req_purpose']
            profile = fm.save(commit=False)
            profile.user = request.user
            profile.save()
            fm.save()
            fm=ReqForm()
            print(em)
            print(rn)
    else:
        fm=ReqForm()
    return render(request,'form.html',{'frm':fm})

def reqInfo(request):
    u=request.user
    if u.groups.filter(name='Managers').exists():
        req = Form.objects.all()
        print(req)
        print("this is a manager")
        context={
        'form':form,
        'req': req
         }
    else:
        req = Form.objects.filter(user=request.user)
        print(req)
        print("normal user")
        context={
            'form':form,
            'req': req
        }
    return render(request,'status.html',context)

def student_approve(request,user_id):
    val=Form.objects.get(id=user_id)
    val.alloted=1
    val.save()
    return HttpResponse("approved successfully")

def student_disapprove(request,user_id):
    val=Form.objects.get(id=user_id)
    val.alloted=2
    val.save()
    return HttpResponse("disapproved successfully")

def student_reset(request,user_id):
    val=Form.objects.get(id=user_id)
    val.alloted=0
    val.save()
    return HttpResponse("reset successfully")
# def write_view(request, *args, **kwargs):
#     val=Form.objects.get(id=user_id)
#     if request.is_ajax() and request.method == "POST":
#         texteditor = request.POST['TextEntered']
#         val.Management_Comments='texteditor'
#         print(texteditor)
# ##      Don't forget to do validation and cleanup on texteditor to avoid security hassles
# ##      Do your logic here
#         SuccessAcknowledgment = {"Acknowledged":"Acknowledged"}
#         return HttpResponse(json.dumps(SuccessAcknowledgment))
#     else:
#         return render(request, "write.html")
def reqInfoMess(request):
    u=request.user
    if u.groups.filter(name='Managers').exists():
        req = Form.objects.all()
        print(req)
        print("this is a manager")
        context={
        'form':form,
        'req': req
         }
    else:
        req = Form.objects.filter(user=request.user)
        print(req)
        print("normal user")
        context={
            'form':form,
            'req': req
        }
    return render(request,'status.html',context)

def showmess(request, user_id):
    u=request.user
    if request.method=='POST':
        fm=mess(request.POST)
        ms=""
        if fm.is_valid():
            ms=fm.cleaned_data['Management_Comments']
            u = fm.save(commit=False)
            #profile.user = request.user
            u.save()
            fm.save()
            fm=mess()
            print(ms)
    return render(request,'status.html',{'mess':ms})


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# License: BSD-3 (https://tldrlegal.com/license/bsd-3-clause-license-(revised))
# Copyright (c) 2016-2021, Cabral, Juan; Luczywo, Nadia
# All rights reserved.

# =============================================================================
# DOCS
# =============================================================================

"""Tool to check if each python module has a corresponding API docs."""

# =============================================================================
# IMPORTS
# =============================================================================

import inspect
import pathlib

import attr

import typer

# =============================================================================
# CONSTANTS
# =============================================================================

VERSION = "0.1"

# =============================================================================
# FUNCTIONS
# =============================================================================

def check_apidoc_structure(apidoc_dir, reference_dir):

    apidoc_dir = pathlib.Path(apidoc_dir)
    reference_dir = pathlib.Path(reference_dir)

    if not apidoc_dir.exists():
        raise OSError(f"'{apidoc_dir}' do no exist")
    if not reference_dir.exists():
        raise OSError(f"'{reference_dir}' do no exist")

    reference = list(reference_dir.glob("**/*.py"))

    result = {}
    for ref in reference:

        # essentially we remove the parent dir
        *dirs, ref_name = ref.relative_to(reference_dir).parts

        if ref_name == "__init__.py":
            ref_name = "index.py"

        search_dir = apidoc_dir
        for subdir in dirs:
            search_dir /= subdir

        search = search_dir / f"{ref_name[:-3]}.rst"

        result[str(ref)] = (str(search), search.exists())

    return result

# =============================================================================
# CLI
# =============================================================================

@attr.s(frozen=True)
class CLI:
    """Check if the structure of API doc directory is equivalent to those of
    the project.

    """

    footnotes = "\n".join(
        [
            "This software is under the BSD 3-Clause License.",
            "Copyright (c) 2021, Juan Cabral.",
            "For bug reporting or other instructions please check:"
            " https://github.com/quatrope/scikit-criteria",
        ]
    )

    run = attr.ib(init=False)

    @run.default
    def _set_run_default(self):
        app = typer.Typer()
        for k in dir(self):
            if k.startswith("_"):
                continue
            v = getattr(self, k)
            if inspect.ismethod(v):
                decorator = app.command()
                decorator(v)
        return app

    def version(self):
        """Print checktestdir.py version."""
        typer.echo(f"{__file__ } v.{VERSION}")

    def check(
        self,
        test_dir: str = typer.Argument(
            ..., help="Path to the api-doc structure."
        ),
        reference_dir: str = typer.Option(
            ..., help="Path to the reference structure."
        ),
        verbose: bool = typer.Option(
            default=False, help="Show all the result"
        ),
    ):
        """Check if the structure of test directory is equivalent to those
        of the project.

        """
        try:
            check_result = check_apidoc_structure(test_dir, reference_dir)
        except Exception as err:
            typer.echo(typer.style(str(err), fg=typer.colors.RED))
            raise typer.Exit(code=1)

        all_tests_exists = True
        for ref, test_result in check_result.items():

            test, test_exists = test_result

            if test_exists:
                fg = typer.colors.GREEN
                status = ""
            else:
                all_tests_exists = False
                fg = typer.colors.RED
                status = typer.style("[NOT FOUND]", fg=typer.colors.YELLOW)

            if verbose or not test_exists:
                msg = f"{ref} -> {test} {status}"
                typer.echo(typer.style(msg, fg=fg))

        if all_tests_exists:
            final_fg = typer.colors.GREEN
            final_status = "Test structure ok!"
            exit_code = 0
        else:
            final_fg = typer.colors.RED
            final_status = "Structure not equivalent!"
            exit_code = 1

        typer.echo("-------------------------------------")
        typer.echo(typer.style(final_status, fg=final_fg))
        raise typer.Exit(code=exit_code)

def main():
    """Run the checkapidocdir.py cli interface."""
    cli = CLI()
    cli.run()

if __name__ == "__main__":
    main()


# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from aliyunsdkcore.request import RpcRequest
from aliyunsdkemr.endpoint import endpoint_data

class ListRequiredServiceRequest(RpcRequest):

	def __init__(self):
		RpcRequest.__init__(self, 'Emr', '2016-04-08', 'ListRequiredService','emr')
		if hasattr(self, "endpoint_map"):
			setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
		if hasattr(self, "endpoint_regional"):
			setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())

	def get_ResourceOwnerId(self):
		return self.get_query_params().get('ResourceOwnerId')

	def set_ResourceOwnerId(self,ResourceOwnerId):
		self.add_query_param('ResourceOwnerId',ResourceOwnerId)

	def get_EmrVersion(self):
		return self.get_query_params().get('EmrVersion')

	def set_EmrVersion(self,EmrVersion):
		self.add_query_param('EmrVersion',EmrVersion)

	def get_ServiceNameList(self):
		return self.get_query_params().get('ServiceNameList')

	def set_ServiceNameList(self,ServiceNameList):
		self.add_query_param('ServiceNameList',ServiceNameList)