From 195a17ac79fa74fe5bee716a95c4192f7c3ca420 Mon Sep 17 00:00:00 2001 From: Hubertus Tummescheit Date: Sat, 19 Sep 2026 13:22:23 -0400 Subject: [PATCH 1/4] Add simulation option 'jacobian_mode' (auto | dd | fd) for the PyFMI Jacobian When 'with_jacobian' is in effect and the FMU provides directional derivatives, PyFMI evaluates the Jacobian with one fmi2GetDirectionalDerivative call per colour group of the sparsity pattern. On FMUs where one such call costs more than an rhs evaluation (measured 1.7x on OCT exports of 140-320 state models), coloured forward differences give the same Jacobian for a third of the cost, and because the colouring is bounded by the densest Jacobian row, Jacobian evaluation was 55-85 % of the solver time on those models. Measured with CVode: absorptionplant (226 states) 164 -> 89 s; Radau5ODE 529 -> 206 s; same step counts, events and accuracy (deviation <= 4e-4 at rtol 1e-6). 'jacobian_mode' = "auto" (default) times one rhs and one directional-derivative call at initialization and picks "fd" when the derivative is the more expensive one, except for RodasODE (a Rosenbrock method needs the exact Jacobian), the sparse linear solver, and rtol < 1e-7 (forward-difference truncation error ~sqrt(eps) then stalls Newton, measured on a 318-state plant at rtol 1e-8). "dd" and "fd" force either. Without directional derivatives the mode is always "fd". The setting is scoped to the simulation: the model's force_finite_differences attribute is restored afterwards. Co-Authored-By: Claude Opus 5 --- src/pyfmi/fmi_algorithm_drivers.py | 110 +++++++++++++++++++++++++++++ tests/test_fmi2.py | 83 ++++++++++++++++++++++ 2 files changed, 193 insertions(+) diff --git a/src/pyfmi/fmi_algorithm_drivers.py b/src/pyfmi/fmi_algorithm_drivers.py index dae2fa3d..e012b650 100644 --- a/src/pyfmi/fmi_algorithm_drivers.py +++ b/src/pyfmi/fmi_algorithm_drivers.py @@ -44,6 +44,17 @@ PYFMI_JACOBIAN_SPARSE_SIZE_LIMIT = 100 PYFMI_JACOBIAN_SPARSE_NNZ_LIMIT = 0.15 #In percentage +# jacobian_mode = "auto": use coloured finite differences instead of the FMU's directional +# derivatives when one directional-derivative call costs more than this fraction of an rhs +# evaluation (measured at initialization; on some tools' FMUs a directional derivative +# costs ~1.7 rhs, on others ~0.01), unless the tolerance is so tight that the forward- +# difference truncation error (~sqrt(eps)) would stall Newton, or the solver needs the +# exact Jacobian (Rosenbrock methods). +PYFMI_JACOBIAN_FD_COST_RATIO = 0.7 +PYFMI_JACOBIAN_FD_RTOL_LIMIT = 1e-7 +PYFMI_JACOBIAN_FD_MIN_DD_TIME = 5e-5 # seconds; below this a directional derivative is cheap anyway +PYFMI_JACOBIAN_EXACT_SOLVERS = ("RodasODE",) + class FMIResult(JMResultBase): def __init__(self, model=None, result_file_name=None, solver=None, result_data=None, options=None, status=0, detailed_timings=None): @@ -99,6 +110,23 @@ class AssimuloFMIAlgOptions(OptionBase): solver. Default: "Default" + jacobian_mode -- + How PyFMI evaluates the Jacobian when 'with_jacobian' is in + effect and the FMU provides directional derivatives: + "dd" uses the directional derivatives (one call per colour group + of the sparsity pattern), "fd" uses coloured forward differences + (one rhs evaluation per colour group) instead, "auto" measures + the cost of one directional-derivative call against one rhs + evaluation at initialization and picks "fd" when a directional + derivative is the more expensive of the two, except for solvers + that need the exact Jacobian (RodasODE), for the sparse linear + solver, and for rtol below 1e-7 where the finite-difference + truncation error would degrade Newton convergence. Without + directional derivatives the Jacobian is always "fd". The mode + that was used is available as the 'jacobian_mode' attribute of + the algorithm object. + Default: "auto" + dynamic_diagnostics -- If True, enables logging of diagnostics data to a result file. This requires that the option 'result_handler' supports 'dynamic_diagnostics', otherwise an @@ -217,6 +245,7 @@ def __init__(self, *args, **kw): 'write_scaled_result':False, 'result_file_name':'', 'with_jacobian':"Default", + 'jacobian_mode':"auto", 'logging':False, 'dynamic_diagnostics':False, 'result_handling':"binary", @@ -365,6 +394,7 @@ def __init__(self, raise FMUException("The model need to be initialized prior to calling the simulate method if the option 'initialize' is set to False") self._set_absolute_tolerance_options() + self._set_jacobian_mode() number_of_diagnostics_variables = 0 if self.result_handler.supports.get('dynamic_diagnostics', False): @@ -561,6 +591,83 @@ def _set_options(self): else: self.with_jacobian = False + def _set_jacobian_mode(self): + """ + Decides whether the PyFMI Jacobian is evaluated from the FMU's directional + derivatives or by coloured finite differences (option 'jacobian_mode') and + configures the model accordingly. Must be called after initialization: the + "auto" mode times one rhs evaluation and one directional-derivative call. + """ + self.jacobian_mode = None + mode = self.options["jacobian_mode"] + if mode not in ("auto", "dd", "fd"): + raise InvalidOptionException("Unknown option to 'jacobian_mode': %s (expected 'auto', 'dd' or 'fd')." % mode) + if not self.with_jacobian or not isinstance(self.model, (FMUModelME2, FMUModelME3)): + return + + provides_dd = bool(self.model.get_capability_flags().get("providesDirectionalDerivatives", False)) + if not provides_dd: + mode = "fd" + elif mode == "auto": + rtol = np.min(self.rtol) if isinstance(self.rtol, (np.ndarray, list)) else self.rtol + if self.options["solver"] in PYFMI_JACOBIAN_EXACT_SOLVERS or \ + self.solver_options.get("linear_solver", "DENSE") == "SPARSE" or \ + rtol < PYFMI_JACOBIAN_FD_RTOL_LIMIT: + mode = "dd" + else: + t_rhs, t_dd = self._probe_jacobian_cost() + # below the floor the Jacobian is cheap either way and the timing is noise: + # keep the exact derivatives + mode = "fd" if (t_dd > PYFMI_JACOBIAN_FD_MIN_DD_TIME and t_dd > PYFMI_JACOBIAN_FD_COST_RATIO * t_rhs) else "dd" + self.model.append_log_message("Model", 4, "[INFO][FMU status:OK] jacobian_mode auto: one rhs %.3g s, one directional derivative %.3g s -> '%s'" % (t_rhs, t_dd, mode)) + + # 0 = directional derivatives if available; True = forward differences. + # The model attribute is restored after the simulation (see solve()). + self._force_finite_differences_prev = self.model.force_finite_differences + self.model.force_finite_differences = True if (mode == "fd" and provides_dd) else 0 + self.jacobian_mode = mode + + def _restore_jacobian_mode(self): + """'jacobian_mode' applies to the simulation only, not to later Jacobian + evaluations on the model (e.g. get_state_space_representation).""" + if self.jacobian_mode is not None: + self.model.force_finite_differences = self._force_finite_differences_prev + + def _probe_jacobian_cost(self, repeats=3): + """ + Returns (seconds per rhs evaluation, seconds per directional-derivative call), + each the minimum over 'repeats' calls at the current model state. The states are + perturbed by 1e-8 of their nominal values between rhs calls so that the FMU + cannot serve a cached result; time and states are restored afterwards. + """ + model = self.model + t = model.time + x = model.continuous_states.copy() + nx = len(x) + if nx == 0: + return 0.0, 0.0 + nominal = np.abs(model.nominal_continuous_states) + t_rhs = np.inf + for k in range(repeats): + model.time = t + model.continuous_states = x + (k + 1) * 1e-8 * nominal + t0 = timer() + model.get_derivatives() + t_rhs = min(t_rhs, timer() - t0) + model.time = t + model.continuous_states = x + states_ref = [v.value_reference for v in model.get_states_list().values()] + derivs_ref = [v.value_reference for v in model.get_derivatives_list().values()] + v = np.zeros(nx) + v[0] = 1.0 + t_dd = np.inf + for k in range(repeats): + t0 = timer() + model.get_directional_derivative(states_ref, derivs_ref, v) + t_dd = min(t_dd, timer() - t0) + model.get_derivatives() # leave the FMU evaluated at (t, x) + return t_rhs, t_dd + def _set_absolute_tolerance_options(self): """ Sets the absolute tolerance. Must not be called before initialization since it depends @@ -668,6 +775,8 @@ def solve(self): except Exception: self.result_handler.simulation_end() #Close the potentially open result files raise #Reraise the exception + finally: + self._restore_jacobian_mode() self.timings["storing_result"] = self.probl.timings["handle_result"] self.timings["computing_solution"] = timer() - time_start - self.timings["storing_result"] @@ -682,6 +791,7 @@ def get_result(self): The AssimuloSimResult object. """ + self._restore_jacobian_mode() time_start = timer() if self.options["return_result"]: diff --git a/tests/test_fmi2.py b/tests/test_fmi2.py index 1264bba2..08a4344f 100644 --- a/tests/test_fmi2.py +++ b/tests/test_fmi2.py @@ -323,6 +323,89 @@ def run_case(expected, default="Default"): opts["with_jacobian"] = True run_case(True, True) + def test_jacobian_mode_option(self): + """'jacobian_mode': directional derivatives vs coloured finite differences.""" + import time as _time + model = Dummy_FMUModelME2([], os.path.join(file_path, "files", "FMUs", "XML", "ME2.0", "BasicSens1.fmu"), _connect_dll=False) + caps = model.get_capability_flags() + model.get_capability_flags = lambda: caps + cost = {"rhs": 0.0, "dd": 0.0} + + def rhs(*args, **kwargs): + _time.sleep(cost["rhs"]) + return np.array([model.continuous_states[0]]) + + def dd(*args, **kwargs): + _time.sleep(cost["dd"]) + return np.array([1.0]) + + model.get_derivatives = rhs + model.get_directional_derivative = dd + opts = model.simulate_options() + opts["result_handling"] = None + opts["with_jacobian"] = True + + def run_case(expected_mode, expected_force_fd, solver="CVode", rtol=1e-6): + model.reset() + opts["solver"] = solver + opts[solver + "_options"]["rtol"] = rtol + alg = NoSolveAlg(0.0, 1.0, (), model, opts) + assert alg.jacobian_mode == expected_mode, alg.jacobian_mode + assert model.force_finite_differences == expected_force_fd, model.force_finite_differences + + # no directional derivatives: always finite differences, nothing to force + caps["providesDirectionalDerivatives"] = False + for mode in ("auto", "dd", "fd"): + opts["jacobian_mode"] = mode + run_case("fd", 0) + + caps["providesDirectionalDerivatives"] = True + model._provides_directional_derivatives = lambda: True + opts["jacobian_mode"] = "dd" + run_case("dd", 0) + opts["jacobian_mode"] = "fd" + run_case("fd", True) + + # auto: decided by the measured cost of a directional derivative vs an rhs + opts["jacobian_mode"] = "auto" + cost["rhs"], cost["dd"] = 0.0, 0.002 + run_case("fd", True) + cost["rhs"], cost["dd"] = 0.002, 0.0 + run_case("dd", 0) + # a cheap directional derivative stays exact even if the rhs is cheaper still + import pyfmi.fmi_algorithm_drivers as fad + floor = fad.PYFMI_JACOBIAN_FD_MIN_DD_TIME + fad.PYFMI_JACOBIAN_FD_MIN_DD_TIME = 1.0 + try: + run_case("dd", 0) + finally: + fad.PYFMI_JACOBIAN_FD_MIN_DD_TIME = floor + # ... except when the solver needs the exact Jacobian or the tolerance is tight + cost["rhs"], cost["dd"] = 0.0, 0.002 + run_case("dd", 0, solver="RodasODE") + run_case("dd", 0, rtol=1e-8) + + # not with_jacobian: nothing decided, nothing forced + opts["with_jacobian"] = False + model.reset() + alg = NoSolveAlg(0.0, 1.0, (), model, opts) + assert alg.jacobian_mode is None + assert model.force_finite_differences == 0 + + # the model attribute is restored after the simulation + opts["with_jacobian"] = True + opts["jacobian_mode"] = "fd" + model.reset() + alg = NoSolveAlg(0.0, 1.0, (), model, opts) + assert model.force_finite_differences is True + alg.solve() + alg.get_result() + assert model.force_finite_differences == 0 + + opts["jacobian_mode"] = "central" + with pytest.raises(InvalidOptionException): + NoSolveAlg(0.0, 1.0, (), model, opts) + def test_sparse_option(self): def run_case(expected_jacobian, expected_sparse, fnbr=0, nnz={}, set_sparse=False): From 984c760bcfbb16ec0ec0ffa1795595335ceaa464 Mon Sep 17 00:00:00 2001 From: Hubertus Tummescheit Date: Sat, 19 Sep 2026 18:47:09 -0400 Subject: [PATCH 2/4] FMI2: kink guard for the coloured finite-difference Jacobian A forward difference taken across a kink of the model -- a limiter, a region boundary of a property function -- returns jump/h (1e8 and more) where the derivative on this side is small. Newton-based integrators converge on the corrupted iteration matrix and reuse it for many steps. Measured on a 318- state combined-cycle plant at rtol 1e-6: two such entries in 200 Jacobian evaluations (d der(pump.s)/d s = -3.2e8 vs 0 at the end of the steam-table failure zone; d der(drum.p)/d hl = -1.3e8 vs -0.18 at t = 0) moved 91 of 308 plant states more than 1e-3 off the rtol 1e-8 reference. The guard (FMUModelME2.fd_kink_guard, default True) works per colour group of _estimate_directional_derivative: - flag: an entry that grew more than 1e3x relative to the previous Jacobian and is not negligible relative to it marks the group as suspect; the first evaluation checks every group. Kinks are transient, so this is nearly free. - confirm: a suspect group is re-differenced with a 10x smaller step; entries whose quotient changes by more than 10 % are kinks (a jump scales with 1/h, a smooth function does not). - fix: kink entries take the FMU's directional derivative for the group when it has one, else the smaller in magnitude of the forward and the backward difference (the side without the jump). Model variables are restored after each check; statistics in _fd_guard_stats. With the guard, CVode with the FD Jacobian on the plant matches the DD run's accuracy (plant median 5.0e-6 vs 9.8e-6, 4 vs 1 states beyond 1e-3, 23 events) at 5458 instead of 14353 steps and 320 instead of 511 Jacobians, each half the cost: 229 s instead of 340 s. On a 226-state plant and a 141-state vehicle model the guard changes nothing (accuracy and time within noise). FMI3's separate finite-difference routine is unchanged. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p --- src/pyfmi/fmi2.pxd | 1 + src/pyfmi/fmi2.pyx | 112 +++++++++++++++++++++++++++++++++++++++++++++ tests/test_fmi2.py | 41 ++++++++++++++++- 3 files changed, 153 insertions(+), 1 deletion(-) diff --git a/src/pyfmi/fmi2.pxd b/src/pyfmi/fmi2.pxd index 8cd24e31..6a509a7d 100644 --- a/src/pyfmi/fmi2.pxd +++ b/src/pyfmi/fmi2.pxd @@ -149,6 +149,7 @@ cdef class FMUModelME2(FMUModelBase2): cpdef _set_time(self, FMIL2.fmi2_real_t t) cpdef get_derivatives(self) cdef public object force_finite_differences + cdef public object fd_kink_guard, _fd_guard_prev, _fd_guard_prev_max, _fd_guard_cur, _fd_guard_stats cdef int _get_derivatives(self, FMIL2.fmi2_real_t[:] values) cdef int _get_continuous_states_fmil(self, FMIL2.fmi2_real_t[:] ndx) cdef int _set_continuous_states_fmil(self, FMIL2.fmi2_real_t[:] ndx) diff --git a/src/pyfmi/fmi2.pyx b/src/pyfmi/fmi2.pyx index 6f1c39d6..baa11461 100644 --- a/src/pyfmi/fmi2.pyx +++ b/src/pyfmi/fmi2.pyx @@ -105,6 +105,14 @@ FMI2_INITIAL_UNKNOWN = 3 DEF FORWARD_DIFFERENCE = 1 DEF CENTRAL_DIFFERENCE = 2 FORWARD_DIFFERENCE_EPS = (np.finfo(float).eps)**0.5 +# Kink guard (fd_kink_guard): an entry of the forward-difference Jacobian is suspect when it is +# more than FD_GUARD_JUMP times its value in the previous Jacobian (and not negligible relative +# to that Jacobian); a suspect colour group is re-differenced with a 10x smaller step, and entries +# that differ by more than FD_GUARD_REL between the two steps are kinks (the difference quotient +# scales with 1/h across a jump, it does not on a smooth function). +FD_GUARD_JUMP = 1e3 +FD_GUARD_REL = 0.1 +FD_GUARD_STEP_RATIO = 0.1 CENTRAL_DIFFERENCE_EPS = (np.finfo(float).eps)**(1/3.0) # Flags for evaluation of FMI Jacobians @@ -4284,6 +4292,12 @@ cdef class FMUModelME2(FMUModelBase2): self._eventInfo.nextEventTime = 0.0 self.force_finite_differences = 0 + # Kink guard for the coloured finite-difference Jacobian (see _fd_kink_guard_group) + self.fd_kink_guard = True + self._fd_guard_prev = None + self._fd_guard_prev_max = 0.0 + self._fd_guard_cur = None + self._fd_guard_stats = {"evaluations": 0, "checked_groups": 0, "kink_entries": 0, "dd_substitutions": 0} # State nominals retrieved before initialization self._preinit_nominal_continuous_states = None @@ -4917,6 +4931,85 @@ cdef class FMUModelME2(FMUModelBase2): else: return self._estimate_directional_derivative(var_ref, func_ref, group, add_diag, output_matrix) + def _fd_kink_guard_group(self, colvals, local_group, fac, var_ref, func_ref, v_ref, z_ref, eps, df, v): + """ + Kink guard for one colour group of the forward-difference Jacobian. + + A forward difference taken across a kink or a discontinuity of the model + (a limiter, a region boundary of a property function) returns a + difference quotient of order jump/h -- 1e8 and more -- where the derivative + on this side of the kink is small. Newton-based integrators then converge + on a corrupted iteration matrix and reuse it for many steps; on a 318-state + plant two such entries in 200 Jacobian evaluations moved a third of the + states off the converged solution at rtol 1e-6. + + Detection, cheap: an entry is suspect when it grew by more than + FD_GUARD_JUMP relative to the previous Jacobian (kinks are transient) and is + not negligible relative to that Jacobian; on the first evaluation every + group is suspect. A suspect group is re-differenced with a 10x smaller step: + entries whose quotient changes by more than FD_GUARD_REL between the two + steps are kinks (a smooth function gives the same quotient, a jump scales it + with 1/h). Kink entries are replaced by the FMU's directional derivative for + this group when it has one, else by the smaller in magnitude of the forward + and the backward difference (the side without the jump). + + Returns the corrected column values, or None when nothing was changed. The + model's variables are restored to their values before the call. Statistics + in self._fd_guard_stats; switch off with self.fd_kink_guard = False. + """ + rows = local_group[2] + cols = local_group[3] + vars_ = local_group[0] + n = len(rows) + pos = sum(len(c) for c in self._fd_guard_cur) + prev = self._fd_guard_prev + cur = colvals.copy() + try: + if prev is not None and prev.shape[0] >= pos + n: + p = prev[pos:pos + n] + floor = 1e-6 * self._fd_guard_prev_max + suspect = bool(np.any((np.abs(cur) > FD_GUARD_JUMP * np.abs(p)) & (np.abs(cur) > floor))) + else: + suspect = True # first evaluation, or the structure changed + if not suspect: + return None + self._fd_guard_stats["checked_groups"] += 1 + + base = np.asarray(v[vars_], dtype=np.double) # unperturbed values (the caller has already perturbed the model) + step = fac * eps[vars_] + z_refs = z_ref[rows] + dfr = df[rows] + h_col = fac * eps[cols] # per entry: the step of its column variable + + def quotient(sign, ratio): + self.set_real(v_ref[vars_], base + sign * ratio * step) + try: + z = self.get_real(z_refs) + finally: + self.set_real(v_ref[vars_], base) + return sign * (z - dfr) / (ratio * h_col) + + small = quotient(1.0, FD_GUARD_STEP_RATIO) + tiny = 1e-12 * max(float(np.max(np.abs(cur))), 1e-300) + kink = np.abs(small - cur) > FD_GUARD_REL * np.maximum(np.abs(cur), np.abs(small)) + tiny + if not kink.any(): + return None + self._fd_guard_stats["kink_entries"] += int(kink.sum()) + + if self._provides_directional_derivatives(): + seed = np.zeros(len(var_ref), dtype=np.double) + seed[vars_] = 1.0 + dd = self.get_directional_derivative(var_ref, func_ref, seed)[rows] + cur[kink] = dd[kink] + self._fd_guard_stats["dd_substitutions"] += int(kink.sum()) + else: + back = quotient(-1.0, 1.0) + pick = np.abs(back) < np.abs(cur) + cur[kink & pick] = back[kink & pick] + return cur + finally: + self._fd_guard_cur.append(cur) + @cython.boundscheck(False) @cython.wraparound(False) @cython.cdivision(True) @@ -5003,6 +5096,9 @@ cdef class FMUModelME2(FMUModelBase2): row.extend(range(dim)) col.extend(range(dim)) + if method == FORWARD_DIFFERENCE and self.fd_kink_guard: + self._fd_guard_cur = [] + self._fd_guard_stats["evaluations"] += 1 for key in group["groups"]: local_group = group[key] sol_found = 0 @@ -5064,6 +5160,15 @@ cdef class FMUModelME2(FMUModelBase2): sol_found = 1 if sol_found: + if method == FORWARD_DIFFERENCE and self.fd_kink_guard: + colvals = np.empty(local_indices_matrix_rows_nbr, dtype=np.double) + for i in range(local_indices_matrix_rows_nbr): + colvals[i] = column_data_pt[i] + guarded = self._fd_kink_guard_group(colvals, local_group, fac, var_ref, func_ref, v_ref, z_ref, eps, df, + self._worker_object.get_real_numpy_vector(1)) + if guarded is not None: + for i in range(local_indices_matrix_rows_nbr): + column_data_pt[i] = guarded[i] if output_matrix is not None: for i in range(local_indices_matrix_rows_nbr): output_matrix_data_pt[local_data_indices[i]] = column_data_pt[i] @@ -5081,6 +5186,13 @@ cdef class FMUModelME2(FMUModelBase2): for i in range(local_indices_vars_nbr): tmp_val_pt[i] = v_pt[local_indices_vars_pt[i]] self._set_real(local_v_vref_pt, tmp_val_pt, local_indices_vars_nbr) + if method == FORWARD_DIFFERENCE and self.fd_kink_guard: + # the accepted values become the reference for the next evaluation's jump test + prev = np.concatenate(self._fd_guard_cur) if self._fd_guard_cur else np.zeros(0) + self._fd_guard_prev = prev + self._fd_guard_prev_max = float(np.max(np.abs(prev))) if prev.size else 0.0 + self._fd_guard_cur = None + if output_matrix is not None: A = output_matrix else: diff --git a/tests/test_fmi2.py b/tests/test_fmi2.py index 08a4344f..d9669130 100644 --- a/tests/test_fmi2.py +++ b/tests/test_fmi2.py @@ -910,6 +910,45 @@ def get_event_info(self): fmu.simulate() + def test_fd_kink_guard(self): + """Forward differences across a kink give jump/h; the guard detects them with a second + step and replaces them by the backward difference (no directional derivatives here).""" + model = Dummy_FMUModelME2([], os.path.join(file_path, "files", "FMUs", "XML", "ME2.0", "LinearStateSpace.fmu"), _connect_dll=False) + x1 = model.variables["x[1]"].value_reference + x2 = model.variables["x[2]"].value_reference + d1 = model.variables["der(x[1])"].value_reference + d2 = model.variables["der(x[2])"].value_reference + kink_at = [None] + + def f(*args, **kwargs): + v1, v2 = model.values[x1], model.values[x2] + jump = 1.0 if (kink_at[0] is not None and v1 > kink_at[0]) else 0.0 # step of size 1 just above x1 + model.values[d1] = -v1 + jump + model.values[d2] = -v2 + 2.0 * v1 + return np.array([model.values[d1], model.values[d2]]) + model.get_derivatives = f + model.initialize(); model.event_update(); model.enter_continuous_time_mode() + model.continuous_states = np.array([1.0, 1.0]); model.values[x1] = 1.0; model.values[x2] = 1.0 + + # smooth: the guard checks every group on the first evaluation and changes nothing + A = model._get_A(add_diag=True).toarray() + assert np.allclose(A, [[-1.0, 0.0], [2.0, -1.0]]), A + assert model._fd_guard_stats["kink_entries"] == 0 and model._fd_guard_stats["checked_groups"] >= 1 + + # a kink right above x1: the forward difference sees the jump (1/eps ~ 6.7e7) + kink_at[0] = 1.0 + 0.5 * np.sqrt(np.finfo(float).eps) + model.fd_kink_guard = False + A_raw = model._get_A(add_diag=True).toarray() + assert A_raw[0, 0] > 1e6, A_raw + model.fd_kink_guard = True + A_guarded = model._get_A(add_diag=True).toarray() + assert np.allclose(A_guarded, [[-1.0, 0.0], [2.0, -1.0]]), A_guarded + assert model._fd_guard_stats["kink_entries"] >= 1 + + # off: the raw column comes through + model.fd_kink_guard = False + assert model._get_A(add_diag=True).toarray()[0, 0] > 1e6 + @pytest.mark.assimulo class Test_FMUModelBase2: def test_relative_quantity(self): @@ -1209,4 +1248,4 @@ def test_no_state_fmu_eval_failure_caught(fmu_path): fmu = load_fmu(fmu_path) expected_err = "The right-hand side function had repeated recoverable errors" with pytest.raises(CVodeError, match = re.escape(expected_err)): - fmu.simulate() \ No newline at end of file + fmu.simulate() From 8fb5408bf07cf0c0077e0577d575c7aaa87cff5c Mon Sep 17 00:00:00 2001 From: Hubertus Tummescheit Date: Tue, 22 Sep 2026 19:38:26 -0400 Subject: [PATCH 3/4] jacobian_mode: document the kink-guarded finite differences in the option's help The default stays "auto" (as introduced); this records what the kink guard protects against and asserts the default in the option test. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p --- src/pyfmi/fmi_algorithm_drivers.py | 8 ++++++++ tests/test_fmi2.py | 1 + 2 files changed, 9 insertions(+) diff --git a/src/pyfmi/fmi_algorithm_drivers.py b/src/pyfmi/fmi_algorithm_drivers.py index e012b650..7cecf2ef 100644 --- a/src/pyfmi/fmi_algorithm_drivers.py +++ b/src/pyfmi/fmi_algorithm_drivers.py @@ -125,6 +125,14 @@ class AssimuloFMIAlgOptions(OptionBase): directional derivatives the Jacobian is always "fd". The mode that was used is available as the 'jacobian_mode' attribute of the algorithm object. + + On FMUs whose directional derivatives cost more than an rhs + evaluation "fd" halves the simulation time of CVode and + Radau5ODE on 100-300 state models at unchanged accuracy. The + finite differences are protected by a kink guard + (FMUModelME2.fd_kink_guard): without it a difference taken + across a kink of the model (a limiter, a property-function + region boundary) corrupts the Newton matrix for many steps. Default: "auto" dynamic_diagnostics -- diff --git a/tests/test_fmi2.py b/tests/test_fmi2.py index d9669130..98028ab4 100644 --- a/tests/test_fmi2.py +++ b/tests/test_fmi2.py @@ -361,6 +361,7 @@ def run_case(expected_mode, expected_force_fd, solver="CVode", rtol=1e-6): caps["providesDirectionalDerivatives"] = True model._provides_directional_derivatives = lambda: True + assert model.simulate_options()["jacobian_mode"] == "auto" opts["jacobian_mode"] = "dd" run_case("dd", 0) opts["jacobian_mode"] = "fd" From 5a9df97151c686b767151c97354bd6727cca6128 Mon Sep 17 00:00:00 2001 From: Hubertus Tummescheit Date: Mon, 21 Sep 2026 11:43:05 -0400 Subject: [PATCH 4/4] FMIODE2.jac: an FMU failure while forming the Jacobian is recoverable; the FD kink guard's probe steps aside when the model refuses it rhs() already turns an FMU failure at a trial point into AssimuloRecoverableError; jac() let the raw FMUException through, which ended the run under any solver that asks for the Jacobian (CVode with_jacobian, TRBDF2, Radau5). Now the same mapping: CVode answers with CVDLS_JACFUNC_RECVR, TRBDF2 falls back to its own differences (Assimulo trbdf2 branch). The one path that actually raised: _fd_kink_guard_group()'s probe at a smaller step called get_real() unguarded, so a nonlinear block that does not converge at the probe point ('Failed to get the Real values.') killed a Jacobian whose columns were already computed. A refused probe is not a kink: the guard returns None and the column stands; counted in _fd_guard_stats['probe_failures']. Measured 2026-09-21: DataCenter.Examples.Systems.StandardChillerSystem and ChillerWithEconomizerSystem (30 days, no directional derivatives) now complete under TRBDF2 with CVode's event counts (133 / 132 state events); each had exactly one refused probe, at t = 0 for the second. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p --- src/pyfmi/fmi2.pyx | 10 ++++++++-- src/pyfmi/simulation/assimulo_interface_fmi2.pyx | 13 ++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/pyfmi/fmi2.pyx b/src/pyfmi/fmi2.pyx index baa11461..3182d82b 100644 --- a/src/pyfmi/fmi2.pyx +++ b/src/pyfmi/fmi2.pyx @@ -4297,7 +4297,7 @@ cdef class FMUModelME2(FMUModelBase2): self._fd_guard_prev = None self._fd_guard_prev_max = 0.0 self._fd_guard_cur = None - self._fd_guard_stats = {"evaluations": 0, "checked_groups": 0, "kink_entries": 0, "dd_substitutions": 0} + self._fd_guard_stats = {"evaluations": 0, "checked_groups": 0, "kink_entries": 0, "dd_substitutions": 0, "probe_failures": 0} # State nominals retrieved before initialization self._preinit_nominal_continuous_states = None @@ -4989,7 +4989,13 @@ cdef class FMUModelME2(FMUModelBase2): self.set_real(v_ref[vars_], base) return sign * (z - dfr) / (ratio * h_col) - small = quotient(1.0, FD_GUARD_STEP_RATIO) + try: + small = quotient(1.0, FD_GUARD_STEP_RATIO) + except FMUException: + # the model refused the probe point: not a kink, and not a reason to + # lose the column the caller already has -- the guard steps aside + self._fd_guard_stats["probe_failures"] += 1 + return None tiny = 1e-12 * max(float(np.max(np.abs(cur))), 1e-300) kink = np.abs(small - cur) > FD_GUARD_REL * np.maximum(np.abs(cur), np.abs(small)) + tiny if not kink.any(): diff --git a/src/pyfmi/simulation/assimulo_interface_fmi2.pyx b/src/pyfmi/simulation/assimulo_interface_fmi2.pyx index 2706116f..8b8a0527 100644 --- a/src/pyfmi/simulation/assimulo_interface_fmi2.pyx +++ b/src/pyfmi/simulation/assimulo_interface_fmi2.pyx @@ -302,7 +302,18 @@ cdef class FMIODE2(cExplicit_Problem): if self._f_nbr == 0: return np.array([[0.0]]) - A = self._model._get_A(add_diag=True, output_matrix=self._A) + # The FMU refusing a perturbed state (a nonlinear block that does not + # converge there, a bracketing failure) is a refused trial point, the + # same thing as in rhs(): recoverable, the solver shrinks its step or + # falls back to its own differences (CVode: CVDLS_JACFUNC_RECVR; + # TRBDF2: rhs-based differences, then the previous Jacobian). + # Measured 2026-09-21 on DataCenter.Examples.Systems.StandardChillerSystem + # and ChillerWithEconomizerSystem (no directional derivatives), where + # the raw FMUException ended a 30-day TRBDF2 run that CVode completed. + try: + A = self._model._get_A(add_diag=True, output_matrix=self._A) + except FMUException: + raise AssimuloRecoverableError if self._A is None: self._A = A