How to use the pypesto.objective.constants.MODE_FUN function in pypesto

To help you get started, we’ve selected a few pypesto examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ICB-DCM / pyPESTO / test / test_sbml_conversion.py View on Github external
def runTest(self):
        for example in ['conversion_reaction']:
            objective, model = load_model_objective(example)
            x0 = np.array(list(model.getParameters()))

            df = objective.check_grad(
                x0, eps=1e-3, verbosity=0,
                mode=pypesto.objective.constants.MODE_FUN)
            print("relative errors MODE_FUN: ", df.rel_err.values)
            print("absolute errors MODE_FUN: ", df.abs_err.values)
            assert np.all((df.rel_err.values < RTOL) |
                          (df.abs_err.values < ATOL))

            df = objective.check_grad(
                x0, eps=1e-3, verbosity=0,
                mode=pypesto.objective.constants.MODE_RES)
            print("relative errors MODE_RES: ", df.rel_err.values)
            print("absolute errors MODE_RES: ", df.rel_err.values)
            assert np.all((df.rel_err.values < RTOL) |
                          (df.abs_err.values < ATOL))

            for library in optimizers.keys():
                for method in optimizers[library]:
                    for fp in [[], [1]]:
github ICB-DCM / pyPESTO / test / test_amici_objective.py View on Github external
# assert that initial guess is uninformative
    assert problem.objective.steadystate_guesses['fval'] == np.inf

    optimizer = pypesto.ScipyOptimizer('L-BFGS-B', options={'maxiter': 50})
    result = pypesto.minimize(
        problem=problem, optimizer=optimizer, n_starts=1,
    )

    assert problem.objective.steadystate_guesses['fval'] < np.inf
    assert len(obj.steadystate_guesses['data']) == 1

    df = obj.check_grad(
        result.optimize_result.list[0]['x'],
        eps=1e-3,
        verbosity=0,
        mode=pypesto.objective.constants.MODE_FUN
    )
    print("relative errors MODE_FUN: ", df.rel_err.values)
    print("absolute errors MODE_FUN: ", df.abs_err.values)
    assert np.all((df.rel_err.values < RTOL) | (df.abs_err.values < ATOL))

    # assert that resetting works
    problem.objective.initialize()
    assert problem.objective.steadystate_guesses['fval'] == np.inf
github ICB-DCM / pyPESTO / pypesto / objective / priors.py View on Github external
def check_mode(self, mode) -> bool:
        if mode == MODE_FUN:
            return True
        elif mode == MODE_RES:
            return False
        else:
            ValueError(f'Invalid input: Expected mode {MODE_FUN} or'
                       f' {MODE_RES}, received {mode} instead.')
github ICB-DCM / pyPESTO / pypesto / objective / objective.py View on Github external
def _call_mode_fun(
            self, x: np.ndarray, sensi_orders: Tuple[int, ...]
    ) -> Dict:
        """
        The method __call__ was called with mode MODE_FUN.
        """
        if self.fun_accept_sensi_orders:
            result = self.fun(x, sensi_orders)
            if not isinstance(result, dict):
                result = Objective.output_to_dict(
                    sensi_orders, MODE_FUN, result)
        elif sensi_orders == (0,):
            if self.grad is True:
                fval = self.fun(x)[0]
            else:
                fval = self.fun(x)
            result = {FVAL: fval}
        elif sensi_orders == (1,):
            if self.grad is True:
                grad = self.fun(x)[1]
            else:
                grad = self.grad(x)
            result = {GRAD: grad}
        elif sensi_orders == (2,):
            if self.hess is True:
                hess = self.fun(x)[2]
            else:
github ICB-DCM / pyPESTO / pypesto / objective / objective.py View on Github external
def check_sensi_orders(self, sensi_orders, mode) -> None:
        """
        Check if the objective is able to compute the requested
        sensitivities. If not, throw an exception.

        Raises
        ------
        ValueError if the objective function cannot be called as
        requested.
        """
        if (mode is MODE_FUN and
            (0 in sensi_orders and not self.has_fun
             or 1 in sensi_orders and not self.has_grad
             or 2 in sensi_orders and not self.has_hess)
            ) or (mode is MODE_RES and
                  (0 in sensi_orders and not self.has_res
                   or 1 in sensi_orders and not self.has_sres)
                  ):
            raise ValueError(
                f"Objective cannot be called with sensi_orders={sensi_orders}"
                f" and mode={mode}")
github ICB-DCM / pyPESTO / pypesto / objective / amici_calculator.py View on Github external
edatas: List['amici.ExpData'],
                              x_ids: Sequence[str],
                              parameter_mapping: 'ParameterMapping',
                              fim_for_hess: bool):
    # full optimization problem dimension (including fixed parameters)
    dim = len(x_ids)

    # check if the simulation failed
    if any(rdata['status'] < 0.0 for rdata in rdatas):
        return get_error_output(amici_model, edatas, rdatas, dim)

    # prepare outputs
    nllh = 0.0
    snllh = None
    s2nllh = None
    if mode == MODE_FUN and sensi_order > 0:
        snllh = np.zeros(dim)
        s2nllh = np.zeros([dim, dim])

    chi2 = None
    res = None
    sres = None
    if mode == MODE_RES:
        chi2 = 0.0
        res = np.zeros([0])
        if sensi_order > 0:
            sres = np.zeros([0, dim])

    par_sim_ids = list(amici_model.getParameterIds())
    sensi_method = amici_solver.getSensitivityMethod()

    # iterate over return data
github ICB-DCM / pyPESTO / pypesto / objective / history.py View on Github external
def _update_counts(self,
                       sensi_orders: Tuple[int, ...],
                       mode: str):
        """
        Update the counters.
        """
        if mode == MODE_FUN:
            if 0 in sensi_orders:
                self._n_fval += 1
            if 1 in sensi_orders:
                self._n_grad += 1
            if 2 in sensi_orders:
                self._n_hess += 1
        elif mode == MODE_RES:
            if 0 in sensi_orders:
                self._n_res += 1
            if 1 in sensi_orders:
                self._n_sres += 1
github ICB-DCM / pyPESTO / pypesto / objective / objective.py View on Github external
def _call_unprocessed(
            self,
            x: np.ndarray,
            sensi_orders: Tuple[int, ...],
            mode: str
    ) -> Dict:
        """
        Call objective function without pre- or post-processing and
        formatting.

        Returns
        -------
        result:
            A dict containing the results.
        """
        if mode == MODE_FUN:
            result = self._call_mode_fun(x, sensi_orders)
        elif mode == MODE_RES:
            result = self._call_mode_res(x, sensi_orders)
        else:
            raise ValueError("This mode is not supported.")
        return result
github ICB-DCM / pyPESTO / pypesto / objective / amici.py View on Github external
def check_sensi_orders(self, sensi_orders, mode) -> bool:
        sensi_order = max(sensi_orders)

        # dynamically obtain maximum allowed sensitivity order
        max_sensi_order = self.max_sensi_order
        if max_sensi_order is None:
            max_sensi_order = 1
            # check whether it is ok to request 2nd order
            sensi_mthd = self.amici_solver.getSensitivityMethod()
            mthd_fwd = amici.SensitivityMethod_forward
            if mode == MODE_FUN and (
                    self.amici_model.o2mode or (
                    sensi_mthd == mthd_fwd and self.fim_for_hess)):
                max_sensi_order = 2

        # evaluate sensitivity order
        return sensi_order <= max_sensi_order