Beispiel #1
0
    def evaluate(
        self,
        parameters: Dict[str, Any] = None,
        array_format: str = FORMAT_DEFAULT,
    ) -> Union[int, np.ndarray]:
        """Evaluate the value at the output port on the basis of parameters and array_format

        Args:
            parameters: Dictionary of global parameters of the Output Port
            array_format: It is a n-dimensional array

        Returns:
            value at output port
        """
        if self.verbose:
            print("    Evaluating %s with %s " %
                  (self.output_port, _params_info(parameters)))
        self.curr_value = evaluate_expr(self.output_port.value,
                                        parameters,
                                        verbose=False,
                                        array_format=array_format)

        if self.verbose:
            print("    Evaluated %s with %s \n       =\t%s" % (
                self.output_port,
                _params_info(parameters),
                _val_info(self.curr_value),
            ))
        return self.curr_value
Beispiel #2
0
def evaluate_expr(
    expr: Union[str, List[str], np.ndarray, "tf.tensor"] = None,
    func_params: Dict[str, Any] = None,
    array_format: str = FORMAT_DEFAULT,
    verbose: Optional[bool] = False,
) -> np.ndarray:
    """Evaluates an expression given in string format and a :code:`dict` of parameters.

    Args:
        expr: Expression or list of expressions to be evaluated
        func_params: A dict of parameters (e.g. :code:`{'weight': 2}`)
        array_format: It can be a n-dimensional array or a tensor
        verbose: If set to True provides in-depth information else verbose message is not displayed

    Returns:
        n-dimensional array

    """

    e = evaluate_params_modelspec(expr,
                                  func_params,
                                  array_format=array_format,
                                  verbose=verbose)
    if type(e) == str and e not in KNOWN_PARAMETERS:
        raise Exception(
            "Error! Could not evaluate expression [%s] with params %s, returned [%s] which is a %s"
            % (expr, _params_info(func_params), e, type(e)))
    return e
Beispiel #3
0
    def evaluate(self,
                 parameters: Dict[str, Any] = None,
                 array_format: str = FORMAT_DEFAULT) -> Union[int, np.ndarray]:
        """Evaluates value at Input port based on parameters and array_format

        Args:
            parameters: Dictionary of  parameters
            array_format: It is a n-dimensional array

        Returns:
            value at Input port
        """
        if self.verbose:
            print("    Evaluated %s with %s =\t%s" % (
                self.input_port,
                _params_info(parameters),
                _val_info(self.curr_value),
            ))
        return self.curr_value
Beispiel #4
0
    def evaluate(
        self,
        parameters: Dict[str, Any],
        time_increment: Optional[float] = None,
        array_format: str = FORMAT_DEFAULT,
    ) -> Any:
        """
        Evaluate the parameter and store the result in the :code:`curr_value` attribute.

        Args:
            parameters: a dictionary  of parameters and their values that may or may not be needed to evaluate this
                parameter.
            time_increment: a floating point value specifying the timestep size, only used for :code:`time_derivative`
                parameters
            array_format: The array format to use (either :code:`'numpy'` or :code:`tensorflow'`).

        Returns:
            The current value of the parameter.
        """
        if self.verbose:
            print("    Evaluating {} with {} ".format(
                self.parameter, _params_info(parameters)))

        if self.parameter.value is not None:

            self.curr_value = evaluate_expr(
                self.parameter.value,
                parameters,
                verbose=False,
                array_format=array_format,
            )
        elif self.parameter.function:
            expr = None
            for f in mdf_functions:
                if self.parameter.function == f:
                    expr = create_python_expression(
                        mdf_functions[f]["expression_string"])
            if not expr:

                expr = self.parameter.function
                # raise "Unknown function: {}. Known functions: {}".format(
                #    self.parameter.function,
                #    mdf_functions.keys,
                # )

            func_params = {}
            func_params.update(parameters)
            if self.verbose:
                print("    Evaluating %s with %s, i.e. [%s]" %
                      (self.parameter, _params_info(func_params), expr))
            for arg in self.parameter.args:
                func_params[arg] = evaluate_expr(
                    self.parameter.args[arg],
                    func_params,
                    verbose=False,
                    array_format=array_format,
                )
                if self.verbose:
                    print("      Arg: {} became: {}".format(
                        arg, _val_info(func_params[arg])))

            # If this is an ONNX operation, evaluate it without modelspec.
            if "onnx_ops." in expr:
                if self.verbose:
                    print(
                        f"{self.parameter.id} is evaluating ONNX function {expr}"
                    )
                self.curr_value = evaluate_onnx_expr(
                    expr,
                    # parameters get overridden by self.parameter.args
                    {
                        **parameters,
                        **self.parameter.args
                    },
                    func_params,
                    self.verbose,
                )
            elif "actr." in expr:
                actr_function = getattr(actr_funcs,
                                        expr.split("(")[0].split(".")[-1])
                self.curr_value = actr_function(
                    *[func_params[arg] for arg in self.parameter.args])
            else:
                self.curr_value = evaluate_expr(expr,
                                                func_params,
                                                verbose=self.verbose,
                                                array_format=array_format)
        else:
            if time_increment == None:

                self.curr_value = evaluate_expr(
                    self.parameter.default_initial_value,
                    parameters,
                    verbose=False,
                    array_format=array_format,
                )

            else:
                td = evaluate_expr(
                    self.parameter.time_derivative,
                    parameters,
                    verbose=False,
                    array_format=array_format,
                )

                self.curr_value += td * time_increment

        if self.verbose:
            print("    Evaluated %s with %s \n       =\t%s" %
                  (self.parameter, _params_info(parameters),
                   _val_info(self.curr_value)))

        return self.curr_value
Beispiel #5
0
    def evaluate(
        self,
        parameters: Dict[str, Any] = None,
        array_format: str = FORMAT_DEFAULT,
    ) -> Dict[str, Any]:
        r"""Performs evaluation on the basis of given parameters and array_format

        Args:
            parameters: A dictionary of function parameters,e.g.logistic, parameters={'gain': 2,"bias": 3,"offset": 1}
            array_format: It can be a n-dimensional array or a tensor

        Returns:
             value of function after evaluation in Dictionary

        """

        expr = None

        # print("functions value and function>>>", self.function.value, self.function.function)

        # func_val  = self.function.value

        if self.function.function:

            for f in mdf_functions:

                if f in self.function.function.keys():

                    expr = create_python_expression(
                        mdf_functions[f]["expression_string"])

                    break

        if expr is None:
            expr = self.function.value
        #     #raise "Unknown function: {}. Known functions: {}".format(
        #     #    self.function.function,
        #     #    mdf_functions.keys,
        #     #)

        func_params = {}
        func_params.update(parameters)
        if self.verbose:
            print("    Evaluating %s with %s, i.e. [%s]" %
                  (self.function, _params_info(func_params), expr))
        if self.function.function:

            for f in mdf_functions:

                if f in self.function.function.keys():

                    for arg in self.function.function[f].keys():

                        func_params[arg] = evaluate_expr(
                            self.function.function[f][arg],
                            func_params,
                            verbose=False,
                            array_format=array_format,
                        )
                        if self.verbose:
                            print("      Arg: {} became: {}".format(
                                arg, _val_info(func_params[arg])))
                    break

        # If this is an ONNX operation, evaluate it without modelspec.

        if "onnx_ops." in expr:
            if self.verbose:
                print(f"{self.function.id} is evaluating ONNX function {expr}")
            self.curr_value = evaluate_onnx_expr(
                expr,
                # parameters get overridden by self.function.args
                {
                    **parameters,
                    **self.function.args
                },
                func_params,
                self.verbose,
            )
        elif "actr." in expr:
            actr_function = getattr(actr_funcs,
                                    expr.split("(")[0].split(".")[-1])
            self.curr_value = actr_function(
                *[func_params[arg] for arg in self.function.args])
        else:
            self.curr_value = evaluate_expr(expr,
                                            func_params,
                                            verbose=self.verbose,
                                            array_format=array_format)

        if self.verbose:
            print("    Evaluated %s with %s =\t%s" %
                  (self.function, _params_info(func_params),
                   _val_info(self.curr_value)))
        return self.curr_value