Skip to content
Merged
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
9 changes: 4 additions & 5 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind",
"workspaceFolder": "/src",

// Docker from inside the container. See https://aka.ms/vscode-remote/samples/docker-from-docker.
// "mounts": [ "source=/var/run/docker.sock,target=/var/run/docker.sock,type=bind" ],

"onCreateCommand":["make", ".venv"],
"onCreateCommand": ["make", ".venv"],

// Python IDE settings:
"customizations": {"vscode": {
Expand All @@ -30,5 +27,7 @@
}},

// User from Dockerfile:
"remoteUser": "root"
"containerUser": "dev",
"remoteUser": "dev",
"updateRemoteUserUID": true
}
6 changes: 6 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
--- CHANGELOG ---
--- PyFMI-FUTURE ---
* Now requires Assimulo >= 3.9.0.
* Fixed a bug where step events ran two event iterations instead of one.
* Fixed a crash when simulating models with step events using `logging = True` or `dynamic_diagnostics = True`.
* Added step events to `dynamic_diagnostics`: `event_type` value `2` and the variable `@Diagnostics.nbr_step_events`.
The event types are available as `pyfmi.common.diagnostics.EventType`.
Comment thread
PeterMeisrimelModelon marked this conversation as resolved.
Resolved
A step event in the same step as a time or state event is recorded as that time or state event.

--- PyFMI-2.23.0 ---
* Fixed an exception when using `dynamic_diagnostics` for FMUs with `unbounded = True` states.
Expand Down
17 changes: 14 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ RUN apt update && apt install python3.11 python3-pip python3.11-dev python3.11-v

# Install system
RUN python3.11 -m pip install Cython numpy scipy matplotlib setuptools==69.1.0
RUN apt-get -y install cmake liblapack-dev libsuitesparse-dev libhypre-dev curl git make vim bash-completion
RUN apt-get -y install cmake liblapack-dev libsuitesparse-dev libhypre-dev curl git make vim bash-completion sudo
RUN cp -v /usr/lib/x86_64-linux-gnu/libblas.so /usr/lib/x86_64-linux-gnu/libblas_OPENMP.so

# Install superlu
Expand All @@ -30,10 +30,10 @@ RUN git clone --depth 1 -b v2.7.0 https://github.com/LLNL/sundials /tmp/sundials
make install

#Install assimulo
RUN git clone --depth 1 -b Assimulo-3.8.0 https://github.com/modelon-community/Assimulo /tmp/Assimulo && \
RUN git clone --depth 1 -b Assimulo-3.9.0 https://github.com/modelon-community/Assimulo /tmp/Assimulo && \
cd /tmp/Assimulo && \
rm setup.cfg && \
python3.11 setup.py install --user --sundials-home=/usr --blas-home=/usr/lib/x86_64-linux-gnu/ --lapack-home=/usr/lib/x86_64-linux-gnu/ --superlu-home=/usr
python3.11 setup.py install --sundials-home=/usr --blas-home=/usr/lib/x86_64-linux-gnu/ --lapack-home=/usr/lib/x86_64-linux-gnu/ --superlu-home=/usr

# Install fmilib
RUN cd /tmp && \
Expand All @@ -44,7 +44,18 @@ RUN cd /tmp && \
make -j4 && \
make install

# Non-root user matching the typical host user (UID/GID 1000).
ARG USERNAME=dev
ARG USER_UID=1000
ARG USER_GID=${USER_UID}
RUN groupadd --gid ${USER_GID} ${USERNAME} && \
useradd --uid ${USER_UID} --gid ${USER_GID} --create-home --shell /bin/bash ${USERNAME} && \
echo "${USERNAME} ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/${USERNAME} && \
chmod 0440 /etc/sudoers.d/${USERNAME} && \
chown -R ${USER_UID}:${USER_GID} /home/${USERNAME}

# Setup a venv to put pip and python on path for convinience running commands
ARG PYTHON_VENV=/src/.venv
ENV PATH=${PYTHON_VENV}/bin:$PATH
WORKDIR /src
USER ${USERNAME}
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ define _run
else \
docker run \
--rm $(2) \
--user $(shell id -u):$(shell id -g) \
-v $(CURDIR):/src \
${DOCKER_IMAGE} \
$(1); \
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ install_requires =
scipy >= 1.10.1
cython >= 3.0.7
matplotlib > 3
assimulo >= 3.5.0
assimulo >= 3.9.0

tests_require =
pytest >= 7.4.4
39 changes: 30 additions & 9 deletions src/common/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,22 @@

import numpy as np
import numbers
from enum import IntEnum

DIAGNOSTICS_PREFIX = '@Diagnostics.'

class EventType(IntEnum):
"""Values of '@Diagnostics.event_data.event_info.event_type'."""
NO_EVENT = -1
STATE_EVENT = 0
TIME_EVENT = 1
STEP_EVENT = 2

@classmethod
def value_legend(cls):
return ", ".join(f"{e.name.replace('_', ' ')}={e.value}" for e in cls).capitalize()


class DiagnosticsBase: # TODO: Future, possible deprecate & remove this?
""" Class serves as a template
to keep track of diagnostics variables not part of the generated result file.
Expand All @@ -31,6 +44,7 @@ class DiagnosticsBase: # TODO: Future, possible deprecate & remove this?
'nbr_events': {'name': f'{DIAGNOSTICS_PREFIX}nbr_events', 'description': 'Cumulative number of events'},
'nbr_time_events': {'name': f'{DIAGNOSTICS_PREFIX}nbr_time_events', 'description': 'Cumulative number of time events'},
'nbr_state_events': {'name': f'{DIAGNOSTICS_PREFIX}nbr_state_events', 'description': 'Cumulative number of state events'},
'nbr_step_events': {'name': f'{DIAGNOSTICS_PREFIX}nbr_step_events', 'description': 'Cumulative number of step events'},
'nbr_steps': {'name': f'{DIAGNOSTICS_PREFIX}nbr_steps', 'description': 'Cumulative number of steps'},
'nbr_state_limits_step': {'name': f'{DIAGNOSTICS_PREFIX}nbr_state_limits_step', 'description': 'Cumulative number of times states limit the step'},
}
Expand Down Expand Up @@ -80,6 +94,7 @@ def prepare_calculated_diagnostics(self, diagnostics_vars: dict) -> dict:
f"{DIAGNOSTICS_PREFIX}nbr_events" : (0, "Cumulative number of events"),
f"{DIAGNOSTICS_PREFIX}nbr_time_events" : (0, "Cumulative number of time events"),
f"{DIAGNOSTICS_PREFIX}nbr_state_events": (0, "Cumulative number of state events"),
f"{DIAGNOSTICS_PREFIX}nbr_step_events" : (0, "Cumulative number of step events"),
f"{DIAGNOSTICS_PREFIX}nbr_steps" : (0, "Cumulative number of steps"),
}
if f"{DIAGNOSTICS_PREFIX}cpu_time_per_step" in diagnostics_vars.keys():
Expand All @@ -104,6 +119,7 @@ def prepare_calculated_diagnostics(self, diagnostics_vars: dict) -> dict:
"nbr_events": calc_diags_names.index(f'{DIAGNOSTICS_PREFIX}nbr_events'),
"nbr_time_events": calc_diags_names.index(f'{DIAGNOSTICS_PREFIX}nbr_time_events'),
"nbr_state_events": calc_diags_names.index(f'{DIAGNOSTICS_PREFIX}nbr_state_events'),
"nbr_step_events": calc_diags_names.index(f'{DIAGNOSTICS_PREFIX}nbr_step_events'),
"nbr_steps": calc_diags_names.index(f'{DIAGNOSTICS_PREFIX}nbr_steps'),
"nbr_state_limits": len(calc_diags_names) - self._number_states,
}
Expand Down Expand Up @@ -167,17 +183,20 @@ def get_calculated_diagnostics_point(self, diag_data: np.ndarray) -> np.ndarray:
if self._idx_map_diags["event_type"] is not None:
# event point
etype = diag_data[self._idx_map_diags["event_type"]]
if etype == 1:
if etype == EventType.TIME_EVENT:
ret[self._idx_map_calc_diags["nbr_events"]] += 1
ret[self._idx_map_calc_diags["nbr_time_events"]] += 1
elif etype == 0:
elif etype == EventType.STATE_EVENT:
ret[self._idx_map_calc_diags["nbr_events"]] += 1
ret[self._idx_map_calc_diags["nbr_state_events"]] += 1
elif etype == EventType.STEP_EVENT:
ret[self._idx_map_calc_diags["nbr_events"]] += 1
ret[self._idx_map_calc_diags["nbr_step_events"]] += 1
else:
ret[self._idx_map_calc_diags["nbr_steps"]] += 1

# state_errors
if etype == -1: # no event
if etype == EventType.NO_EVENT:
index_diag_data = self._idx_map_diags["state_errors"]
index_calc = self._idx_map_calc_diags["nbr_state_limits"]
for i in range(self._number_states):
Expand All @@ -198,21 +217,23 @@ def get_events_and_steps(cls, event_type_data: np.ndarray) -> dict:
'{DIAGNOSTICS_PREFIX}nbr_events',
'{DIAGNOSTICS_PREFIX}nbr_time_events',
'{DIAGNOSTICS_PREFIX}nbr_state_events',
'{DIAGNOSTICS_PREFIX}nbr_step_events',
'{DIAGNOSTICS_PREFIX}nbr_steps'
"""
return {
f"{DIAGNOSTICS_PREFIX}nbr_events": np.cumsum(event_type_data != -1),
f"{DIAGNOSTICS_PREFIX}nbr_time_events": np.cumsum(event_type_data == 1),
f"{DIAGNOSTICS_PREFIX}nbr_state_events": np.cumsum(event_type_data == 0),
f"{DIAGNOSTICS_PREFIX}nbr_steps": np.concatenate(([0], np.cumsum(event_type_data[1:] == -1))), # do not count the first point
f"{DIAGNOSTICS_PREFIX}nbr_events": np.cumsum(event_type_data != EventType.NO_EVENT),
f"{DIAGNOSTICS_PREFIX}nbr_time_events": np.cumsum(event_type_data == EventType.TIME_EVENT),
f"{DIAGNOSTICS_PREFIX}nbr_state_events": np.cumsum(event_type_data == EventType.STATE_EVENT),
f"{DIAGNOSTICS_PREFIX}nbr_step_events": np.cumsum(event_type_data == EventType.STEP_EVENT),
f"{DIAGNOSTICS_PREFIX}nbr_steps": np.concatenate(([0], np.cumsum(event_type_data[1:] == EventType.NO_EVENT))), # do not count the first point
}

@classmethod
def get_nbr_state_limits(cls, event_type_data: np.ndarray, state_error: np.ndarray) -> np.ndarray:
"""Given event_type_data trajectory, return the cumulative number of times
the (normalized) state_error exceeded 1 (= limited step-size)."""
min_nbr_states = min(event_type_data.size, state_error.size)
return np.cumsum((event_type_data[:min_nbr_states] == -1) * (state_error[:min_nbr_states] >= 1.0))
return np.cumsum((event_type_data[:min_nbr_states] == EventType.NO_EVENT) * (state_error[:min_nbr_states] >= 1.0))

def setup_diagnostics_variables(model, start_time, options, solver_options):
""" Sets up initial diagnostics data. This function is called before a simulation is initiated."""
Expand Down Expand Up @@ -276,6 +297,6 @@ def setup_diagnostics_variables(model, start_time, options, solver_options):
_diagnostics_vars[f"{DIAGNOSTICS_PREFIX}event_data.event_info.indicator_"+str(i+1)] = (ei_values[i], "Value for event indicator {}.".format(i+1))
for i in range(nof_ei):
_diagnostics_vars[f"{DIAGNOSTICS_PREFIX}event_data.event_info.state_event_info.index_"+str(i+1)] = (0.0, "Zero crossing indicator for event indicator {}".format(i+1))
_diagnostics_vars[f"{DIAGNOSTICS_PREFIX}event_data.event_info.event_type"] = (-1, "No event=-1, state event=0, time event=1")
_diagnostics_vars[f"{DIAGNOSTICS_PREFIX}event_data.event_info.event_type"] = (EventType.NO_EVENT, EventType.value_legend())

return _diagnostics_params, _diagnostics_vars
1 change: 1 addition & 0 deletions src/common/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -1762,6 +1762,7 @@ def _get_calculated_diags_trajectory(self, name: str) -> np.ndarray:
f"{DIAGNOSTICS_PREFIX}nbr_events",
f"{DIAGNOSTICS_PREFIX}nbr_time_events",
f"{DIAGNOSTICS_PREFIX}nbr_state_events",
f"{DIAGNOSTICS_PREFIX}nbr_step_events",
f"{DIAGNOSTICS_PREFIX}nbr_steps",
]
):
Expand Down
18 changes: 13 additions & 5 deletions src/pyfmi/simulation/assimulo_interface_fmi2.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ from timeit import default_timer as timer
cimport pyfmi.fmil_import as FMIL
cimport pyfmi.fmi2 as FMI2
from pyfmi.fmi2 import FMI2_REAL, FMI2_INPUT
from pyfmi.common.diagnostics import EventType
from pyfmi.exceptions import (
FMUException,
InvalidOptionException,
Expand All @@ -44,6 +45,9 @@ from pyfmi.exceptions import (
from assimulo.problem cimport cExplicit_Problem
from assimulo.exception import AssimuloRecoverableError, TerminateSimulation

# Stored on every solver step, so held as a C double.
cdef double NO_EVENT = EventType.NO_EVENT

cdef class FMIODE2(cExplicit_Problem):
"""
An Assimulo Explicit Model extended to FMI2 interface.
Expand Down Expand Up @@ -404,6 +408,8 @@ cdef class FMIODE2(cExplicit_Problem):
This method is called when Assimulo finds an event.
"""
cdef int status
# A state or time event in the same step takes precedence.
cdef bint step_event = event_info[2] and not event_info[1] and not any(event_info[0])

if self._extra_f_nbr > 0:
y_extra = solver.y[-self._extra_f_nbr:]
Expand Down Expand Up @@ -441,6 +447,7 @@ cdef class FMIODE2(cExplicit_Problem):
fwrite.write("\nDetected event at t = %.14E \n"%solver.t)
fwrite.write(" State event info: "+" ".join(str(i) for i in event_info[0])+ "\n")
fwrite.write(" Time event info: "+str(event_info[1])+ "\n")
fwrite.write(" Step event info: "+str(step_event)+ "\n")

preface = "[INFO][FMU status:OK] "
event_info_tag = 'EventInfo'
Expand All @@ -454,6 +461,9 @@ cdef class FMIODE2(cExplicit_Problem):
msg = preface + ' <boolean name="time_event_info">' + str(event_info[1]) + '</boolean>'
self._model.append_log_message("Model", 6, msg)

msg = preface + ' <boolean name="step_event_info">' + str(step_event) + '</boolean>'
self._model.append_log_message("Model", 6, msg)

msg = preface + '</%s>'%(event_info_tag)
self._model.append_log_message("Model", 6, msg)
else:
Expand Down Expand Up @@ -486,13 +496,13 @@ cdef class FMIODE2(cExplicit_Problem):
while index < self._number_of_diagnostics_variables - 1:
diag_data[index] = 0
index +=1
diag_data[index] = 1.0
diag_data[index] = EventType.TIME_EVENT
index +=1
else:
for ei in event_info[0]:
diag_data[index] = ei
index +=1
diag_data[index] = 0.0
diag_data[index] = EventType.STEP_EVENT if step_event else EventType.STATE_EVENT
index +=1
if index != self._number_of_diagnostics_variables:
raise FMUException("Failed logging diagnostics, number of data points expected to be {} but was {}".format(self._number_of_diagnostics_variables, index))
Expand Down Expand Up @@ -659,7 +669,7 @@ cdef class FMIODE2(cExplicit_Problem):
diag_data[index] = 0
index +=1
if support_event_indicators:
diag_data[index] = float(-1)
diag_data[index] = NO_EVENT
self.export.diagnostics_point(diag_data)


Expand All @@ -671,8 +681,6 @@ cdef class FMIODE2(cExplicit_Problem):
ret_flag = 0
if enter_event_mode:
self._logg_step_event += [solver.t]
# Event have been detect, call event iteration.
self.handle_event(solver,[0])
ret_flag = 1 # Tell to reinitiate the solver.

if self._synchronize_factor > 0:
Expand Down
14 changes: 9 additions & 5 deletions src/pyfmi/simulation/assimulo_interface_fmi3.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ from pyfmi.fmi3 import (
FMI3_Type,
FMI3_Variability
)
from pyfmi.common.diagnostics import EventType
from pyfmi.exceptions import (
FMUException,
InvalidOptionException,
Expand All @@ -49,6 +50,9 @@ from pyfmi.exceptions import (
from assimulo.problem cimport cExplicit_Problem
from assimulo.exception import AssimuloRecoverableError, TerminateSimulation

# Stored on every solver step, so held as a C double.
cdef double NO_EVENT = EventType.NO_EVENT

cdef class FMIODE3(cExplicit_Problem):
""" An Assimulo Explicit Model extended to FMI3 interface. """

Expand Down Expand Up @@ -394,6 +398,8 @@ cdef class FMIODE3(cExplicit_Problem):
def handle_event(self, solver, event_info):
""" This method is called when Assimulo finds an event. """
cdef FMIL3.fmi3_status_t status
# A state or time event in the same step takes precedence.
cdef bint step_event = event_info[2] and not event_info[1] and not any(event_info[0])

if self._extra_f_nbr > 0:
y_extra = solver.y[-self._extra_f_nbr:]
Expand Down Expand Up @@ -444,13 +450,13 @@ cdef class FMIODE3(cExplicit_Problem):
while index < self._number_of_diagnostics_variables - 1:
diag_data[index] = 0
index +=1
diag_data[index] = 1.0
diag_data[index] = EventType.TIME_EVENT
index +=1
else:
for ei in event_info[0]:
diag_data[index] = ei
index +=1
diag_data[index] = 0.0
diag_data[index] = EventType.STEP_EVENT if step_event else EventType.STATE_EVENT
index +=1
if index != self._number_of_diagnostics_variables:
raise FMUException("Failed logging diagnostics, number of data points expected to be {} but was {}".format(self._number_of_diagnostics_variables, index))
Expand Down Expand Up @@ -533,7 +539,7 @@ cdef class FMIODE3(cExplicit_Problem):
diag_data[index] = 0
index +=1
if support_event_indicators:
diag_data[index] = float(-1)
diag_data[index] = NO_EVENT
self.export.diagnostics_point(diag_data)


Expand All @@ -546,8 +552,6 @@ cdef class FMIODE3(cExplicit_Problem):
ret_flag = 0
if enter_event_mode:
self._logg_step_event += [solver.t]
# Event have been detect, call event iteration.
self.handle_event(solver,[0])
ret_flag = 1 # Tell to reinitiate the solver.

if self._synchronize_factor > 0:
Expand Down
Loading
Loading