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/src/pyfmi/fmi_algorithm_drivers.py b/src/pyfmi/fmi_algorithm_drivers.py index dae2fa3d..7cecf2ef 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,31 @@ 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. + + 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 -- 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 +253,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 +402,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 +599,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 +783,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 +799,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..98028ab4 100644 --- a/tests/test_fmi2.py +++ b/tests/test_fmi2.py @@ -323,6 +323,90 @@ 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 + assert model.simulate_options()["jacobian_mode"] == "auto" + 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): @@ -827,6 +911,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): @@ -1126,4 +1249,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()