def test(self):
        error = EMAError('a message')

        self.assertEqual(str(error), 'a message')
        
        error = EMAError('a message', 'another message')

        if sys.version_info[0] < 3:
            self.assertEqual(str(error), str("(u'a message', u'another message')"))
        else: 
            self.assertEqual(str(error), str("('a message', 'another message')"))
Exemple #2
0
    def _store_outcomes(self, case_id, outcomes, ex_id):
        for outcome in self.outcomes:
            _logger.debug("storing {}".format(outcome))

            try:
                outcome_res = outcomes[outcome]
            except KeyError:
                message = "%s not specified as outcome in msi" % outcome
                _logger.debug(message)
            else:
                try:
                    self.results[outcome][case_id, ] = outcome_res
                except KeyError:
                    shape = np.asarray(outcome_res).shape

                    if len(shape) > 2:
                        message = self.shape_error_msg.format(len(shape))
                        raise EMAError(message)

                    shape = list(shape)
                    shape.insert(0, self.nr_experiments)

                    self.results[outcome] = np.empty(shape)
                    self.results[outcome][:] = np.NAN
                    self.results[outcome][case_id, ] = outcome_res

                self.db.write_ex_m_1(
                    self.scope_name,
                    SOURCE_IS_CORE_MODEL
                    if not self.using_metamodel else METAMODEL_ID,
                    ex_id,
                    outcome,
                    outcome_res,
                )
Exemple #3
0
 def process(self, values):
     values = super(ScalarOutcome, self).process(values)
     if not isinstance(values, numbers.Number):
         raise EMAError(
             f"outcome {self.name} should be a scalar, but is {type(values)}: {values}"
             .format())
     return values
    def _sort_parameters(self, parameters):
        '''sort parameters into full factorial and other

        Parameters
        ----------
        parameters : list of parameters

        '''
        ff_params = []
        other_params = []

        for param in parameters:
            if param.pff:
                ff_params.append(param)
            else:
                other_params.append(param)

        if not ff_params:
            raise EMAError("no parameters for full factorial sampling")
        if not other_params:
            raise EMAError("no parameters for normal sampling")

        return ff_params, other_params
Exemple #5
0
def to_problem(model, searchover, reference=None, constraints=None):
    '''helper function to create Problem object

    Parameters
    ----------
    model : AbstractModel instance
    searchover : str
    reference : Policy or Scenario instance, optional
                overwrite the default scenario in case of searching over 
                levers, or default policy in case of searching over 
                uncertainties
    constraints : list, optional

    Returns
    -------
    Problem instance

    '''
    _type_mapping = {
        RealParameter: platypus.Real,
        IntegerParameter: platypus.Integer,
        CategoricalParameter: platypus.Permutation
    }

    # extract the levers and the outcomes
    decision_variables = determine_parameters(model, searchover, union=True)

    outcomes = determine_objects(model, 'outcomes')
    outcomes = [
        outcome for outcome in outcomes if outcome.kind != AbstractOutcome.INFO
    ]
    outcome_names = [outcome.name for outcome in outcomes]

    if not outcomes:
        raise EMAError(("no outcomes specified to optimize over, "
                        "all outcomes are of kind=INFO"))

    problem = Problem(searchover,
                      decision_variables,
                      outcome_names,
                      constraints,
                      reference=reference)
    problem.types = to_platypus_types(decision_variables)
    problem.directions = [outcome.kind for outcome in outcomes]
    problem.constraints[:] = "==0"

    return problem
    def show_tree(self, mplfig=True, format='png'):
        '''return a png of the tree

        Parameters
        ----------
        mplfig : bool, optional
                 if true (default) returns a matplotlib figure with the tree,
                 otherwise, it returns the output as bytes
        format : {'png', 'svg'}, default 'png'
                 Gives a format of the output.

        '''
        assert self.clf
        try:
            import pydotplus as pydot
        except ImportError:
            import pydot  # dirty hack for read the docs

        dot_data = StringIO()
        tree.export_graphviz(self.clf,
                             out_file=dot_data,
                             feature_names=self.feature_names)
        dot_data = dot_data.getvalue()  # .encode('ascii') # @UndefinedVariable
        graphs = pydot.graph_from_dot_data(dot_data)

        # FIXME:: pydot now always returns a list, usted to be either a
        # singleton or a list. This is a stopgap which might be sufficient
        # but just in case, we raise an error if assumption of len==1 does
        # not hold
        if len(graphs) > 1:
            raise EMAError("trying to visualize more than one tree")

        graph = graphs[0]

        if format == 'png':
            img = graph.create_png()
            if mplfig:
                fig, ax = plt.subplots()
                ax.imshow(mpimg.imread(io.BytesIO(img)))
                ax.axis('off')
                return fig
        elif format == 'svg':
            img = graph.create_svg()
        else:
            raise TypeError('''format must be in {'png', 'svg'}''')

        return img
Exemple #7
0
def to_robust_problem(model,
                      scenarios,
                      robustness_functions,
                      constraints=None):
    '''helper function to create RobustProblem object

    Parameters
    ----------
    model : AbstractModel instance
    scenarios : collection
    robustness_functions : iterable of ScalarOutcomes
    constraints : list, optional


    Returns
    -------
    RobustProblem instance

    '''

    # extract the levers and the outcomes
    decision_variables = determine_parameters(model, 'levers', union=True)

    outcomes = robustness_functions
    outcomes = [
        outcome for outcome in outcomes if outcome.kind != AbstractOutcome.INFO
    ]
    outcome_names = [outcome.name for outcome in outcomes]

    if not outcomes:
        raise EMAError(("no outcomes specified to optimize over, "
                        "all outcomes are of kind=INFO"))

    problem = RobustProblem(decision_variables, outcome_names, scenarios,
                            robustness_functions, constraints)

    problem.types = to_platypus_types(decision_variables)
    problem.directions = [outcome.kind for outcome in outcomes]
    problem.constraints[:] = "==0"

    return problem
Exemple #8
0
    def process(self, values):
        if self.function:
            var_names = self.variable_name

            n_variables = len(var_names)
            try:
                n_values = len(values)
            except TypeError:
                len_val = None

            if (n_values == None) and (n_variables == 1):
                return self.function(values)
            elif n_variables != n_values:
                raise ValueError(
                    ('number of variables is {}, '
                     'number of outputs is {}').format(n_variables, n_values))
            else:
                return self.function(*values)
        else:
            if len(values) > 1:
                raise EMAError(('more than one value returned without '
                                'processing function'))

            return values[0]
Exemple #9
0
 def process(self, values):
     values = super(TimeSeriesOutcome, self).process(values)
     if not isinstance(values, collections.Iterable):
         raise EMAError("outcome {} should be a collection".format(
             self.name))
     return values
Exemple #10
0
 def process(self, values):
     values = super(ScalarOutcome, self).process(values)
     if not isinstance(values, numbers.Number):
         raise EMAError("outcome {} should be a scalar".format(self.name))
     return values