diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b016d882..76aa429b 100755 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -9,10 +9,15 @@ jobs: linux: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + - uses: actions/setup-python@v4 + with: + python-version: '3.11.x' + - name: Setup Python + run: | + python3 -m pip install Cython numpy scipy matplotlib nose-py3 - name: Install system run: | - sudo apt-get -y install python3-scipy python3-setuptools python3-nose cython3 python3-matplotlib sudo apt-get -y install cmake liblapack-dev libsuitesparse-dev libhypre-dev sudo cp -v /usr/lib/x86_64-linux-gnu/libblas.so /usr/lib/x86_64-linux-gnu/libblas_OPENMP.so - name: Install superlu @@ -35,9 +40,8 @@ jobs: sudo make install - name: Install assimulo run: | - cd /tmp - curl -fSsL https://github.com/modelon-community/Assimulo/archive/Assimulo-3.4.1.tar.gz | tar xz - cd Assimulo-Assimulo-3.4.1 + git clone --depth 1 -b dev-pm-python_upgrade https://github.com/modelon-community/Assimulo /tmp/Assimulo + cd /tmp/Assimulo python3 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 --extra-fortran-compile-flags="-fallow-argument-mismatch" - name: Install fmilib run: | @@ -55,5 +59,4 @@ jobs: run: | rm src/pyfmi/__init__.py cp -rv src/pyfmi/tests/files tests - nosetests3 tests - + python3 -m nose --verbose tests/* diff --git a/CHANGELOG b/CHANGELOG index 8f876710..643fa023 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,7 @@ --- PyFMI-NEXT_VERSION --- * Removed utilities related to the obsolete FMUX model interface. * Removed no longer required dependency on lxml. + * Upgraded to Cython3. --- PyFMI-2.11.0 --- * Refactored result handling for dynamic_diagnostics. It is now possible use dynamic_diagnostics with a custom result handler. diff --git a/setup.cfg b/setup.cfg index c4a18de3..ae02d747 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,13 +1,13 @@ [options] setup_requires = setuptools - numpy >= 1.17 - cython >= 0.29.13 + numpy >= 1.26.3 + cython >= 3.0 install_requires = - numpy >= 1.17 - scipy >= 1.3 - cython >= 0.29.13 - nose >= 1.3.7 + numpy >= 1.26.3 + scipy >= 1.11.4 + cython >= 3.0.7 + nose-py3 >= 1.6.3 matplotlib > 3 - assimulo >= 3.2 \ No newline at end of file + assimulo >= 3.5.0 diff --git a/setup.py b/setup.py index 7e0e7483..99ece78b 100644 --- a/setup.py +++ b/setup.py @@ -33,13 +33,13 @@ from Cython.Distutils import build_ext from Cython.Build import cythonize except ImportError: - raise Exception("Please upgrade to a newer Cython version, >= 0.15.") + raise Exception("Please upgrade to a newer Cython version, >= 3.") NAME = "PyFMI" AUTHOR = "Modelon AB" AUTHOR_EMAIL = "" -VERSION = "3.0-dev" +VERSION = "2.12.0" LICENSE = "LGPL" URL = "https://github.com/modelon-community/PyFMI" DOWNLOAD_URL = "https://github.com/modelon-community/PyFMI/releases" @@ -73,7 +73,7 @@ ------------- - `FMI Library (at least 2.0.1) `_ - `Python-headers (usually included on Windows, python-dev on Ubuntu)`_ -- `Python 3.7 or newer`_ +- `Python 3.11 or newer`_ - Python package dependencies are listed in file setup.cfg. Optional @@ -90,9 +90,10 @@ copy_args = sys.argv[1:] -if os.getenv("FMIL_HOME"): #Check for if there exists and environment variable that specifies FMIL - incdirs = os.path.join(os.getenv("FMIL_HOME"), 'include') - libdirs = os.path.join(os.getenv("FMIL_HOME"), 'lib') +fmil_home = os.getenv("FMIL_HOME") +if fmil_home: #Check for environment variable that specifies FMIL + incdirs = os.path.join(fmil_home, 'include') + libdirs = os.path.join(fmil_home, 'lib') else: incdirs = "" libdirs = "" @@ -153,7 +154,6 @@ debug_flag = False copy_args.remove(x) - if not incdirs: raise Exception("FMI Library cannot be found. Please specify its location, either using the flag to the setup script '--fmil-home' or specify it using the environment variable FMIL_HOME.") @@ -214,29 +214,35 @@ def check_extensions(): incl_path = [".", "src", os.path.join("src", "pyfmi")] #FMI PYX ext_list += cythonize([os.path.join("src", "pyfmi", "fmi.pyx")], - include_path = incl_path) + include_path = incl_path, + compiler_directives={'language_level' : "3str"}) #FMI UTIL ext_list += cythonize([os.path.join("src", "pyfmi", "fmi_util.pyx")], - include_path = incl_path) + include_path = incl_path, + compiler_directives={'language_level' : "3str"}) #FMI Extended PYX ext_list += cythonize([os.path.join("src", "pyfmi", "fmi_extended.pyx")], - include_path = incl_path) + include_path = incl_path, + compiler_directives={'language_level' : "3str"}) #FMI Coupled PYX ext_list += cythonize([os.path.join("src", "pyfmi", "fmi_coupled.pyx")], - include_path = incl_path) + include_path = incl_path, + compiler_directives={'language_level' : "3str"}) #Simulation interface PYX ext_list += cythonize([os.path.join("src", "pyfmi", "simulation", "assimulo_interface.pyx")], - include_path = incl_path) + include_path = incl_path, + compiler_directives={'language_level' : "3str"}) #MASTER PYX compile_time_env = {'WITH_OPENMP': with_openmp} ext_list += cythonize([os.path.join("src", "pyfmi", "master.pyx")], include_path = incl_path, - compile_time_env=compile_time_env) + compile_time_env=compile_time_env, + compiler_directives={'language_level' : "3str"}) for i in range(len(ext_list)): diff --git a/src/common/core.py b/src/common/core.py index c8dfcae3..b391d56e 100644 --- a/src/common/core.py +++ b/src/common/core.py @@ -149,7 +149,7 @@ def _exec_algorithm(self, module, algorithm, options): Exception if algorithm is not a subclass of common.algorithm_drivers.AlgorithmBase. """ - from .algorithm_drivers import AlgorithmBase + from pyfmi.algorithm_drivers import AlgorithmBase if isinstance(algorithm, str): module = __import__(module, globals(), locals(), [algorithm], 0) @@ -182,7 +182,7 @@ def _exec_simulate_algorithm(self, Exception if algorithm is not a subclass of common.algorithm_drivers.AlgorithmBase. """ - from .algorithm_drivers import AlgorithmBase + from pyfmi.algorithm_drivers import AlgorithmBase if isinstance(algorithm, str): module = __import__(module, globals(), locals(), [algorithm], 0) diff --git a/src/common/io.py b/src/common/io.py index c0eb2538..736f786f 100644 --- a/src/common/io.py +++ b/src/common/io.py @@ -370,20 +370,20 @@ class ResultWriter(): Base class for writing results to file. """ - def write_header(): + def write_header(self): """ The header is intended to be used for writing general information about the model. This is intended to be called once. """ pass - def write_point(): + def write_point(self): """ This method does the writing of the actual result. """ pass - def write_finalize(): + def write_finalize(self): """ The finalize method can be used to for instance close the file. """ diff --git a/src/common/log/__init__.py b/src/common/log/__init__.py index bdc25805..d1e16cee 100644 --- a/src/common/log/__init__.py +++ b/src/common/log/__init__.py @@ -19,7 +19,7 @@ The log analysis toolkit. """ -from .parser import parse_xml_log, parse_xml_log, extract_xml_log, parse_fmu_xml_log -from .prettyprinter import prettyprint_to_file +from pyfmi.common.log.parser import parse_xml_log, parse_xml_log, extract_xml_log, parse_fmu_xml_log +from pyfmi.common.log.prettyprinter import prettyprint_to_file __all__=['parser','tree','prettyprinter'] diff --git a/src/common/log/parser.py b/src/common/log/parser.py index 18eba0ca..b2a8627e 100644 --- a/src/common/log/parser.py +++ b/src/common/log/parser.py @@ -23,7 +23,7 @@ import os import numpy as np from distutils.util import strtobool -from .tree import * +from pyfmi.common.log.tree import * from pyfmi.fmi_util import python3_flag from pyfmi.fmi import FMUException diff --git a/src/common/log/prettyprinter.py b/src/common/log/prettyprinter.py index 66d9774d..ac463772 100644 --- a/src/common/log/prettyprinter.py +++ b/src/common/log/prettyprinter.py @@ -19,7 +19,7 @@ """ from numpy import ndarray -from .tree import * +from pyfmi.common.log.tree import * def prettyprint(write, node): """Prettyprint a log node to the write callback write.""" diff --git a/src/pyfmi/__init__.py b/src/pyfmi/__init__.py index 6dee1238..05b87784 100644 --- a/src/pyfmi/__init__.py +++ b/src/pyfmi/__init__.py @@ -21,11 +21,11 @@ __all__ = ['fmi_algorithm_drivers', 'examples', 'fmi', 'common'] #Import the model class allowing for users to type e.g.,: from pyfmi import FMUModelME1 -from .fmi import load_fmu, FMUModelME1, FMUModelME2 -from .fmi import FMUModelCS1, FMUModelCS2 -from .fmi_coupled import CoupledFMUModelME2 -from .master import Master -from .fmi_extended import FMUModelME1Extended +from pyfmi.fmi import load_fmu, FMUModelME1, FMUModelME2 +from pyfmi.fmi import FMUModelCS1, FMUModelCS2 +from pyfmi.fmi_coupled import CoupledFMUModelME2 +from pyfmi.master import Master +from pyfmi.fmi_extended import FMUModelME1Extended import numpy as N import os.path import sys @@ -49,7 +49,7 @@ def wrap(func): try: - curr_dir = os.path.dirname(os.path.abspath(__file__)); + curr_dir = os.path.dirname(os.path.abspath(__file__)) _fpath=os.path.join(curr_dir,'version.txt') with open(_fpath, 'r') as f: __version__=f.readline().strip() @@ -178,5 +178,3 @@ def check_packages(): This package is needed to be able to use the plot-GUI.") sys.stdout.write("\n\n") - - diff --git a/src/pyfmi/fmi.pxd b/src/pyfmi/fmi.pxd index 0296ff2c..b4caf933 100644 --- a/src/pyfmi/fmi.pxd +++ b/src/pyfmi/fmi.pxd @@ -29,7 +29,7 @@ cimport numpy as N N.import_array() -cimport fmil_import as FMIL +cimport pyfmi.fmil_import as FMIL cdef FMIL.fmi_version_enu_t import_and_get_version(FMIL.fmi_import_context_t*, char*, char*, int) @@ -116,7 +116,7 @@ cdef class FMUModelBase(ModelBase): cdef FMIL.jm_callbacks* callbacks_standard #Internal values - cdef public object __t + cdef public object _t cdef public object _file_open cdef public object _npoints cdef public object _enable_logging @@ -158,10 +158,11 @@ cdef class FMUModelME1(FMUModelBase): cpdef _get_time(self) cpdef _set_time(self, FMIL.fmi1_real_t t) cpdef get_derivatives(self) - cdef int __get_nominal_continuous_states(self, FMIL.fmi1_real_t* xnominal, size_t nx) + cdef int _get_nominal_continuous_states_fmil(self, FMIL.fmi1_real_t* xnominal, size_t nx) cdef public object _preinit_nominal_continuous_states -cdef class __ForTestingFMUModelME1(FMUModelME1): +cdef class _ForTestingFMUModelME1(FMUModelME1): + cdef int _get_nominal_continuous_states_fmil(self, FMIL.fmi1_real_t* xnominal, size_t nx) cpdef set_allocated_fmu(self, int value) cdef class FMUModelBase2(ModelBase): @@ -190,7 +191,7 @@ cdef class FMUModelBase2(ModelBase): cdef public list _save_real_variables_val cdef public list _save_int_variables_val cdef public list _save_bool_variables_val - cdef object __t + cdef object _t cdef public object _pyEventInfo cdef char* _fmu_temp_dir cdef object _states_references @@ -206,7 +207,7 @@ cdef class FMUModelBase2(ModelBase): cdef object _outputs_states_dependencies_kind cdef object _outputs_inputs_dependencies_kind cdef object _A, _B, _C, _D - cdef public object _group_A, _group_B, _group_C, _group_D + cdef public object _group_A, _group_B, _group_C, _group_D cdef object _mask_A cdef object _A_row_ind, _A_col_ind cdef public object _has_entered_init_mode @@ -234,9 +235,9 @@ cdef class FMUModelBase2(ModelBase): cdef int _get_directional_derivative(self, N.ndarray v_ref, N.ndarray z_ref, N.ndarray dv, N.ndarray dz) except -1 cpdef set_real(self, valueref, values) cpdef N.ndarray get_real(self, valueref) - cdef int __set_real(self, FMIL.fmi2_value_reference_t* vrefs, FMIL.fmi2_real_t* values, size_t size) - cdef int __get_real(self, FMIL.fmi2_value_reference_t* vrefs, size_t size, FMIL.fmi2_real_t* values) - cdef int _get_real(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_real_t[:] values) + cdef int _set_real(self, FMIL.fmi2_value_reference_t* vrefs, FMIL.fmi2_real_t* values, size_t size) + cdef int _get_real_by_ptr(self, FMIL.fmi2_value_reference_t* vrefs, size_t size, FMIL.fmi2_real_t* values) + cdef int _get_real_by_list(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_real_t[:] values) cdef int _get_integer(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_integer_t[:] values) cdef int _get_boolean(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_real_t[:] values) @@ -255,11 +256,11 @@ cdef class FMUModelME2(FMUModelBase2): cpdef get_derivatives(self) cdef public object force_finite_differences cdef int _get_derivatives(self, FMIL.fmi2_real_t[:] values) - cdef int __get_continuous_states(self, FMIL.fmi2_real_t[:] ndx) - cdef int __set_continuous_states(self, FMIL.fmi2_real_t[:] ndx) + cdef int _get_continuous_states_fmil(self, FMIL.fmi2_real_t[:] ndx) + cdef int _set_continuous_states_fmil(self, FMIL.fmi2_real_t[:] ndx) cdef int _get_event_indicators(self, FMIL.fmi2_real_t[:] values) cdef int _completed_integrator_step(self, int* enter_event_mode, int* terminate_simulation) - cdef int __get_nominal_continuous_states(self, FMIL.fmi2_real_t* xnominal, size_t nx) + cdef int _get_nominal_continuous_states_fmil(self, FMIL.fmi2_real_t* xnominal, size_t nx) cdef public object _preinit_nominal_continuous_states cdef class WorkerClass2: @@ -274,5 +275,11 @@ cdef class WorkerClass2: cdef N.ndarray get_real_numpy_vector(self, int index) cpdef verify_dimensions(self, int dim) -cdef class __ForTestingFMUModelME2(FMUModelME2): +cdef class _ForTestingFMUModelME2(FMUModelME2): + cdef int _get_real_by_ptr(self, FMIL.fmi2_value_reference_t* vrefs, size_t size, FMIL.fmi2_real_t* values) + cdef int _set_real(self, FMIL.fmi2_value_reference_t* vrefs, FMIL.fmi2_real_t* values, size_t size) + cdef int _get_real_by_list(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_real_t[:] values) + cdef int _get_integer(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_integer_t[:] values) + cdef int _get_boolean(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_real_t[:] values) + cdef int _get_nominal_continuous_states_fmil(self, FMIL.fmi2_real_t* xnominal, size_t nx) cpdef set_initialized_fmu(self, int value) diff --git a/src/pyfmi/fmi.pyx b/src/pyfmi/fmi.pyx index f4de45d8..6b704617 100644 --- a/src/pyfmi/fmi.pyx +++ b/src/pyfmi/fmi.pyx @@ -14,6 +14,9 @@ # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . + +# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION + """ Module containing the FMI interface Python wrappers. """ @@ -37,15 +40,11 @@ import numpy as N cimport numpy as N from numpy cimport PyArray_DATA -N.import_array() - -cimport fmil_import as FMIL +cimport pyfmi.fmil_import as FMIL from pyfmi.common.core import create_temp_dir, delete_temp_dir from pyfmi.common.core import create_temp_file, delete_temp_file -#from pyfmi.common.core cimport BaseModel -#from pyfmi.common import python3_flag, encode, decode from pyfmi.fmi_util import cpr_seed, enable_caching, python3_flag from pyfmi.fmi_util cimport encode, decode @@ -1446,7 +1445,7 @@ cdef class FMUModelBase(ModelBase): FMI_REGISTER_GLOBALLY += 1 #Update the global register of FMUs #Default values - self.__t = None + self._t = None #Internal values self._file_open = False @@ -1545,9 +1544,8 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiGetReal """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, copy=False, dtype=N.uint32).ravel() - nref = val_ref.size + cdef FMIL.size_t nref = N.size(val_ref) cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = N.array([0.0]*nref, dtype=float, ndmin=1) if nref == 0: ## get_real([]) @@ -1579,12 +1577,11 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiSetReal """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, copy=False, dtype=N.uint32).ravel() cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = N.array(values, copy=False, dtype=float).ravel() - nref = val_ref.size + cdef FMIL.size_t nref = N.size(val_ref) - if val_ref.size != val.size: + if nref != N.size(val): raise FMUException( 'The length of valueref and values are inconsistent.') @@ -1614,9 +1611,8 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiGetInteger """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - nref = val_ref.size + cdef FMIL.size_t nref = N.size(val_ref) cdef N.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] val = N.array([0]*nref, dtype=int,ndmin=1) if nref == 0: ## get_integer([]) @@ -1648,13 +1644,11 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiSetInteger """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() cdef N.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] val = N.array(values, dtype=int,ndmin=1).ravel() + cdef FMIL.size_t nref = N.size(val_ref) - nref = val_ref.size - - if val_ref.size != val.size: + if nref != N.size(val): raise FMUException( 'The length of valueref and values are inconsistent.') @@ -1685,9 +1679,8 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiGetBoolean """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - nref = val_ref.size + cdef FMIL.size_t nref = N.size(val_ref) if nref == 0: ## get_boolean([]) return N.array([]) @@ -1727,10 +1720,8 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiSetBoolean """ cdef int status - cdef FMIL.size_t nref - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - nref = val_ref.size + cdef FMIL.size_t nref = N.size(val_ref) cdef void *val = FMIL.malloc(sizeof(FMIL.fmi1_boolean_t)*nref) @@ -1741,7 +1732,7 @@ cdef class FMUModelBase(ModelBase): else: (val)[i] = 0 - if val_ref.size != values.size: + if nref != N.size(values): raise FMUException( 'The length of valueref and values are inconsistent.') @@ -1773,9 +1764,8 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiGetString """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1, mode='c'] input_valueref = N.array(valueref, dtype=N.uint32, ndmin=1).ravel() - nref = input_valueref.size + cdef FMIL.size_t nref = N.size(input_valueref) if nref == 0: ## get_string([]) return [] @@ -1814,20 +1804,20 @@ cdef class FMUModelBase(ModelBase): """ cdef int status cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef FMIL.fmi1_string_t* val = FMIL.malloc(sizeof(FMIL.fmi1_string_t)*val_ref.size) + cdef FMIL.fmi1_string_t* val = FMIL.malloc(sizeof(FMIL.fmi1_string_t)*N.size(val_ref)) if not isinstance(values, list): raise FMUException( 'The values needs to be a list of values.') - if len(values) != val_ref.size: + if len(values) != N.size(val_ref): raise FMUException( 'The length of valueref and values are inconsistent.') values = [encode(item) for item in values] - for i in range(val_ref.size): + for i in range(N.size(val_ref)): val[i] = values[i] - status = FMIL.fmi1_import_set_string(self._fmu, val_ref.data, val_ref.size, val) + status = FMIL.fmi1_import_set_string(self._fmu, val_ref.data, N.size(val_ref), val) FMIL.free(val) @@ -1870,7 +1860,7 @@ cdef class FMUModelBase(ModelBase): Helper method to set, see docstring on set. """ cdef FMIL.fmi1_value_reference_t ref - cdef FMIL.fmi1_base_type_enu_t type + cdef FMIL.fmi1_base_type_enu_t basetype cdef FMIL.fmi1_import_variable_t* variable cdef FMIL.fmi1_variable_alias_kind_enu_t alias_kind @@ -1882,20 +1872,20 @@ cdef class FMUModelBase(ModelBase): raise FMUException("The variable %s could not be found."%variable_name) ref = FMIL.fmi1_import_get_variable_vr(variable) - type = FMIL.fmi1_import_get_variable_base_type(variable) + basetype = FMIL.fmi1_import_get_variable_base_type(variable) alias_kind = FMIL.fmi1_import_get_variable_alias_kind(variable) - if type == FMIL.fmi1_base_type_real: #REAL + if basetype == FMIL.fmi1_base_type_real: #REAL if alias_kind == FMI_NEGATED_ALIAS: value = -value self.set_real([ref], [value]) - elif type == FMIL.fmi1_base_type_int or type == FMIL.fmi1_base_type_enum: #INTEGER + elif basetype == FMIL.fmi1_base_type_int or basetype == FMIL.fmi1_base_type_enum: #INTEGER if alias_kind == FMI_NEGATED_ALIAS: value = -value self.set_integer([ref], [value]) - elif type == FMIL.fmi1_base_type_str: #STRING + elif basetype == FMIL.fmi1_base_type_str: #STRING self.set_string([ref], [value]) - elif type == FMIL.fmi1_base_type_bool: #BOOLEAN + elif basetype == FMIL.fmi1_base_type_bool: #BOOLEAN if alias_kind == FMI_NEGATED_ALIAS: value = not value self.set_boolean([ref], [value]) @@ -1908,7 +1898,7 @@ cdef class FMUModelBase(ModelBase): Helper method to get, see docstring on get. """ cdef FMIL.fmi1_value_reference_t ref - cdef FMIL.fmi1_base_type_enu_t type + cdef FMIL.fmi1_base_type_enu_t basetype cdef FMIL.fmi1_import_variable_t* variable cdef FMIL.fmi1_variable_alias_kind_enu_t alias_kind @@ -1920,18 +1910,18 @@ cdef class FMUModelBase(ModelBase): raise FMUException("The variable %s could not be found."%variable_name) ref = FMIL.fmi1_import_get_variable_vr(variable) - type = FMIL.fmi1_import_get_variable_base_type(variable) + basetype = FMIL.fmi1_import_get_variable_base_type(variable) alias_kind = FMIL.fmi1_import_get_variable_alias_kind(variable) - if type == FMIL.fmi1_base_type_real: #REAL + if basetype == FMIL.fmi1_base_type_real: #REAL value = self.get_real([ref]) return -1*value if alias_kind == FMI_NEGATED_ALIAS else value - elif type == FMIL.fmi1_base_type_int or type == FMIL.fmi1_base_type_enum: #INTEGER + elif basetype == FMIL.fmi1_base_type_int or basetype == FMIL.fmi1_base_type_enum: #INTEGER value = self.get_integer([ref]) return -1*value if alias_kind == FMI_NEGATED_ALIAS else value - elif type == FMIL.fmi1_base_type_str: #STRING + elif basetype == FMIL.fmi1_base_type_str: #STRING return self.get_string([ref]) - elif type == FMIL.fmi1_base_type_bool: #BOOLEAN + elif basetype == FMIL.fmi1_base_type_bool: #BOOLEAN value = self.get_boolean([ref]) return not value if alias_kind == FMI_NEGATED_ALIAS else value else: @@ -2019,7 +2009,7 @@ cdef class FMUModelBase(ModelBase): The type of the variable. """ cdef FMIL.fmi1_import_variable_t* variable - cdef FMIL.fmi1_base_type_enu_t type + cdef FMIL.fmi1_base_type_enu_t basetype variable_name = encode(variable_name) cdef char* variablename = variable_name @@ -2028,9 +2018,9 @@ cdef class FMUModelBase(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi1_import_get_variable_base_type(variable) + basetype = FMIL.fmi1_import_get_variable_base_type(variable) - return type + return basetype cpdef FMIL.fmi1_value_reference_t get_variable_valueref(self, variable_name) except *: """ @@ -2170,7 +2160,7 @@ cdef class FMUModelBase(ModelBase): cdef FMIL.fmi1_import_bool_variable_t* bool_variable cdef FMIL.fmi1_import_enum_variable_t* enum_variable cdef FMIL.fmi1_import_string_variable_t* str_variable - cdef FMIL.fmi1_base_type_enu_t type + cdef FMIL.fmi1_base_type_enu_t basetype cdef int status cdef FMIL.fmi1_boolean_t FMITRUE = 1 @@ -2186,25 +2176,25 @@ cdef class FMUModelBase(ModelBase): if status == 0: raise FMUException("The variable %s does not have a start value."%variablename) - type = FMIL.fmi1_import_get_variable_base_type(variable) + basetype = FMIL.fmi1_import_get_variable_base_type(variable) - if type == FMIL.fmi1_base_type_real: + if basetype == FMIL.fmi1_base_type_real: real_variable = FMIL.fmi1_import_get_variable_as_real(variable) return FMIL.fmi1_import_get_real_variable_start(real_variable) - elif type == FMIL.fmi1_base_type_int: + elif basetype == FMIL.fmi1_base_type_int: int_variable = FMIL.fmi1_import_get_variable_as_integer(variable) return FMIL.fmi1_import_get_integer_variable_start(int_variable) - elif type == FMIL.fmi1_base_type_bool: + elif basetype == FMIL.fmi1_base_type_bool: bool_variable = FMIL.fmi1_import_get_variable_as_boolean(variable) return FMIL.fmi1_import_get_boolean_variable_start(bool_variable) == FMITRUE - elif type == FMIL.fmi1_base_type_enum: + elif basetype == FMIL.fmi1_base_type_enum: enum_variable = FMIL.fmi1_import_get_variable_as_enum(variable) return FMIL.fmi1_import_get_enum_variable_start(enum_variable) - elif type == FMIL.fmi1_base_type_str: + elif basetype == FMIL.fmi1_base_type_str: str_variable = FMIL.fmi1_import_get_variable_as_string(variable) return FMIL.fmi1_import_get_string_variable_start(str_variable) @@ -2228,7 +2218,7 @@ cdef class FMUModelBase(ModelBase): cdef FMIL.fmi1_import_integer_variable_t* int_variable cdef FMIL.fmi1_import_real_variable_t* real_variable cdef FMIL.fmi1_import_enum_variable_t* enum_variable - cdef FMIL.fmi1_base_type_enu_t type + cdef FMIL.fmi1_base_type_enu_t basetype variable_name = encode(variable_name) cdef char* variablename = variable_name @@ -2237,17 +2227,17 @@ cdef class FMUModelBase(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi1_import_get_variable_base_type(variable) + basetype = FMIL.fmi1_import_get_variable_base_type(variable) - if type == FMIL.fmi1_base_type_real: + if basetype == FMIL.fmi1_base_type_real: real_variable = FMIL.fmi1_import_get_variable_as_real(variable) return FMIL.fmi1_import_get_real_variable_max(real_variable) - elif type == FMIL.fmi1_base_type_int: + elif basetype == FMIL.fmi1_base_type_int: int_variable = FMIL.fmi1_import_get_variable_as_integer(variable) return FMIL.fmi1_import_get_integer_variable_max(int_variable) - elif type == FMIL.fmi1_base_type_enum: + elif basetype == FMIL.fmi1_base_type_enum: enum_variable = FMIL.fmi1_import_get_variable_as_enum(variable) return FMIL.fmi1_import_get_enum_variable_max(enum_variable) @@ -2271,7 +2261,7 @@ cdef class FMUModelBase(ModelBase): cdef FMIL.fmi1_import_integer_variable_t* int_variable cdef FMIL.fmi1_import_real_variable_t* real_variable cdef FMIL.fmi1_import_enum_variable_t* enum_variable - cdef FMIL.fmi1_base_type_enu_t type + cdef FMIL.fmi1_base_type_enu_t basetype variable_name = encode(variable_name) cdef char* variablename = variable_name @@ -2280,17 +2270,17 @@ cdef class FMUModelBase(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi1_import_get_variable_base_type(variable) + basetype = FMIL.fmi1_import_get_variable_base_type(variable) - if type == FMIL.fmi1_base_type_real: + if basetype == FMIL.fmi1_base_type_real: real_variable = FMIL.fmi1_import_get_variable_as_real(variable) return FMIL.fmi1_import_get_real_variable_min(real_variable) - elif type == FMIL.fmi1_base_type_int: + elif basetype == FMIL.fmi1_base_type_int: int_variable = FMIL.fmi1_import_get_variable_as_integer(variable) return FMIL.fmi1_import_get_integer_variable_min(int_variable) - elif type == FMIL.fmi1_base_type_enum: + elif basetype == FMIL.fmi1_base_type_enum: enum_variable = FMIL.fmi1_import_get_variable_as_enum(variable) return FMIL.fmi1_import_get_enum_variable_min(enum_variable) @@ -2298,9 +2288,9 @@ cdef class FMUModelBase(ModelBase): raise FMUException("The variable type does not have a minimum value.") @enable_caching - def get_model_variables(self,type=None, int include_alias=True, - causality=None, variability=None, - int only_start=False, int only_fixed=False, + def get_model_variables(self, type=None, int include_alias=True, + causality=None, variability=None, + int only_start=False, int only_fixed=False, filter=None, int _as_list = False): """ Extract the names of the variables in a model. @@ -2790,10 +2780,10 @@ cdef class FMUModelCS1(FMUModelBase): GLOBAL_FMU_OBJECT = None cpdef _get_time(self): - return self.__t + return self._t cpdef _set_time(self, FMIL.fmi1_real_t t): - self.__t = t + self._t = t time = property(_get_time,_set_time, doc = """ @@ -2984,23 +2974,21 @@ cdef class FMUModelCS1(FMUModelBase): """ cdef int status cdef int can_interpolate_inputs - cdef FMIL.size_t nref cdef FMIL.fmi1_import_capabilities_t *fmu_capabilities cdef N.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] np_orders = N.array(orders, dtype=N.int32, ndmin=1).ravel() cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] value_refs cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = N.array(values, dtype=float, ndmin=1).ravel() - - nref = val.size + cdef FMIL.size_t nref = N.size(val) orders = N.array([0]*nref, dtype=N.int32) - if nref != np_orders.size: + if nref != N.size(np_orders): raise FMUException("The number of variables must be the same as the number of orders.") fmu_capabilities = FMIL.fmi1_import_get_capabilities(self._fmu) can_interpolate_inputs = FMIL.fmi1_import_get_canInterpolateInputs(fmu_capabilities) #NOTE IS THIS THE HIGHEST ORDER OF INTERPOLATION OR SIMPLY IF IT CAN OR NOT? - for i in range(np_orders.size): + for i in range(N.size(np_orders)): if np_orders[i] < 1: raise FMUException("The order must be greater than zero.") if not can_interpolate_inputs: @@ -3170,7 +3158,7 @@ cdef class FMUModelCS1(FMUModelBase): self._allocated_fmu = 0 #Default values - self.__t = None + self._t = None #Internal values self._file_open = False @@ -3350,7 +3338,7 @@ cdef class FMUModelME1(FMUModelBase): FMI_REGISTER_GLOBALLY += 1 #Update the global register of FMUs #Default values - self.__t = None + self._t = None #Internal values self._file_open = False @@ -3396,11 +3384,11 @@ cdef class FMUModelME1(FMUModelBase): self._log_stream = None cpdef _get_time(self): - return self.__t + return self._t cpdef _set_time(self, FMIL.fmi1_real_t t): cdef int status - self.__t = t + self._t = t status = FMIL.fmi1_import_set_time(self._fmu,t) @@ -3427,7 +3415,7 @@ cdef class FMUModelME1(FMUModelBase): cdef int status cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] ndx = values - if ndx.size != self._nContinuousStates: + if N.size(ndx) != self._nContinuousStates: raise FMUException( 'Failed to set the new continuous states. ' \ 'The number of values are not consistent with the number of '\ @@ -3446,7 +3434,7 @@ cdef class FMUModelME1(FMUModelBase): """) - cdef int __get_nominal_continuous_states(self, FMIL.fmi1_real_t* xnominal, size_t nx): + cdef int _get_nominal_continuous_states_fmil(self, FMIL.fmi1_real_t* xnominal, size_t nx): return FMIL.fmi1_import_get_nominal_continuous_states(self._fmu, xnominal, nx) def _get_nominal_continuous_states(self): @@ -3459,7 +3447,7 @@ cdef class FMUModelME1(FMUModelBase): cdef int status cdef N.ndarray[FMIL.fmi1_real_t, ndim=1, mode='c'] xn = N.zeros(self._nContinuousStates, dtype=N.double) - status = self.__get_nominal_continuous_states( xn.data, self._nContinuousStates) + status = self._get_nominal_continuous_states_fmil( xn.data, self._nContinuousStates) if status != 0: raise FMUException('Failed to get the nominal values.') @@ -3956,9 +3944,9 @@ cdef class FMUModelME1(FMUModelBase): self._instantiated_fmu = 0 -cdef class __ForTestingFMUModelME1(FMUModelME1): +cdef class _ForTestingFMUModelME1(FMUModelME1): - cdef int __get_nominal_continuous_states(self, FMIL.fmi1_real_t* xnominal, size_t nx): + cdef int _get_nominal_continuous_states_fmil(self, FMIL.fmi1_real_t* xnominal, size_t nx): for i in range(nx): if self._allocated_fmu == 1: # If initialized # Set new values to test that atol gets auto-corrected. @@ -4040,7 +4028,7 @@ cdef class FMUModelBase2(ModelBase): self._allow_unzipped_fmu = 1 if allow_unzipped_fmu else 0 #Default values - self.__t = None + self._t = None self._A = None self._group_A = None self._mask_A = None @@ -4221,9 +4209,8 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2GetReal """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, copy=False, dtype=N.uint32).ravel() - nref = input_valueref.size + cdef FMIL.size_t nref = N.size(input_valueref) cdef N.ndarray[FMIL.fmi2_real_t, ndim=1,mode='c'] output_value = N.zeros(nref) if nref == 0: ## get_real([]) @@ -4259,21 +4246,21 @@ cdef class FMUModelBase2(ModelBase): cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, copy=False, dtype=N.uint32).ravel() cdef N.ndarray[FMIL.fmi2_real_t, ndim=1,mode='c'] set_value = N.array(values, copy=False, dtype=float).ravel() - if input_valueref.size != set_value.size: + if N.size(input_valueref) != N.size(set_value): raise FMUException('The length of valueref and values are inconsistent.') - status = FMIL.fmi2_import_set_real(self._fmu, input_valueref.data, input_valueref.size, set_value.data) + status = FMIL.fmi2_import_set_real(self._fmu, input_valueref.data, N.size(input_valueref), set_value.data) if status != 0: raise FMUException('Failed to set the Real values. See the log for possibly more information.') - cdef int _get_real(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_real_t[:] values): + cdef int _get_real_by_list(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_real_t[:] values): return FMIL.fmi2_import_get_real(self._fmu, &valueref[0], size, &values[0]) - cdef int __get_real(self, FMIL.fmi2_value_reference_t* vrefs, size_t size, FMIL.fmi2_real_t* values): + cdef int _get_real_by_ptr(self, FMIL.fmi2_value_reference_t* vrefs, size_t size, FMIL.fmi2_real_t* values): return FMIL.fmi2_import_get_real(self._fmu, vrefs, size, values) - cdef int __set_real(self, FMIL.fmi2_value_reference_t* vrefs, FMIL.fmi2_real_t* values, size_t size): + cdef int _set_real(self, FMIL.fmi2_value_reference_t* vrefs, FMIL.fmi2_real_t* values, size_t size): return FMIL.fmi2_import_set_real(self._fmu, vrefs, size, values) cdef int _get_integer(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_integer_t[:] values): @@ -4300,9 +4287,8 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2GetInteger """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - nref = input_valueref.size + cdef FMIL.size_t nref = N.size(input_valueref) cdef N.ndarray[FMIL.fmi2_integer_t, ndim=1,mode='c'] output_value = N.zeros(nref, dtype=int) if nref == 0: ## get_integer([]) @@ -4334,14 +4320,11 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2SetInteger """ cdef int status - cdef FMIL.size_t nref - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() cdef N.ndarray[FMIL.fmi2_integer_t, ndim=1,mode='c'] set_value = N.array(values, dtype=int,ndmin=1).ravel() + cdef FMIL.size_t nref = N.size(input_valueref) - nref = input_valueref.size - - if input_valueref.size != set_value.size: + if nref != N.size(set_value): raise FMUException('The length of valueref and values are inconsistent.') status = FMIL.fmi2_import_set_integer(self._fmu, input_valueref.data, nref, set_value.data) @@ -4383,9 +4366,8 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2GetBoolean """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, dtype=N.uint32, ndmin=1).ravel() - nref = input_valueref.size + cdef FMIL.size_t nref = N.size(input_valueref) if nref == 0: ## get_boolean([]) return N.array([]) @@ -4425,10 +4407,9 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2SetBoolean """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, dtype=N.uint32,ndmin=1).flatten() - nref = len(input_valueref) + cdef FMIL.size_t nref = N.size(input_valueref) cdef void* set_value = FMIL.malloc(sizeof(FMIL.fmi2_boolean_t)*nref) @@ -4470,9 +4451,8 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2GetString """ cdef int status - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] input_valueref = N.array(valueref, dtype=N.uint32, ndmin=1).ravel() - nref = input_valueref.size + cdef FMIL.size_t nref = N.size(input_valueref) if nref == 0: ## get_string([]) return [] @@ -4512,20 +4492,20 @@ cdef class FMUModelBase2(ModelBase): """ cdef int status cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef FMIL.fmi2_string_t* val = FMIL.malloc(sizeof(FMIL.fmi2_string_t)*val_ref.size) + cdef FMIL.fmi2_string_t* val = FMIL.malloc(sizeof(FMIL.fmi2_string_t)*N.size(val_ref)) if not isinstance(values, list): raise FMUException( 'The values needs to be a list of values.') - if len(values) != val_ref.size: + if len(values) != N.size(val_ref): raise FMUException( 'The length of valueref and values are inconsistent.') values = [encode(item) for item in values] - for i in range(val_ref.size): + for i in range(N.size(val_ref)): val[i] = values[i] - status = FMIL.fmi2_import_set_string(self._fmu, val_ref.data, val_ref.size, val) + status = FMIL.fmi2_import_set_string(self._fmu, val_ref.data, N.size(val_ref), val) FMIL.free(val) @@ -4537,16 +4517,16 @@ cdef class FMUModelBase2(ModelBase): Helper method to set, see docstring on set. """ cdef FMIL.fmi2_value_reference_t ref - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype ref = self.get_variable_valueref(variable_name) - type = self.get_variable_data_type(variable_name) + basetype = self.get_variable_data_type(variable_name) - if type == FMIL.fmi2_base_type_real: #REAL + if basetype == FMIL.fmi2_base_type_real: #REAL self.set_real([ref], [value]) - elif type == FMIL.fmi2_base_type_int: + elif basetype == FMIL.fmi2_base_type_int: self.set_integer([ref], [value]) - elif type == FMIL.fmi2_base_type_enum: + elif basetype == FMIL.fmi2_base_type_enum: if isinstance(value, str) or isinstance(value, bytes): enum_type = self.get_variable_declared_type(variable_name) enum_values = {encode(v[0]): k for k, v in enum_type.items.items()} @@ -4558,9 +4538,9 @@ cdef class FMUModelBase2(ModelBase): raise FMUException(msg) else: self.set_integer([ref], [value]) - elif type == FMIL.fmi2_base_type_str: #STRING + elif basetype == FMIL.fmi2_base_type_str: #STRING self.set_string([ref], [value]) - elif type == FMIL.fmi2_base_type_bool: #BOOLEAN + elif basetype == FMIL.fmi2_base_type_bool: #BOOLEAN self.set_boolean([ref], [value]) else: raise FMUException('Type not supported.') @@ -4570,18 +4550,18 @@ cdef class FMUModelBase2(ModelBase): Helper method to get, see docstring on get. """ cdef FMIL.fmi2_value_reference_t ref - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype ref = self.get_variable_valueref(variable_name) - type = self.get_variable_data_type(variable_name) + basetype = self.get_variable_data_type(variable_name) - if type == FMIL.fmi2_base_type_real: #REAL + if basetype == FMIL.fmi2_base_type_real: #REAL return self.get_real([ref]) - elif type == FMIL.fmi2_base_type_int or type == FMIL.fmi2_base_type_enum: #INTEGER + elif basetype == FMIL.fmi2_base_type_int or basetype == FMIL.fmi2_base_type_enum: #INTEGER return self.get_integer([ref]) - elif type == FMIL.fmi2_base_type_str: #STRING + elif basetype == FMIL.fmi2_base_type_str: #STRING return self.get_string([ref]) - elif type == FMIL.fmi2_base_type_bool: #BOOLEAN + elif basetype == FMIL.fmi2_base_type_bool: #BOOLEAN return self.get_boolean([ref]) else: raise FMUException('Type not supported.') @@ -4668,7 +4648,7 @@ cdef class FMUModelBase2(ModelBase): if stop_time == "Default": stop_time = self.get_default_experiment_stop_time() - self.__t = start_time + self._t = start_time self._last_accepted_time = start_time self._relative_tolerance = tolerance @@ -4690,7 +4670,7 @@ cdef class FMUModelBase2(ModelBase): raise FMUException('An error occured when reseting the model, see the log for possible more information') #Default values - self.__t = None + self._t = None self._has_entered_init_mode = False #Reseting the allocation flags @@ -5398,7 +5378,7 @@ cdef class FMUModelBase2(ModelBase): cdef FMIL.fmi2_import_variable_t* variable cdef FMIL.fmi2_value_reference_t vr cdef FMIL.fmi2_import_variable_typedef_t* variable_type - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype cdef FMIL.fmi2_import_enumeration_typedef_t * enumeration_type cdef FMIL.fmi2_import_integer_typedef_t * integer_type cdef FMIL.fmi2_import_real_typedef_t * real_type @@ -5430,9 +5410,9 @@ cdef class FMUModelBase2(ModelBase): type_desc = FMIL.fmi2_import_get_type_description(variable_type) type_quantity = FMIL.fmi2_import_get_type_quantity(variable_type) - type = FMIL.fmi2_import_get_variable_base_type(variable) + basetype = FMIL.fmi2_import_get_variable_base_type(variable) - if type == FMIL.fmi2_base_type_enum: + if basetype == FMIL.fmi2_base_type_enum: enumeration_type = FMIL.fmi2_import_get_type_as_enum(variable_type) enum_size = FMIL.fmi2_import_get_enum_type_size(enumeration_type) items = OrderedDict() @@ -5450,7 +5430,7 @@ cdef class FMUModelBase2(ModelBase): decode(type_quantity) if type_quantity != NULL else "", items) - elif type == FMIL.fmi2_base_type_int: + elif basetype == FMIL.fmi2_base_type_int: integer_type = FMIL.fmi2_import_get_type_as_int(variable_type) min_val = FMIL.fmi2_import_get_integer_type_min(integer_type) @@ -5460,7 +5440,7 @@ cdef class FMUModelBase2(ModelBase): decode(type_desc) if type_desc != NULL else "", decode(type_quantity) if type_quantity != NULL else "", min_val, max_val) - elif type == FMIL.fmi2_base_type_real: + elif basetype == FMIL.fmi2_base_type_real: real_type = FMIL.fmi2_import_get_type_as_real(variable_type) min_val = FMIL.fmi2_import_get_real_type_min(real_type) @@ -5523,7 +5503,7 @@ cdef class FMUModelBase2(ModelBase): The type of the variable. """ cdef FMIL.fmi2_import_variable_t* variable - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype variable_name = encode(variable_name) cdef char* variablename = variable_name @@ -5532,9 +5512,9 @@ cdef class FMUModelBase2(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi2_import_get_variable_base_type(variable) + basetype = FMIL.fmi2_import_get_variable_base_type(variable) - return type + return basetype cpdef get_variable_description(self, variable_name): """ @@ -5633,7 +5613,7 @@ cdef class FMUModelBase2(ModelBase): cdef FMIL.fmi2_import_variable_t* variable cdef FMIL.fmi2_import_real_variable_t* real_variable cdef FMIL.fmi2_import_unit_t* unit - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype cdef char* unit_description variable_name = encode(variable_name) @@ -5643,8 +5623,8 @@ cdef class FMUModelBase2(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi2_import_get_variable_base_type(variable) - if type != FMIL.fmi2_base_type_real: + basetype = FMIL.fmi2_import_get_variable_base_type(variable) + if basetype != FMIL.fmi2_base_type_real: raise FMUException("The variable %s is not a Real variable. Units only exists for Real variables."%variablename) real_variable = FMIL.fmi2_import_get_variable_as_real(variable) @@ -5672,7 +5652,7 @@ cdef class FMUModelBase2(ModelBase): """ cdef FMIL.fmi2_import_variable_t* variable cdef FMIL.fmi2_import_real_variable_t* real_variable - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype cdef FMIL.fmi2_boolean_t relative_quantity variable_name = encode(variable_name) @@ -5682,8 +5662,8 @@ cdef class FMUModelBase2(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi2_import_get_variable_base_type(variable) - if type != FMIL.fmi2_base_type_real: + basetype = FMIL.fmi2_import_get_variable_base_type(variable) + if basetype != FMIL.fmi2_base_type_real: raise FMUException("The variable %s is not a Real variable. Relative quantity only exists for Real variables."%variablename) real_variable = FMIL.fmi2_import_get_variable_as_real(variable) @@ -5706,7 +5686,7 @@ cdef class FMUModelBase2(ModelBase): """ cdef FMIL.fmi2_import_variable_t* variable cdef FMIL.fmi2_import_real_variable_t* real_variable - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype cdef FMIL.fmi2_boolean_t unbounded variable_name = encode(variable_name) @@ -5716,8 +5696,8 @@ cdef class FMUModelBase2(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi2_import_get_variable_base_type(variable) - if type != FMIL.fmi2_base_type_real: + basetype = FMIL.fmi2_import_get_variable_base_type(variable) + if basetype != FMIL.fmi2_base_type_real: raise FMUException("The variable %s is not a Real variable. Unbounded attribute only exists for Real variables."%variablename) real_variable = FMIL.fmi2_import_get_variable_as_real(variable) @@ -5741,7 +5721,7 @@ cdef class FMUModelBase2(ModelBase): cdef FMIL.fmi2_import_variable_t* variable cdef FMIL.fmi2_import_real_variable_t* real_variable cdef FMIL.fmi2_import_display_unit_t* display_unit - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype cdef char* display_unit_description variable_name = encode(variable_name) @@ -5751,8 +5731,8 @@ cdef class FMUModelBase2(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi2_import_get_variable_base_type(variable) - if type != FMIL.fmi2_base_type_real: + basetype = FMIL.fmi2_import_get_variable_base_type(variable) + if basetype != FMIL.fmi2_base_type_real: raise FMUException("The variable %s is not a Real variable. Display units only exists for Real variables."%variablename) real_variable = FMIL.fmi2_import_get_variable_as_real(variable) @@ -5796,8 +5776,8 @@ cdef class FMUModelBase2(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi2_import_get_variable_base_type(variable) - if type != FMIL.fmi2_base_type_real: + basetype = FMIL.fmi2_import_get_variable_base_type(variable) + if basetype != FMIL.fmi2_base_type_real: raise FMUException("The variable %s is not a Real variable. Display units only exists for Real variables."%variablename) real_variable = FMIL.fmi2_import_get_variable_as_real(variable) @@ -5858,7 +5838,7 @@ cdef class FMUModelBase2(ModelBase): The start value. """ cdef FMIL.fmi2_import_variable_t * variable - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype cdef FMIL.fmi2_import_integer_variable_t* int_variable cdef FMIL.fmi2_import_real_variable_t* real_variable cdef FMIL.fmi2_import_bool_variable_t* bool_variable @@ -5879,25 +5859,25 @@ cdef class FMUModelBase2(ModelBase): if status == 0: raise FMUException("The variable %s does not have a start value."%variablename) - type = FMIL.fmi2_import_get_variable_base_type(variable) + basetype = FMIL.fmi2_import_get_variable_base_type(variable) - if type == FMIL.fmi2_base_type_real: + if basetype == FMIL.fmi2_base_type_real: real_variable = FMIL.fmi2_import_get_variable_as_real(variable) return FMIL.fmi2_import_get_real_variable_start(real_variable) - elif type == FMIL.fmi2_base_type_int: + elif basetype == FMIL.fmi2_base_type_int: int_variable = FMIL.fmi2_import_get_variable_as_integer(variable) return FMIL.fmi2_import_get_integer_variable_start(int_variable) - elif type == FMIL.fmi2_base_type_bool: + elif basetype == FMIL.fmi2_base_type_bool: bool_variable = FMIL.fmi2_import_get_variable_as_boolean(variable) return FMIL.fmi2_import_get_boolean_variable_start(bool_variable) == FMITRUE - elif type == FMIL.fmi2_base_type_enum: + elif basetype == FMIL.fmi2_base_type_enum: enum_variable = FMIL.fmi2_import_get_variable_as_enum(variable) return FMIL.fmi2_import_get_enum_variable_start(enum_variable) - elif type == FMIL.fmi2_base_type_str: + elif basetype == FMIL.fmi2_base_type_str: str_variable = FMIL.fmi2_import_get_variable_as_string(variable) return FMIL.fmi2_import_get_string_variable_start(str_variable) @@ -5921,7 +5901,7 @@ cdef class FMUModelBase2(ModelBase): cdef FMIL.fmi2_import_integer_variable_t* int_variable cdef FMIL.fmi2_import_real_variable_t* real_variable cdef FMIL.fmi2_import_enum_variable_t* enum_variable - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype variable_name = encode(variable_name) cdef char* variablename = variable_name @@ -5930,17 +5910,17 @@ cdef class FMUModelBase2(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi2_import_get_variable_base_type(variable) + basetype = FMIL.fmi2_import_get_variable_base_type(variable) - if type == FMIL.fmi2_base_type_real: + if basetype == FMIL.fmi2_base_type_real: real_variable = FMIL.fmi2_import_get_variable_as_real(variable) return FMIL.fmi2_import_get_real_variable_max(real_variable) - elif type == FMIL.fmi2_base_type_int: + elif basetype == FMIL.fmi2_base_type_int: int_variable = FMIL.fmi2_import_get_variable_as_integer(variable) return FMIL.fmi2_import_get_integer_variable_max(int_variable) - elif type == FMIL.fmi2_base_type_enum: + elif basetype == FMIL.fmi2_base_type_enum: enum_variable = FMIL.fmi2_import_get_variable_as_enum(variable) return FMIL.fmi2_import_get_enum_variable_max(enum_variable) @@ -5964,7 +5944,7 @@ cdef class FMUModelBase2(ModelBase): cdef FMIL.fmi2_import_integer_variable_t* int_variable cdef FMIL.fmi2_import_real_variable_t* real_variable cdef FMIL.fmi2_import_enum_variable_t* enum_variable - cdef FMIL.fmi2_base_type_enu_t type + cdef FMIL.fmi2_base_type_enu_t basetype variable_name = encode(variable_name) cdef char* variablename = variable_name @@ -5973,17 +5953,17 @@ cdef class FMUModelBase2(ModelBase): if variable == NULL: raise FMUException("The variable %s could not be found."%variablename) - type = FMIL.fmi2_import_get_variable_base_type(variable) + basetype = FMIL.fmi2_import_get_variable_base_type(variable) - if type == FMIL.fmi2_base_type_real: + if basetype == FMIL.fmi2_base_type_real: real_variable = FMIL.fmi2_import_get_variable_as_real(variable) return FMIL.fmi2_import_get_real_variable_min(real_variable) - elif type == FMIL.fmi2_base_type_int: + elif basetype == FMIL.fmi2_base_type_int: int_variable = FMIL.fmi2_import_get_variable_as_integer(variable) return FMIL.fmi2_import_get_integer_variable_min(int_variable) - elif type == FMIL.fmi2_base_type_enum: + elif basetype == FMIL.fmi2_base_type_enum: enum_variable = FMIL.fmi2_import_get_variable_as_enum(variable) return FMIL.fmi2_import_get_enum_variable_min(enum_variable) @@ -6894,14 +6874,14 @@ cdef class FMUModelBase2(ModelBase): N.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] dz) except -1: cdef int status - assert dv.size >= v_ref.size and dz.size >= z_ref.size + assert N.size(dv) >= N.size(v_ref) and N.size(dz) >= N.size(z_ref) if not self._provides_directional_derivatives(): raise FMUException('This FMU does not provide directional derivatives') status = FMIL.fmi2_import_get_directional_derivative(self._fmu, - v_ref.data, v_ref.size, - z_ref.data, z_ref.size, + v_ref.data, N.size(v_ref), + z_ref.data, N.size(z_ref), dv.data, dz.data) @@ -7115,7 +7095,7 @@ cdef class FMUModelCS2(FMUModelBase2): Returns:: The time. """ - return self.__t + return self._t cpdef _set_time(self, FMIL.fmi2_real_t t): """ @@ -7125,7 +7105,7 @@ cdef class FMUModelCS2(FMUModelBase2): t-- The time to set. """ - self.__t = t + self._t = t time = property(_get_time,_set_time, doc = """ @@ -7212,12 +7192,10 @@ cdef class FMUModelCS2(FMUModelBase2): """ cdef int status cdef unsigned int can_interpolate_inputs - cdef FMIL.size_t nref cdef N.ndarray[FMIL.fmi2_integer_t, ndim=1, mode='c'] orders cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] value_refs cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] val = N.array(values, dtype=float, ndmin=1).ravel() - - nref = val.size + cdef FMIL.size_t nref = N.size(val) orders = N.array([0]*nref, dtype=N.int32) can_interpolate_inputs = FMIL.fmi2_import_get_capability(self._fmu, FMIL.fmi2_cs_canInterpolateInputs) @@ -7251,11 +7229,11 @@ cdef class FMUModelCS2(FMUModelBase2): N.ndarray[FMIL.fmi2_integer_t, ndim=1, mode="c"] orders): cdef int status - assert values.size >= value_refs.size and orders.size >= value_refs.size + assert N.size(values) >= N.size(value_refs) and N.size(orders) >= N.size(value_refs) status = FMIL.fmi2_import_set_real_input_derivatives(self._fmu, value_refs.data, - value_refs.size, orders.data, + N.size(value_refs), orders.data, values.data) return status @@ -7322,10 +7300,10 @@ cdef class FMUModelCS2(FMUModelBase2): N.ndarray[FMIL.fmi2_integer_t, ndim=1, mode="c"] orders): cdef int status - assert values.size >= value_refs.size and orders.size >= value_refs.size + assert N.size(values) >= N.size(value_refs) and N.size(orders) >= N.size(value_refs) status = FMIL.fmi2_import_get_real_output_derivatives(self._fmu, - value_refs.data, value_refs.size, + value_refs.data, N.size(value_refs), orders.data, values.data) return status @@ -7746,7 +7724,7 @@ cdef class FMUModelME2(FMUModelBase2): Returns:: The time. """ - return self.__t + return self._t cpdef _set_time(self, FMIL.fmi2_real_t t): """ @@ -7762,7 +7740,7 @@ cdef class FMUModelME2(FMUModelBase2): if status != 0: raise FMUException('Failed to set the time.') - self.__t = t + self._t = t time = property(_get_time,_set_time, doc = """ @@ -8015,7 +7993,7 @@ cdef class FMUModelME2(FMUModelBase2): return enterEventMode==FMI2_TRUE, terminateSimulation==FMI2_TRUE - cdef int __get_continuous_states(self, FMIL.fmi2_real_t[:] ndx): + cdef int _get_continuous_states_fmil(self, FMIL.fmi2_real_t[:] ndx): if self._nContinuousStates > 0: return FMIL.fmi2_import_get_continuous_states(self._fmu, &ndx[0] ,self._nContinuousStates) else: @@ -8031,16 +8009,16 @@ cdef class FMUModelME2(FMUModelBase2): """ cdef int status cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] ndx = N.zeros(self._nContinuousStates, dtype=N.double) - status = self.__get_continuous_states(ndx) + status = self._get_continuous_states_fmil(ndx) if status != 0: raise FMUException('Failed to retrieve the continuous states.') return ndx - cdef int __set_continuous_states(self, FMIL.fmi2_real_t[:] ndx): + cdef int _set_continuous_states_fmil(self, FMIL.fmi2_real_t[:] ndx): if self._nContinuousStates > 0: - return FMIL.fmi2_import_set_continuous_states(self._fmu, &ndx[0] , self._nContinuousStates) + return FMIL.fmi2_import_set_continuous_states(self._fmu, &ndx[0], self._nContinuousStates) else: return FMIL.fmi2_status_ok @@ -8056,13 +8034,13 @@ cdef class FMUModelME2(FMUModelBase2): cdef int status cdef N.ndarray[FMIL.fmi2_real_t, ndim=1,mode='c'] ndx = values - if ndx.size != self._nContinuousStates: + if N.size(ndx) != self._nContinuousStates: raise FMUException( 'Failed to set the new continuous states. ' \ 'The number of values are not consistent with the number of '\ 'continuous states.') - status = self.__set_continuous_states(ndx) + status = self._set_continuous_states_fmil(ndx) if status >= 3: raise FMUException('Failed to set the new continuous states.') @@ -8074,7 +8052,7 @@ cdef class FMUModelME2(FMUModelBase2): the low-level FMI function: fmi2SetContinuousStates/fmi2GetContinuousStates. """) - cdef int __get_nominal_continuous_states(self, FMIL.fmi2_real_t* xnominal, size_t nx): + cdef int _get_nominal_continuous_states_fmil(self, FMIL.fmi2_real_t* xnominal, size_t nx): return FMIL.fmi2_import_get_nominals_of_continuous_states(self._fmu, xnominal, nx) def _get_nominal_continuous_states(self): @@ -8087,7 +8065,7 @@ cdef class FMUModelME2(FMUModelBase2): cdef int status cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] xn = N.zeros(self._nContinuousStates, dtype=N.double) - status = self.__get_nominal_continuous_states( xn.data, self._nContinuousStates) + status = self._get_nominal_continuous_states_fmil( xn.data, self._nContinuousStates) if status != 0: raise FMUException('Failed to get the nominal values.') @@ -8341,8 +8319,8 @@ cdef class FMUModelME2(FMUModelBase2): local_z_vref_pt = self._worker_object.get_value_reference_vector(1) #Get updated values for the derivatives and states - self.__get_real(z_ref_pt, len_f, df_pt) - self.__get_real(v_ref_pt, len_v, v_pt) + self._get_real_by_ptr(z_ref_pt, len_f, df_pt) + self._get_real_by_ptr(v_ref_pt, len_v, v_pt) if group is not None: if "nominals" in group: # Re-use extracted nominals @@ -8406,12 +8384,12 @@ cdef class FMUModelME2(FMUModelBase2): for fac in [1.0, 0.1, 0.01, 0.001]: #In very special cases, the epsilon is too big, if an error, try to reduce eps for i in range(local_indices_vars_nbr): tmp_val_pt[i] = v_pt[local_indices_vars_pt[i]]+fac*eps_pt[local_indices_vars_pt[i]] - self.__set_real(local_v_vref_pt, tmp_val_pt, local_indices_vars_nbr) + self._set_real(local_v_vref_pt, tmp_val_pt, local_indices_vars_nbr) if method == FORWARD_DIFFERENCE: #Forward and Backward difference column_data_pt = tmp_val_pt - status = self.__get_real(local_z_vref_pt, local_indices_matrix_rows_nbr, tmp_val_pt) + status = self._get_real_by_ptr(local_z_vref_pt, local_indices_matrix_rows_nbr, tmp_val_pt) if status == 0: for i in range(local_indices_matrix_rows_nbr): column_data_pt[i] = (tmp_val_pt[i] - df_pt[local_indices_matrix_rows_pt[i]])/(fac*eps_pt[local_indices_matrix_columns_pt[i]]) @@ -8420,9 +8398,9 @@ cdef class FMUModelME2(FMUModelBase2): else: #Backward for i in range(local_indices_vars_nbr): tmp_val_pt[i] = v_pt[local_indices_vars_pt[i]]-fac*eps_pt[local_indices_vars_pt[i]] - self.__set_real(local_v_vref_pt, tmp_val_pt, local_indices_vars_nbr) + self._set_real(local_v_vref_pt, tmp_val_pt, local_indices_vars_nbr) - status = self.__get_real(local_z_vref_pt, local_indices_matrix_rows_nbr, tmp_val_pt) + status = self._get_real_by_ptr(local_z_vref_pt, local_indices_matrix_rows_nbr, tmp_val_pt) if status == 0: for i in range(local_indices_matrix_rows_nbr): column_data_pt[i] = (df_pt[local_indices_matrix_rows_pt[i]] - tmp_val_pt[i])/(fac*eps_pt[local_indices_matrix_columns_pt[i]]) @@ -8433,7 +8411,7 @@ cdef class FMUModelME2(FMUModelBase2): dfpertp = self.get_real(z_ref[local_group[2]]) for i in range(local_indices_vars_nbr): tmp_val_pt[i] = v_pt[local_indices_vars_pt[i]]-fac*eps_pt[local_indices_vars_pt[i]] - self.__set_real(local_v_vref_pt, tmp_val_pt, local_indices_vars_nbr) + self._set_real(local_v_vref_pt, tmp_val_pt, local_indices_vars_nbr) dfpertm = self.get_real(z_ref[local_group[2]]) @@ -8457,7 +8435,7 @@ cdef class FMUModelME2(FMUModelBase2): col.extend(local_group[3]) 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) + self._set_real(local_v_vref_pt, tmp_val_pt, local_indices_vars_nbr) if output_matrix is not None: A = output_matrix @@ -8485,7 +8463,7 @@ cdef class FMUModelME2(FMUModelBase2): tmp = v_pt[i] for fac in [1.0, 0.1, 0.01, 0.001]: #In very special cases, the epsilon is too big, if an error, try to reduce eps v_pt[i] = tmp+fac*eps_pt[i] - self.__set_real(v_ref_pt, v_pt, len_v) + self._set_real(v_ref_pt, v_pt, len_v) if method == FORWARD_DIFFERENCE: #Forward and Backward difference try: @@ -8494,7 +8472,7 @@ cdef class FMUModelME2(FMUModelBase2): break except FMUException: #Try backward difference v_pt[i] = tmp - fac*eps_pt[i] - self.__set_real(v_ref_pt, v_pt, len_v) + self._set_real(v_ref_pt, v_pt, len_v) try: dfpert = self.get_real(z_ref) A[:, i] = (df - dfpert)/(fac*eps_pt[i]) @@ -8505,7 +8483,7 @@ cdef class FMUModelME2(FMUModelBase2): else: #Central difference dfpertp = self.get_real(z_ref) v_pt[i] = tmp - fac*eps_pt[i] - self.__set_real(v_ref_pt, v_pt, len_v) + self._set_real(v_ref_pt, v_pt, len_v) dfpertm = self.get_real(z_ref) A[:, i] = (dfpertp - dfpertm)/(2*fac*eps_pt[i]) break @@ -8514,12 +8492,12 @@ cdef class FMUModelME2(FMUModelBase2): #Reset values v_pt[i] = tmp - self.__set_real(v_ref_pt, v_pt, len_v) + self._set_real(v_ref_pt, v_pt, len_v) return A -cdef class __ForTestingFMUModelME2(FMUModelME2): - cdef int __get_real(self, FMIL.fmi2_value_reference_t* vrefs, size_t size, FMIL.fmi2_real_t* values): +cdef class _ForTestingFMUModelME2(FMUModelME2): + cdef int _get_real_by_ptr(self, FMIL.fmi2_value_reference_t* vrefs, size_t size, FMIL.fmi2_real_t* values): vr = N.zeros(size) for i in range(size): vr[i] = vrefs[i] @@ -8534,7 +8512,7 @@ cdef class __ForTestingFMUModelME2(FMUModelME2): return FMIL.fmi2_status_ok - cdef int __set_real(self, FMIL.fmi2_value_reference_t* vrefs, FMIL.fmi2_real_t* values, size_t size): + cdef int _set_real(self, FMIL.fmi2_value_reference_t* vrefs, FMIL.fmi2_real_t* values, size_t size): vr = N.zeros(size) vv = N.zeros(size) for i in range(size): @@ -8548,7 +8526,7 @@ cdef class __ForTestingFMUModelME2(FMUModelME2): return FMIL.fmi2_status_ok - cdef int _get_real(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_real_t[:] values): + cdef int _get_real_by_list(self, FMIL.fmi2_value_reference_t[:] valueref, size_t size, FMIL.fmi2_real_t[:] values): try: tmp = self.get_real(valueref) for i in range(size): @@ -8575,7 +8553,7 @@ cdef class __ForTestingFMUModelME2(FMUModelME2): return FMIL.fmi2_status_error return FMIL.fmi2_status_ok - cdef int __get_nominal_continuous_states(self, FMIL.fmi2_real_t* xnominal, size_t nx): + cdef int _get_nominal_continuous_states_fmil(self, FMIL.fmi2_real_t* xnominal, size_t nx): for i in range(nx): if self._initialized_fmu == 1: # Set new values to test that atol gets auto-corrected. diff --git a/src/pyfmi/fmi_algorithm_drivers.py b/src/pyfmi/fmi_algorithm_drivers.py index 923c8a01..d68065ab 100644 --- a/src/pyfmi/fmi_algorithm_drivers.py +++ b/src/pyfmi/fmi_algorithm_drivers.py @@ -666,7 +666,7 @@ def _set_absolute_tolerance_options(self): self.solver_options["atol"] = 0.01*self.rtol else: self.solver_options["atol"] = 0.01*self.rtol*self.model.nominal_continuous_states - elif isinstance(preinit_nominals, N.ndarray) and (preinit_nominals.size > 0): + elif isinstance(preinit_nominals, N.ndarray) and (N.size(preinit_nominals) > 0): # Heuristic: # Try to find if atol was specified as "atol = factor * model.nominal_continuous_states", # and if that's the case, recompute atol with nominals from after initialization. @@ -1323,9 +1323,10 @@ def parameter_estimation_callback(y): p0 = [] for i,parameter in enumerate(self.parameters): p0.append(self.model.get(parameter)/self.options["scaling"][i]) + p0 = N.array(p0).flatten() print('\nRunning solver: ' + self.options["method"]) - print(' Initial parameters (scaled): ' + str(N.array(p0).flatten())) + print(' Initial parameters (scaled): ' + str(p0)) print(' ') res = sciopt.minimize(parameter_estimation_f, p0, diff --git a/src/pyfmi/fmi_coupled.pyx b/src/pyfmi/fmi_coupled.pyx index c0bdf7e3..debfb55f 100644 --- a/src/pyfmi/fmi_coupled.pyx +++ b/src/pyfmi/fmi_coupled.pyx @@ -15,8 +15,10 @@ # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . +# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION + import pyfmi.fmi as fmi -from fmi cimport FMUModelME2 +from pyfmi.fmi cimport FMUModelME2 cimport fmil_import as FMIL from pyfmi.fmi_util import cpr_seed, enable_caching, Graph @@ -205,7 +207,7 @@ cdef class CoupledModelBase: cdef class CoupledFMUModelBase(CoupledModelBase): cdef public list connections, models - cdef public object __t, __tolerance, _has_entered_init_mode + cdef public object _t, _tolerance, _has_entered_init_mode cdef public int _len_inputs, _len_outputs, _len_states, _len_events cdef public object models_dict, models_id_mapping cdef public dict index,names @@ -232,7 +234,6 @@ cdef class CoupledFMUModelBase(CoupledModelBase): "couplings": {}}) for model in self.models) self.models_id_mapping = {str(id(model)): model for model in self.models} - self._len_inputs = 0 self._len_outputs = 0 self._len_states = 0 self._len_events = 0 @@ -241,8 +242,8 @@ cdef class CoupledFMUModelBase(CoupledModelBase): self.connection_setup() #Default values - self.__t = None - self.__tolerance = None + self._t = None + self._tolerance = None self._has_entered_init_mode = False @@ -421,8 +422,8 @@ cdef class CoupledFMUModelBase(CoupledModelBase): if stop_time == "Default": stop_time = self.get_default_experiment_stop_time() - self.__t = start_time - self.__tolerance = tolerance + self._t = start_time + self._tolerance = tolerance for model in self.models: model.setup_experiment(tolerance_defined, tolerance, start_time, stop_time_defined, stop_time) @@ -487,7 +488,7 @@ cdef class CoupledFMUModelBase(CoupledModelBase): model.reset() #Default values - self.__t = None + self._t = None self._has_entered_init_mode = False #Internal values @@ -680,7 +681,7 @@ cdef class CoupledFMUModelBase(CoupledModelBase): The ValueReference for the variable passed as argument. """ - cdef FMIL.fmi2_value_reference_t vr + cdef FMIL.fmi2_value_reference_t vr name_parts = variable_name.split(".") try: @@ -1008,7 +1009,7 @@ cdef class CoupledFMUModelBase(CoupledModelBase): input_valueref = np.array(valueref, ndmin=1).ravel() set_value = np.array(values, dtype=float, ndmin=1).ravel() - if input_valueref.size != set_value.size: + if np.size(input_valueref) != np.size(set_value): raise fmi.FMUException('The length of valueref and values are inconsistent.') for i,vref in enumerate(input_valueref): @@ -1043,7 +1044,7 @@ cdef class CoupledFMUModelBase(CoupledModelBase): input_valueref = np.array(valueref, ndmin=1).ravel() set_value = np.array(values, dtype=int,ndmin=1).ravel() - if input_valueref.size != set_value.size: + if np.size(input_valueref) != np.size(set_value): raise fmi.FMUException('The length of valueref and values are inconsistent.') for i,vref in enumerate(input_valueref): @@ -1078,7 +1079,7 @@ cdef class CoupledFMUModelBase(CoupledModelBase): input_valueref = np.array(valueref, ndmin=1).ravel() set_value = np.array(values, ndmin=1).ravel() - if input_valueref.size != set_value.size: + if np.size(input_valueref) != np.size(set_value): raise fmi.FMUException('The length of valueref and values are inconsistent.') for i,vref in enumerate(input_valueref): @@ -1865,7 +1866,7 @@ cdef class CoupledFMUModelME2(CoupledFMUModelBase): The time. """ - return self.__t + return self._t cpdef _set_time(self, FMIL.fmi2_real_t t): """ @@ -1878,7 +1879,7 @@ cdef class CoupledFMUModelME2(CoupledFMUModelBase): """ for model in self.models: model.time = t - self.__t = t + self._t = t time = property(_get_time,_set_time) @@ -2264,14 +2265,15 @@ cdef class CoupledFMUModelME2(CoupledFMUModelBase): return capabilities['providesDirectionalDerivatives'] def _compare_connected_outputs(self, y, y_new): - cdef double sum = 0.0 + cdef double _sum = 0.0 cdef int i, N = len(y) + cdef double err for i in range(N): - prod = (y[i]-y_new[i]) * (1 / (self.__tolerance*y[i]+self.__tolerance)) #Missing nominals - sum += prod*prod + prod = (y[i]-y_new[i]) * (1 / (self._tolerance*y[i]+self._tolerance)) #Missing nominals + _sum += prod*prod - err = (sum/N)**0.5 if N > 0 else 0.0 #If there are no connections between the models + err = (_sum/N)**0.5 if N > 0 else 0.0 #If there are no connections between the models if err < 1: return False #No new discrete states needed diff --git a/src/pyfmi/fmi_extended.pyx b/src/pyfmi/fmi_extended.pyx index bfad504b..01ee7045 100644 --- a/src/pyfmi/fmi_extended.pyx +++ b/src/pyfmi/fmi_extended.pyx @@ -14,6 +14,9 @@ # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . + +# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION + """ Module containing the FMI interface Python wrappers. """ @@ -30,9 +33,9 @@ cimport numpy as N N.import_array() cimport fmil_import as FMIL -from fmi cimport FMUModelME1 -from fmi import FMUException -from fmi import FMI_OK, FMI_DEFAULT_LOG_LEVEL, FMI_ME +from pyfmi.fmi cimport FMUModelME1 +from pyfmi.fmi import FMUException +from pyfmi.fmi import FMI_OK, FMI_DEFAULT_LOG_LEVEL, FMI_ME cdef class FMUModelME1Extended(FMUModelME1): diff --git a/src/pyfmi/fmi_util.pxd b/src/pyfmi/fmi_util.pxd index 5b4c46a8..002d2c9f 100644 --- a/src/pyfmi/fmi_util.pxd +++ b/src/pyfmi/fmi_util.pxd @@ -17,6 +17,10 @@ from libc.stdio cimport FILE +import numpy as np +cimport numpy as np +from pyfmi.fmi cimport FMUModelME2 + cpdef decode(x) cpdef encode(x) @@ -45,4 +49,15 @@ ELSE: cdef inline int os_specific_fseek(FILE *stream, long long offset, int whence): return fseeko(stream, offset, whence) cdef inline long long os_specific_ftell(FILE *stream): - return ftello(stream) \ No newline at end of file + return ftello(stream) + +cdef class DumpData: + cdef np.ndarray real_var_ref, int_var_ref, bool_var_ref + cdef np.ndarray real_var_tmp, int_var_tmp, bool_var_tmp + cdef np.ndarray time_tmp + cdef public FMUModelME2 model_me2 + cdef public int model_me2_instance + cdef public object _file, model + cdef size_t real_size, int_size, bool_size + cdef int _with_diagnostics + cdef dump_data(self, np.ndarray data) diff --git a/src/pyfmi/fmi_util.pyx b/src/pyfmi/fmi_util.pyx index 65c4e764..5b9c48d7 100644 --- a/src/pyfmi/fmi_util.pyx +++ b/src/pyfmi/fmi_util.pyx @@ -14,6 +14,9 @@ # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . + +# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION + """ Module containing the FMI interface Python wrappers. """ @@ -34,7 +37,7 @@ from pyfmi.fmi cimport FMUModelME2, FMUModelBase import functools import marshal -import fmi +import pyfmi.fmi as fmi import sys python3_flag = True if sys.hexversion > 0x03000000 else False @@ -274,7 +277,10 @@ cpdef prepare_data_info(np.ndarray[int, ndim=2] data_info, list sorted_vars, lis data_info[2,i] = 0 data_info[3,i] = -1 - alias = -1 if var.alias == FMI_NEGATED_ALIAS else 1 + if var.alias == FMI_NEGATED_ALIAS: + alias = -1 + else: + alias = 1 if last_vref == var.value_reference: data_info[0,i] = last_data_matrix @@ -314,7 +320,10 @@ cpdef prepare_data_info(np.ndarray[int, ndim=2] data_info, list sorted_vars, lis data_info[1,i] = alias*last_index data_info[0,i] = last_data_matrix - data_info[0,0] = 0; data_info[1, 0] = 1; data_info[2, 0] = 0; data_info[3, 0] = -1 + data_info[0, 0] = 0 + data_info[1, 0] = 1 + data_info[2, 0] = 0 + data_info[3, 0] = -1 for i in range(nof_sorted_vars+1, nof_sorted_vars+1+nof_diag_params): data_info[0,i] = 1 @@ -336,7 +345,7 @@ cpdef prepare_data_info(np.ndarray[int, ndim=2] data_info, list sorted_vars, lis model.get_integer(param_int).astype(float), model.get_boolean(param_bool).astype(float), np.array(diagnostics_param_values).astype(float)), - axis = 0, + axis = 0 ) ) @@ -1019,17 +1028,7 @@ class Graph: f.write('}') cdef class DumpData: - cdef np.ndarray real_var_ref, int_var_ref, bool_var_ref - cdef np.ndarray real_var_tmp, int_var_tmp, bool_var_tmp - cdef np.ndarray time_tmp - cdef public FMUModelME2 model_me2 - cdef public int model_me2_instance - cdef public object _file, model - cdef size_t real_size, int_size, bool_size - cdef int _with_diagnostics - def __init__(self, model, filep, real_var_ref, int_var_ref, bool_var_ref, with_diagnostics): - if type(model) != FMUModelME2: self.real_var_ref = np.array(real_var_ref, ndmin=1).ravel() self.int_var_ref = np.array(int_var_ref, ndmin=1).ravel() @@ -1039,14 +1038,14 @@ cdef class DumpData: self.int_var_ref = np.array(int_var_ref, dtype=np.uint32, ndmin=1).ravel() self.bool_var_ref = np.array(bool_var_ref, dtype=np.uint32, ndmin=1).ravel() - self.real_var_tmp = np.zeros(self.real_var_ref.size) - self.int_var_tmp = np.zeros(self.int_var_ref.size, dtype=np.int32) - self.bool_var_tmp = np.zeros(self.bool_var_ref.size) - self.time_tmp = np.zeros(1) + self.real_size = np.size(self.real_var_ref) + self.int_size = np.size(self.int_var_ref) + self.bool_size = np.size(bool_var_ref) - self.real_size = self.real_var_ref.size - self.int_size = self.int_var_ref.size - self.bool_size = self.bool_var_ref.size + self.real_var_tmp = np.zeros(self.real_size) + self.int_var_tmp = np.zeros(self.int_size, dtype=np.int32) + self.bool_var_tmp = np.zeros(self.bool_size) + self.time_tmp = np.zeros(1) self._file = filep @@ -1070,7 +1069,7 @@ cdef class DumpData: self.dump_data(self.time_tmp) if self.real_size > 0: - self.model_me2._get_real(self.real_var_ref, self.real_size, self.real_var_tmp) + self.model_me2._get_real_by_list(self.real_var_ref, self.real_size, self.real_var_tmp) self.dump_data(self.real_var_tmp) if self.int_size > 0: @@ -1269,7 +1268,10 @@ def read_diagnostics_trajectory( flag_ptr = flag.data if has_position_data == 1: - file_pos_list = file_pos_diag_var if read_diag_data == 1 else file_pos_model_var + if read_diag_data == 1: + file_pos_list = file_pos_diag_var + else: + file_pos_list = file_pos_model_var for file_pos in file_pos_list: os_specific_fseek(cfile, file_pos+data_index*sizeof_type, 0) fread((data_ptr + i), sizeof_dtype, 1, cfile) diff --git a/src/pyfmi/fmil_import.pxd b/src/pyfmi/fmil_import.pxd index e91f8228..f514dc00 100644 --- a/src/pyfmi/fmil_import.pxd +++ b/src/pyfmi/fmil_import.pxd @@ -292,7 +292,7 @@ cdef extern from 'fmilib.h': ctypedef void(*fmi2_callback_logger_ft)(fmi2_component_environment_t c,fmi2_string_t instanceName, fmi2_status_t status, fmi2_string_t category,fmi2_string_t message,...) ctypedef void(*fmi1_step_finished_ft)(fmi1_component_t c, fmi1_status_t status) ctypedef void(*fmi2_step_finished_ft)(fmi2_component_environment_t env, fmi2_status_t status) - ctypedef void (*jm_logger_f)(jm_callbacks* c, jm_string module, jm_log_level_enu_t log_level, jm_string message) + ctypedef void (*jm_logger_f)(jm_callbacks* c, jm_string module, jm_log_level_enu_t log_level, jm_string message) except * ctypedef void *(*fmi2_callback_allocate_memory_ft)(size_t, size_t) ctypedef void(*fmi2_callback_free_memory_ft)(void *) ctypedef int(*fmi2_xml_element_start_handle_ft)(void *, char *, void *, char *, char * *) diff --git a/src/pyfmi/master.pyx b/src/pyfmi/master.pyx index 82d14633..4e1e5f2f 100644 --- a/src/pyfmi/master.pyx +++ b/src/pyfmi/master.pyx @@ -15,6 +15,8 @@ # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . +# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION + import pyfmi.fmi as fmi from pyfmi.common.algorithm_drivers import OptionBase, InvalidAlgorithmOptionException, AssimuloSimResult from pyfmi.common.io import ResultDymolaTextual, ResultHandlerFile, ResultHandlerDummy, ResultHandlerBinaryFile, ResultDymolaBinary @@ -37,10 +39,10 @@ import scipy.sparse.linalg as splin import scipy.optimize as sopt import scipy.version -from fmi cimport FMUModelCS2 +from pyfmi.fmi cimport FMUModelCS2 from cpython cimport bool cimport fmil_import as FMIL -from fmi_util import Graph +from pyfmi.fmi_util import Graph from cython.parallel import prange, parallel IF WITH_OPENMP: @@ -373,7 +375,7 @@ cdef class Master: cdef public dict statistics, models_id_mapping cdef public object opts cdef public object models_dict, L, L_discrete - cdef public object I + cdef public object _ident_matrix cdef public object y_prev, yd_prev, input_traj cdef public object DL_prev cdef public int algebraic_loops, storing_fmu_state @@ -466,7 +468,7 @@ cdef class Master: self.y_prev = None self.input_traj = None - self.I = sp.eye(self._len_inputs, self._len_outputs, format="csr") #y = Cx + Du , u = Ly -> DLy DL[inputsXoutputs] + self._ident_matrix = sp.eye(self._len_inputs, self._len_outputs, format="csr") #y = Cx + Du , u = Ly -> DLy DL[inputsXoutputs] self._error_data = {"time":[], "error":[], "step-size":[], "rejected":[]} @@ -756,34 +758,31 @@ cdef class Master: return self.storing_fmu_state cpdef np.ndarray get_connection_outputs(self): - cdef int i = 0, inext = 0 + cdef int i, index, index_start, index_end cdef np.ndarray y = np.empty((self._len_outputs)) for model in self.models: - #y.extend(model.get(self.models_dict[model]["local_output"])) - #y.extend(model.get_real(self.models_dict[model]["local_output_vref"])) - i = self.models_dict[model]["global_index_outputs"] - inext = i + self.models_dict[model]["local_output_len"] - y[i:inext] = (model).get_real(self.models_dict[model]["local_output_vref_array"]) - i = inext - - #return np.array(y) + index_start = self.models_dict[model]["global_index_outputs"] + index_end = index_start + self.models_dict[model]["local_output_len"] + local_output_vref_array = (model).get_real(self.models_dict[model]["local_output_vref_array"]) + for i, index in enumerate(range(index_start, index_end)): + y[index] = local_output_vref_array[i] return y.reshape(-1,1) cpdef np.ndarray get_connection_outputs_discrete(self): - cdef int i = 0, inext = 0 + cdef int i, index, index_start, index_end cdef np.ndarray y = np.empty((self._len_outputs_discrete)) for model in self.models: - i = self.models_dict[model]["global_index_outputs_discrete"] - inext = i + self.models_dict[model]["local_output_discrete_len"] - y[i:inext] = model.get(self.models_dict[model]["local_output_discrete"]) - i = inext - + index_start = self.models_dict[model]["global_index_outputs_discrete"] + index_end = index_start + self.models_dict[model]["local_output_discrete_len"] + local_output_discrete = model.get(self.models_dict[model]["local_output_discrete"]) + for i, index in enumerate(range(index_start, index_end)): + y[index] = local_output_discrete[i] return y.reshape(-1,1) cpdef np.ndarray _get_derivatives(self): - cdef int i = 0, inext = 0 + cdef int i, index, index_start, index_end cdef np.ndarray xd = np.empty((self._len_derivatives)) for model in self.models_dict.keys(): @@ -791,10 +790,11 @@ cdef class Master: return None for model in self.models: - i = self.models_dict[model]["global_index_derivatives"] - inext = i + self.models_dict[model]["local_derivative_len"] - xd[i:inext] = (model).get_real(self.models_dict[model]["local_derivative_vref_array"]) - i = inext + index_start = self.models_dict[model]["global_index_derivatives"] + index_end = index_start + self.models_dict[model]["local_derivative_len"] + local_derivative_vref_array = (model).get_real(self.models_dict[model]["local_derivative_vref_array"]) + for i, index in enumerate(range(index_start, index_end)): + xd[index] = local_derivative_vref_array[i] return xd.reshape(-1,1) @@ -853,7 +853,7 @@ cdef class Master: else: return C.dot(xd)+D.dot(ud) else: #First step - return splin.spsolve((self.I-D.dot(self.L)),C.dot(xd)).reshape((-1,1)) + return splin.spsolve((self._ident_matrix-D.dot(self.L)),C.dot(xd)).reshape((-1,1)) y_last = self.get_last_y() if y_last is not None: @@ -898,7 +898,7 @@ cdef class Master: if ud is not None and udd is not None: return C.dot(A.dot(xd))+C.dot(B.dot(ud+self.get_current_step_size()*udd))+D.dot(udd) else: #First step - return splin.spsolve((self.I-D.dot(self.L)),C.dot(A.dot(xd)+B.dot(self.L.dot(yd_cur)))).reshape((-1,1)) + return splin.spsolve((self._ident_matrix-D.dot(self.L)),C.dot(A.dot(xd)+B.dot(self.L.dot(yd_cur)))).reshape((-1,1)) yd_last = self.get_last_yd() if yd_last is not None: @@ -965,7 +965,7 @@ cdef class Master: z = yd - D.dot(uhat) - yd = splin.spsolve((self.I-DL),z).reshape((-1,1)) + yd = splin.spsolve((self._ident_matrix-DL),z).reshape((-1,1)) """ return ydd @@ -980,7 +980,7 @@ cdef class Master: z = yd - D.dot(uhat) - yd = splin.spsolve((self.I-DL),z).reshape((-1,1)) + yd = splin.spsolve((self._ident_matrix-DL),z).reshape((-1,1)) return yd @@ -1016,7 +1016,7 @@ cdef class Master: z = y - DL.dot(y_prev) #z = y - matvec(DL, y_prev.ravel()) - y = splin.spsolve((self.I-DL),z).reshape((-1,1)) + y = splin.spsolve((self._ident_matrix-DL),z).reshape((-1,1)) #y = splin.lsqr((sp.eye(*DL.shape)-DL),z)[0].reshape((-1,1)) elif self.algebraic_loops and self.support_directional_derivatives: @@ -1339,15 +1339,15 @@ cdef class Master: C = self.compute_global_C() if C is not None: C = C.todense() - I = np.eye(*DL.shape) - LIDLC = self.L.dot(lin.solve(I-DL,C)) + _ident_matrix = np.eye(*DL.shape) + LIDLC = self.L.dot(lin.solve(_ident_matrix-DL,C)) print(" , rho(L(I-DL)^(-1)C)=%s"%(str(numpy.linalg.eig(LIDLC)[0]))) A = self.compute_global_A() B = self.compute_global_B() if C is not None and A is not None and B is not None: A = A.todense(); B = B.todense() eAH = slin.expm(A*step_size) - K1 = lin.solve(I-DL,C) + K1 = lin.solve(_ident_matrix-DL,C) K2 = lin.solve(A,(eAH-np.eye(*eAH.shape)).dot(B.dot(self.L.todense()))) R1 = np.hstack((eAH, K1)) R2 = np.hstack((K2.dot(eAH), K2.dot(K1))) @@ -1391,11 +1391,13 @@ cdef class Master: cdef double alpha = 0.9 cdef double fac1 = 6.0 cdef double fac2 = 0.2 + cdef double _tmp if error == 0.0: return step_size*fac1 else: - return step_size*min(fac1,max(fac2,alpha*(1.0/error)**one_over_p)) + _tmp = alpha*(1.0/error)**one_over_p + return step_size*min(fac1, max(fac2, _tmp)) cdef reset_statistics(self): for key in self.elapsed_time: diff --git a/src/pyfmi/simulation/assimulo_interface.pxd b/src/pyfmi/simulation/assimulo_interface.pxd index 044e12c0..91f7c0d6 100644 --- a/src/pyfmi/simulation/assimulo_interface.pxd +++ b/src/pyfmi/simulation/assimulo_interface.pxd @@ -18,6 +18,7 @@ import numpy as N cimport numpy as N +import logging from pyfmi.fmi cimport FMUModelME2 @@ -33,7 +34,6 @@ if assimulo_present: from assimulo.problem import Implicit_Problem from assimulo.problem import Explicit_Problem from assimulo.problem cimport cExplicit_Problem - from assimulo.exception import * else: class Implicit_Problem: pass diff --git a/src/pyfmi/simulation/assimulo_interface.pyx b/src/pyfmi/simulation/assimulo_interface.pyx index 3b93e989..62d82610 100644 --- a/src/pyfmi/simulation/assimulo_interface.pyx +++ b/src/pyfmi/simulation/assimulo_interface.pyx @@ -15,6 +15,8 @@ # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . +# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION + """ This file contains code for mapping FMUs to the Problem specifications required by Assimulo. @@ -54,7 +56,7 @@ if assimulo_present: from assimulo.problem import Implicit_Problem from assimulo.problem import Explicit_Problem from assimulo.problem cimport cExplicit_Problem - from assimulo.exception import * + from assimulo.exception import AssimuloRecoverableError, TerminateSimulation else: class Implicit_Problem: pass @@ -727,7 +729,7 @@ cdef class FMIODE2(cExplicit_Problem): self.model_me2._set_time(t) #Check if there are any states if self._f_nbr != 0: - self.model_me2.__set_continuous_states(y) + self.model_me2._set_continuous_states_fmil(y) else: #Moving data to the model self._model.time = t @@ -748,7 +750,7 @@ cdef class FMIODE2(cExplicit_Problem): if self._f_nbr == 0: return 0 - self.model_me2.__get_continuous_states(self._state_temp_1) + self.model_me2._get_continuous_states_fmil(self._state_temp_1) res = FMIL.memcmp(self._state_temp_1.data, y.data, self._f_nbr*sizeof(double)) if res == 0: diff --git a/tests/test_fmi.py b/tests/test_fmi.py index bdc9e4bf..3b46e907 100644 --- a/tests/test_fmi.py +++ b/tests/test_fmi.py @@ -25,7 +25,7 @@ from io import StringIO from pyfmi import testattr -from pyfmi.fmi import FMUException, InvalidOptionException, InvalidXMLException, InvalidBinaryException, InvalidVersionException, FMUModelME1, FMUModelCS1, load_fmu, FMUModelCS2, FMUModelME2, PyEventInfo +from pyfmi.fmi import FMUException, InvalidOptionException, InvalidXMLException, InvalidBinaryException, InvalidVersionException, FMUModelME1, FMUModelCS1, load_fmu, FMUModelCS2, FMUModelME2 import pyfmi.fmi as fmi from pyfmi.fmi_algorithm_drivers import AssimuloFMIAlg, AssimuloFMIAlgOptions, \ PYFMI_JACOBIAN_LIMIT, PYFMI_JACOBIAN_SPARSE_SIZE_LIMIT @@ -538,7 +538,7 @@ def test_get_erroneous_nominals_capi_fmi1(self): logging.basicConfig(stream=log_stream, level=logging.WARNING) model.states_vref = [114, 115, 116, 117, 118, 119, 120, 121] - # NOTE: Property 'nominal_continuous_states' is already overriden in Dummy_FMUModelME1, so just + # NOTE: Property 'nominal_continuous_states' is already overridden in Dummy_FMUModelME1, so just # call the underlying function immediately. xn = model._get_nominal_continuous_states() @@ -1191,16 +1191,19 @@ def test_estimate_directional_derivatives_BCD(self): model = Dummy_FMUModelME2([], os.path.join(file_path, "files", "FMUs", "XML", "ME2.0", "OutputTest2.fmu"), _connect_dll=False) def f(*args, **kwargs): - x1 = model.values[model.variables["x1"].value_reference] - x2 = model.values[model.variables["x2"].value_reference] - u1 = model.values[model.variables["u1"].value_reference] - - model.values[model.variables["y1"].value_reference] = x1*x2 - u1 - model.values[model.variables["y2"].value_reference] = x2 - model.values[model.variables["y3"].value_reference] = u1 + x1 - - model.values[model.variables["der(x1)"].value_reference] = -1.0 - model.values[model.variables["der(x2)"].value_reference] = -1.0 + x1 = model.get_real([model.variables["x1"].value_reference], evaluate = False) + x2 = model.get_real([model.variables["x2"].value_reference], evaluate = False) + u1 = model.get_real([model.variables["u1"].value_reference], evaluate = False) + + model.set_real([model.variables["y1"].value_reference], x1*x2 - u1) + model.set_real([model.variables["y2"].value_reference], x2) + model.set_real([model.variables["y3"].value_reference], u1 + x1) + + dx1 = -1.0 + dx2 = -1.0 + model.set_real([model.variables["der(x1)"].value_reference], [dx1]) + model.set_real([model.variables["der(x2)"].value_reference], [dx2]) + return np.array([dx1, dx2]) model.get_derivatives = f model.initialize() @@ -1227,17 +1230,17 @@ def f(*args, **kwargs): C = model._get_C(use_structure_info=True) D = model._get_D(use_structure_info=True) - assert np.allclose(B.toarray(), np.array([[0.0],[0.0]])) - assert np.allclose(C.toarray(), np.array([[0.0, 0.0],[0.0, 1.0], [1.0, 0.0]])) - assert np.allclose(D.toarray(), np.array([[-1.0],[0.0], [1.0]])) + assert np.allclose(B.toarray(), np.array([[0.0], [0.0]])), str(B.toarray()) + assert np.allclose(C.toarray(), np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0]])), str(C.toarray()) + assert np.allclose(D.toarray(), np.array([[-1.0], [0.0], [1.0]])), str(D.toarray()) B = model._get_B(use_structure_info=False) C = model._get_C(use_structure_info=False) D = model._get_D(use_structure_info=False) - assert np.allclose(B, np.array([[0.0],[0.0]])) - assert np.allclose(C, np.array([[0.0, 0.0],[0.0, 1.0], [1.0, 0.0]])) - assert np.allclose(D, np.array([[-1.0],[0.0], [1.0]])) + assert np.allclose(B, np.array([[0.0], [0.0]])), str(B.toarray()) + assert np.allclose(C, np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0]])), str(C.toarray()) + assert np.allclose(D, np.array([[-1.0], [0.0], [1.0]])), str(D.toarray()) @testattr(stddist = True) def test_output_dependencies(self): @@ -1421,7 +1424,7 @@ def test_get_erroneous_nominals_capi(self): log_stream = StringIO() logging.basicConfig(stream=log_stream, level=logging.WARNING) - # NOTE: Property 'nominal_continuous_states' is already overriden in Dummy_FMUModelME2, so just + # NOTE: Property 'nominal_continuous_states' is already overridden in Dummy_FMUModelME2, so just # call the underlying function immediately. xn = model._get_nominal_continuous_states() diff --git a/tests/test_fmi_coupled.py b/tests/test_fmi_coupled.py index 2fe809cb..d0b26f88 100644 --- a/tests/test_fmi_coupled.py +++ b/tests/test_fmi_coupled.py @@ -46,26 +46,26 @@ def test_linear_example(self): model_sub_2 = Dummy_FMUModelME2([], os.path.join(me2_xml_path, "LinearStability.SubSystem2.fmu"), _connect_dll=False) def sub1(*args, **kwargs): - u1 = model_sub_1.values[model_sub_1.get_variable_valueref("u1")] - a1 = model_sub_1.values[model_sub_1.get_variable_valueref("a1")] - b1 = model_sub_1.values[model_sub_1.get_variable_valueref("b1")] - c1 = model_sub_1.values[model_sub_1.get_variable_valueref("c1")] - d1 = model_sub_1.values[model_sub_1.get_variable_valueref("d1")] + u1 = model_sub_1.get_real([model_sub_1.get_variable_valueref("u1")], evaluate = False) + a1 = model_sub_1.get_real([model_sub_1.get_variable_valueref("a1")], evaluate = False) + b1 = model_sub_1.get_real([model_sub_1.get_variable_valueref("b1")], evaluate = False) + c1 = model_sub_1.get_real([model_sub_1.get_variable_valueref("c1")], evaluate = False) + d1 = model_sub_1.get_real([model_sub_1.get_variable_valueref("d1")], evaluate = False) x1 = model_sub_1.continuous_states[0] - model_sub_1.values[model_sub_1.get_variable_valueref("y1")] = c1*x1+d1*u1 - model_sub_1.values[model_sub_1.get_variable_valueref("x1")] = x1 - return np.array([a1*x1+b1*u1]) + model_sub_1.set_real([model_sub_1.get_variable_valueref("y1")], c1*x1+d1*u1) + model_sub_1.set_real([model_sub_1.get_variable_valueref("x1")], [x1]) + return a1*x1+b1*u1 def sub2(*args, **kwargs): - u2 = model_sub_2.values[model_sub_2.get_variable_valueref("u2")] - a2 = model_sub_2.values[model_sub_2.get_variable_valueref("a2")] - b2 = model_sub_2.values[model_sub_2.get_variable_valueref("b2")] - c2 = model_sub_2.values[model_sub_2.get_variable_valueref("c2")] - d2 = model_sub_2.values[model_sub_2.get_variable_valueref("d2")] + u2 = model_sub_2.get_real([model_sub_2.get_variable_valueref("u2")], evaluate = False) + a2 = model_sub_2.get_real([model_sub_2.get_variable_valueref("a2")], evaluate = False) + b2 = model_sub_2.get_real([model_sub_2.get_variable_valueref("b2")], evaluate = False) + c2 = model_sub_2.get_real([model_sub_2.get_variable_valueref("c2")], evaluate = False) + d2 = model_sub_2.get_real([model_sub_2.get_variable_valueref("d2")], evaluate = False) x2 = model_sub_2.continuous_states[0] - model_sub_2.values[model_sub_2.get_variable_valueref("y2")] = c2*x2+d2*u2 - model_sub_2.values[model_sub_2.get_variable_valueref("x2")] = x2 - return np.array([a2*x2+b2*u2]) + model_sub_2.set_real([model_sub_2.get_variable_valueref("y2")], c2*x2+d2*u2) + model_sub_2.set_real([model_sub_2.get_variable_valueref("x2")], [x2]) + return a2*x2+b2*u2 model_sub_1.get_derivatives = sub1 model_sub_2.get_derivatives = sub2 diff --git a/tests/test_fmi_estimate.py b/tests/test_fmi_estimate.py index e32d2cee..0f438c09 100644 --- a/tests/test_fmi_estimate.py +++ b/tests/test_fmi_estimate.py @@ -15,17 +15,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -import nose import os import numpy as np from pyfmi import testattr -from pyfmi.fmi import FMUException, FMUModelME1, FMUModelCS1, load_fmu, FMUModelCS2, FMUModelME2, PyEventInfo -import pyfmi.fmi_util as fmi_util -import pyfmi.fmi as fmi -import pyfmi.fmi_algorithm_drivers as fmi_algorithm_drivers -from pyfmi.tests.test_util import Dummy_FMUModelCS1, Dummy_FMUModelME1, Dummy_FMUModelME2, Dummy_FMUModelCS2 -from pyfmi.common.io import ResultHandler +from pyfmi.tests.test_util import Dummy_FMUModelME2 from scipy.io.matlab.mio import loadmat assimulo_installed = True @@ -43,41 +37,43 @@ class Test_FMUModelME2_Estimate: def test_quadtank_estimate(self): model = Dummy_FMUModelME2([], os.path.join(file_path, "files", "FMUs", "XML", "ME2.0", "QuadTankPack_Sim_QuadTank.fmu"), _connect_dll=False) - g = model.values[model.get_variable_valueref("qt.g")] - g1_nmp = model.values[model.get_variable_valueref("qt.g1_nmp")] - g2_nmp = model.values[model.get_variable_valueref("qt.g2_nmp")] - k1_nmp = model.values[model.get_variable_valueref("qt.k1_nmp")] - k2_nmp = model.values[model.get_variable_valueref("qt.k2_nmp")] - A1 = model.values[model.get_variable_valueref("qt.A1")] - A2 = model.values[model.get_variable_valueref("qt.A2")] - A3 = model.values[model.get_variable_valueref("qt.A3")] - A4 = model.values[model.get_variable_valueref("qt.A4")] - a3 = model.values[model.get_variable_valueref("qt.a3")] - a4 = model.values[model.get_variable_valueref("qt.a4")] + g = model.get_real([model.get_variable_valueref("qt.g")], evaluate = False) + g1_nmp = model.get_real([model.get_variable_valueref("qt.g1_nmp")], evaluate = False) + g2_nmp = model.get_real([model.get_variable_valueref("qt.g2_nmp")], evaluate = False) + k1_nmp = model.get_real([model.get_variable_valueref("qt.k1_nmp")], evaluate = False) + k2_nmp = model.get_real([model.get_variable_valueref("qt.k2_nmp")], evaluate = False) + A1 = model.get_real([model.get_variable_valueref("qt.A1")], evaluate = False) + A2 = model.get_real([model.get_variable_valueref("qt.A2")], evaluate = False) + A3 = model.get_real([model.get_variable_valueref("qt.A3")], evaluate = False) + A4 = model.get_real([model.get_variable_valueref("qt.A4")], evaluate = False) + a3 = model.get_real([model.get_variable_valueref("qt.a3")], evaluate = False) + a4 = model.get_real([model.get_variable_valueref("qt.a4")], evaluate = False) u1_vref = model.get_variable_valueref("u1") u2_vref = model.get_variable_valueref("u2") a1_vref = model.get_variable_valueref("qt.a1") a2_vref = model.get_variable_valueref("qt.a2") def f(*args, **kwargs): - x1 = model.continuous_states[0]; x2 = model.continuous_states[1]; x3 = model.continuous_states[2]; x4 = model.continuous_states[3] - u1 = model.values[u1_vref] - u2 = model.values[u2_vref] - a1 = model.values[a1_vref] - a2 = model.values[a2_vref] + x1 = model.continuous_states[0] + x2 = model.continuous_states[1] + x3 = model.continuous_states[2] + x4 = model.continuous_states[3] + + u1 = model.get_real([u1_vref], evaluate = False) + u2 = model.get_real([u2_vref], evaluate = False) + a1 = model.get_real([a1_vref], evaluate = False) + a2 = model.get_real([a2_vref], evaluate = False) - sqrt = lambda x: (x)**0.5 - der_x1 = -a1/A1*sqrt(2.*g*x1) + a3/A1*sqrt(2*g*x3) + g1_nmp*k1_nmp/A1*u1; - der_x2 = -a2/A2*sqrt(2.*g*x2) + a4/A2*sqrt(2*g*x4) + g2_nmp*k2_nmp/A2*u2; - der_x3 = -a3/A3*sqrt(2.*g*x3) + (1.-g2_nmp)*k2_nmp/A3*u2; - der_x4 = -a4/A4*sqrt(2.*g*x4) + (1.-g1_nmp)*k1_nmp/A4*u1; - return np.array([der_x1,der_x2,der_x3,der_x4]) - + der_x1 = -a1/A1*np.sqrt(2.*g*x1) + a3/A1*np.sqrt(2*g*x3) + g1_nmp*k1_nmp/A1*u1 + der_x2 = -a2/A2*np.sqrt(2.*g*x2) + a4/A2*np.sqrt(2*g*x4) + g2_nmp*k2_nmp/A2*u2 + der_x3 = -a3/A3*np.sqrt(2.*g*x3) + (1.-g2_nmp)*k2_nmp/A3*u2 + der_x4 = -a4/A4*np.sqrt(2.*g*x4) + (1.-g1_nmp)*k1_nmp/A4*u1 + return np.concatenate([der_x1, der_x2, der_x3, der_x4]) model.get_derivatives = f # Load measurement data from file - data = loadmat(os.path.join(file_path, "files", "Results", "qt_par_est_data.mat"),appendmat=False) + data = loadmat(os.path.join(file_path, "files", "Results", "qt_par_est_data.mat"), appendmat=False) # Extract data series t_meas = data['t'][6000::100,0]-60 @@ -92,7 +88,7 @@ def f(*args, **kwargs): u = np.transpose(np.vstack((t_meas,u1,u2))) # Estimation of 2 parameters - data = np.vstack((t_meas, y1_meas,y2_meas)).transpose() + data = np.vstack((t_meas, y1_meas, y2_meas)).transpose() res = model.estimate(parameters=["qt.a1", "qt.a2"], measurements = (['qt.x1', 'qt.x2'], data), input=(['u1','u2'],u)) @@ -101,11 +97,11 @@ def f(*args, **kwargs): model.reset() # Set optimal values for a1 and a2 into the model - model.set('qt.a1',res["qt.a1"]) - model.set('qt.a2',res["qt.a2"]) + model.set(['qt.a1'], res["qt.a1"]) + model.set(['qt.a2'], res["qt.a2"]) # Simulate model response with optimal parameters a1 and a2 - res = model.simulate(input=(['u1','u2'],u),start_time=0.,final_time=60) + res = model.simulate(input=(['u1','u2'], u), start_time=0., final_time=60) assert np.abs(res.final('qt.x1') - 0.07060188) < 1e-3, "Was: " + str(res.final('qt.x1')) + ", expected: 0.07060188" assert np.abs(res.final('qt.x2') - 0.06654621) < 1e-3 diff --git a/tests/test_fmi_master.py b/tests/test_fmi_master.py index 6d5bb2aa..811c4b01 100644 --- a/tests/test_fmi_master.py +++ b/tests/test_fmi_master.py @@ -118,7 +118,7 @@ def do_step1(current_t, step_size, new_step=True): u1 = model_sub1.values[model_sub1.get_variable_valueref("u1")] model_sub1.continuous_states = 1.0/a1*(np.exp(a1*step_size)-1.0)*b1*u1+np.exp(a1*step_size)*model_sub1.continuous_states - model_sub1.values[model_sub1.get_variable_valueref("y1")] = c1*model_sub1.continuous_states+d1*u1 + model_sub1.set_real([model_sub1.get_variable_valueref("y1")], c1*model_sub1.continuous_states+d1*u1) model_sub1.completed_integrator_step() return 0 @@ -126,7 +126,7 @@ def do_step2(current_t, step_size, new_step=True): u2 = model_sub2.values[model_sub2.get_variable_valueref("u2")] model_sub2.continuous_states = 1.0/a2*(np.exp(a2*step_size)-1.0)*b2*u2+np.exp(a2*step_size)*model_sub2.continuous_states - model_sub2.values[model_sub2.get_variable_valueref("y2")] = c2*model_sub2.continuous_states+d2*u2 + model_sub2.set_real([model_sub2.get_variable_valueref("y2")], c2*model_sub2.continuous_states+d2*u2) model_sub2.completed_integrator_step() return 0 @@ -219,13 +219,13 @@ def test_integer_connections(self): model_sub1.set("y", 1) def do_step1(current_t, step_size, new_step=True): - model_sub1.values[model_sub1.get_variable_valueref("y")] = 1 if current_t+step_size < 0.5 else 3 + model_sub1.set_integer([model_sub1.get_variable_valueref("y")], [1] if current_t+step_size < 0.5 else [3]) model_sub1.completed_integrator_step() return 0 def do_step2(current_t, step_size, new_step=True): - u = model_sub2.values[model_sub2.get_variable_valueref("u")] - model_sub2.values[model_sub2.get_variable_valueref("y")] = 10*u + u = model_sub2.get_integer([model_sub2.get_variable_valueref("u")]) + model_sub2.set_integer([model_sub2.get_variable_valueref("y")], 10*u) model_sub2.completed_integrator_step() return 0 @@ -233,14 +233,14 @@ def do_step2(current_t, step_size, new_step=True): model_sub2.do_step = do_step2 models = [model_sub1, model_sub2] - connections=[(model_sub1,'y',model_sub2,'u')] + connections = [(model_sub1, 'y', model_sub2, 'u')] master = Master(models,connections) opts = master.simulate_options() opts["block_initialization"] = True - res = master.simulate(start_time=0.0,final_time=2.0, options=opts) + res = master.simulate(start_time=0.0, final_time=2.0, options=opts) assert res[model_sub2]["u"][0] == 1 assert res[model_sub2]["u"][-1] == 3 @@ -252,13 +252,13 @@ def test_integer_to_real_connections(self): model_sub1.set("y", 1) def do_step1(current_t, step_size, new_step=True): - model_sub1.values[model_sub1.get_variable_valueref("y")] = 1 if current_t+step_size < 0.5 else 3 + model_sub1.set_integer([model_sub1.get_variable_valueref("y")], [1] if current_t+step_size < 0.5 else [3]) model_sub1.completed_integrator_step() return 0 def do_step2(current_t, step_size, new_step=True): - u = model_sub2.values[model_sub2.get_variable_valueref("u")] - model_sub2.values[model_sub2.get_variable_valueref("y")] = 10*u + u = model_sub2.get_real([model_sub2.get_variable_valueref("u")]) + model_sub2.set_real([model_sub2.get_variable_valueref("y")], 10*u) model_sub2.completed_integrator_step() return 0 @@ -266,9 +266,9 @@ def do_step2(current_t, step_size, new_step=True): model_sub2.do_step = do_step2 models = [model_sub1, model_sub2] - connections=[(model_sub1,'y',model_sub2,'u')] + connections= [(model_sub1, 'y', model_sub2, 'u')] - master = Master(models,connections) + master = Master(models, connections) opts = master.simulate_options() opts["block_initialization"] = True @@ -299,7 +299,7 @@ def do_step1(current_t, step_size, new_step=True): u1 = model_sub1.values[model_sub1.get_variable_valueref("u1")] model_sub1.continuous_states = 1.0/a1*(np.exp(a1*step_size)-1.0)*b1*u1+np.exp(a1*step_size)*model_sub1.continuous_states - model_sub1.values[model_sub1.get_variable_valueref("y1")] = c1*model_sub1.continuous_states+d1*u1 + model_sub1.set_real([model_sub1.get_variable_valueref("y1")], c1*model_sub1.continuous_states+d1*u1) model_sub1.completed_integrator_step() return 0 @@ -307,7 +307,7 @@ def do_step2(current_t, step_size, new_step=True): u2 = model_sub2.values[model_sub2.get_variable_valueref("u2")] model_sub2.continuous_states = 1.0/a2*(np.exp(a2*step_size)-1.0)*b2*u2+np.exp(a2*step_size)*model_sub2.continuous_states - model_sub2.values[model_sub2.get_variable_valueref("y2")] = c2*model_sub2.continuous_states+d2*u2 + model_sub2.set_real([model_sub2.get_variable_valueref("y2")], c2*model_sub2.continuous_states+d2*u2) model_sub2.completed_integrator_step() return 0 diff --git a/tests/test_stream.py b/tests/test_stream.py index 85981033..a517eb51 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -23,7 +23,7 @@ from filecmp import cmp as compare_files from pyfmi import testattr -from pyfmi.fmi import FMUException, FMUModelME1, FMUModelCS1, load_fmu, FMUModelCS2, FMUModelME2 +from pyfmi.fmi import FMUException, load_fmu, FMUModelCS2, FMUModelME2 from pyfmi.tests.test_util import get_examples_folder file_path = os.path.dirname(os.path.abspath(__file__)) @@ -54,7 +54,7 @@ def simulate_and_verify_stream_contents(compiled_fmu, fmu_loader, stream, open_t is given in mode 'w'. This is solely used for testing to reduce duplicated code. """ - fmu = fmu_loader(compiled_fmu, log_file_name = stream, log_level=3) + fmu = fmu_loader(compiled_fmu, log_file_name = stream, log_level = 3) results = fmu.simulate() contents = [] @@ -156,13 +156,13 @@ def setup_class(cls): def test_testio(self): """ load_fmu and custom IO class. """ stream = TestIO("") - simulate_and_verify_stream_contents(self.example_fmu, self.test_class, stream) + simulate_and_verify_stream_contents(Test_LoadFMU.example_fmu, Test_LoadFMU.test_class, stream) @testattr(stddist = True) def test_stringio(self): """ load_fmu and StringIO. """ stream = StringIO() - simulate_and_verify_stream_contents(self.example_fmu, self.test_class, stream) + simulate_and_verify_stream_contents(Test_LoadFMU.example_fmu, Test_LoadFMU.test_class, stream) @testattr(stddist = True) def test_textiowrapper(self): @@ -170,7 +170,7 @@ def test_textiowrapper(self): p = tempfile.mkdtemp() output_file = os.path.join(p, 'test.txt') stream = open(output_file, 'w') - simulate_and_verify_stream_contents(self.example_fmu, self.test_class, stream, True) + simulate_and_verify_stream_contents(Test_LoadFMU.example_fmu, Test_LoadFMU.test_class, stream, True) if not stream.closed: stream.close() rmtree(p) diff --git a/tests/test_util.py b/tests/test_util.py index 99500ea9..b87abf04 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -15,18 +15,17 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -import nose import os import numpy as np -from pyfmi.fmi import FMUException, FMUModelME1, __ForTestingFMUModelME1, FMUModelCS1, load_fmu, \ - FMUModelCS2, FMUModelME2, __ForTestingFMUModelME2 +from pyfmi.fmi import (FMUException, FMUModelME1, _ForTestingFMUModelME1, FMUModelCS1, + FMUModelCS2, FMUModelME2, _ForTestingFMUModelME2) def get_examples_folder(): return os.path.join(os.path.dirname(__file__), '..', 'examples') -class Dummy_FMUModelME1(__ForTestingFMUModelME1): - # If true, makes use of the real __ForTesting implementation for nominal_continuous_states, +class Dummy_FMUModelME1(_ForTestingFMUModelME1): + # If true, makes use of the real _ForTesting implementation for nominal_continuous_states, # else just returns 1.0 for each. override_nominal_continuous_states = True @@ -136,7 +135,6 @@ class Dummy_FMUModelCS2(FMUModelCS2): def __init__(self, negated_aliases, *args,**kwargs): FMUModelCS2.__init__(self, *args, **kwargs) - self.continuous_states = np.zeros(self.get_ode_sizes()[0]) self.variables = self.get_model_variables(include_alias=False) self.negated_aliases = negated_aliases @@ -208,11 +206,11 @@ def set_integer(self, vref, values): for i,v in enumerate(vref): self.values[v] = values[i] -class Dummy_FMUModelME2(__ForTestingFMUModelME2): +class Dummy_FMUModelME2(_ForTestingFMUModelME2): # -- Test options -- - # If true, makes use of the real __ForTesting implementation for nominal_continuous_states, + # If true, makes use of the real _ForTesting implementation for nominal_continuous_states, # else just returns 1.0 for each. override_nominal_continuous_states = True @@ -286,8 +284,9 @@ def completed_integrator_step(self, *args, **kwargs): def get_derivatives(self): return -self.continuous_states - def get_real(self, vref): - self.get_derivatives() + def get_real(self, vref, evaluate = True): + if evaluate: + self.get_derivatives() vals = [] if type(vref) == int: vref = [vref] @@ -314,4 +313,4 @@ def get_nominal_continuous_states_testimpl(self): else: return super().nominal_continuous_states - nominal_continuous_states = property(get_nominal_continuous_states_testimpl) \ No newline at end of file + nominal_continuous_states = property(get_nominal_continuous_states_testimpl)