Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/pyfmi/fmi2.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
112 changes: 112 additions & 0 deletions src/pyfmi/fmi2.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand All @@ -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:
Expand Down
118 changes: 118 additions & 0 deletions src/pyfmi/fmi_algorithm_drivers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"]
Expand All @@ -682,6 +799,7 @@ def get_result(self):

The AssimuloSimResult object.
"""
self._restore_jacobian_mode()
time_start = timer()

if self.options["return_result"]:
Expand Down
Loading