-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathfmi3.pyx
More file actions
5236 lines (4132 loc) · 218 KB
/
Copy pathfmi3.pyx
File metadata and controls
5236 lines (4132 loc) · 218 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2025 Modelon AB
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION
cimport cython
import os
from enum import IntEnum
import logging
from pathlib import Path
from typing import Union
import numpy as np
cimport numpy as np
from numpy cimport PyArray_DATA
cimport pyfmi.fmil_import as FMIL
cimport pyfmi.fmil3_import as FMIL3
cimport pyfmi.fmi_base as FMI_BASE
cimport pyfmi.util as pyfmi_util
from pyfmi.util import enable_caching
import scipy.sparse as sps
# TYPES
# TODO: Import into fmi.pyx for convenience imports?
class FMI3_Type(IntEnum):
FLOAT64 = FMIL3.fmi3_base_type_float64
FLOAT32 = FMIL3.fmi3_base_type_float32
INT64 = FMIL3.fmi3_base_type_int64
INT32 = FMIL3.fmi3_base_type_int32
INT16 = FMIL3.fmi3_base_type_int16
INT8 = FMIL3.fmi3_base_type_int8
UINT64 = FMIL3.fmi3_base_type_uint64
UINT32 = FMIL3.fmi3_base_type_uint32
UINT16 = FMIL3.fmi3_base_type_uint16
UINT8 = FMIL3.fmi3_base_type_uint8
BOOL = FMIL3.fmi3_base_type_bool
BINARY = FMIL3.fmi3_base_type_binary
CLOCK = FMIL3.fmi3_base_type_clock
STRING = FMIL3.fmi3_base_type_str
ENUM = FMIL3.fmi3_base_type_enum
class FMI3_Initial(IntEnum):
EXACT = FMIL3.fmi3_initial_enu_exact
APPROX = FMIL3.fmi3_initial_enu_approx
CALCULATED = FMIL3.fmi3_initial_enu_calculated
UNKNOWN = FMIL3.fmi3_initial_enu_unknown
class FMI3_Variability(IntEnum):
CONSTANT = FMIL3.fmi3_variability_enu_constant
FIXED = FMIL3.fmi3_variability_enu_fixed
TUNABLE = FMIL3.fmi3_variability_enu_tunable
DISCRETE = FMIL3.fmi3_variability_enu_discrete
CONTINUOUS = FMIL3.fmi3_variability_enu_continuous
UNKNOWN = FMIL3.fmi3_variability_enu_unknown
class FMI3_Causality(IntEnum):
STRUCTURAL_PARAMETER = FMIL3.fmi3_causality_enu_structural_parameter
PARAMETER = FMIL3.fmi3_causality_enu_parameter
CALCULATED_PARAMETER = FMIL3.fmi3_causality_enu_calculated_parameter
INPUT = FMIL3.fmi3_causality_enu_input
OUTPUT = FMIL3.fmi3_causality_enu_output
LOCAL = FMIL3.fmi3_causality_enu_local
INDEPENDENT = FMIL3.fmi3_causality_enu_independent
UNKNOWN = FMIL3.fmi3_causality_enu_unknown
class FMI3_DependencyKind(IntEnum):
DEPENDENT = FMIL3.fmi3_dependencies_kind_dependent
CONSTANT = FMIL3.fmi3_dependencies_kind_constant
FIXED = FMIL3.fmi3_dependencies_kind_fixed
TUNABLE = FMIL3.fmi3_dependencies_kind_tunable
DISCRETE = FMIL3.fmi3_dependencies_kind_discrete
# Jacobian approximation
DEF FORWARD_DIFFERENCE = 1
DEF CENTRAL_DIFFERENCE = 2
FORWARD_DIFFERENCE_EPS = (np.finfo(float).eps)**0.5
CENTRAL_DIFFERENCE_EPS = (np.finfo(float).eps)**(1/3.0)
from pyfmi.exceptions import (
FMUException,
InvalidXMLException,
InvalidFMUException,
InvalidBinaryException,
InvalidVersionException,
)
from pyfmi.fmi_base import (
FMI_DEFAULT_LOG_LEVEL,
_handle_load_fmu_exception,
check_fmu_args
)
from pyfmi.common.core import create_temp_dir
# CALLBACKS
cdef void importlogger3(FMIL.jm_callbacks* c, FMIL.jm_string module, FMIL.jm_log_level_enu_t log_level, FMIL.jm_string message):
if c.context != NULL:
(<FMUModelBase3>c.context)._logger(module, log_level, message)
cdef class FMI3ModelVariable:
""" Class defining data structure based on the XML elements of ModelVariables. """
def __init__(self, name, value_reference, data_type, description, variability, causality, alias, initial):
self._name = name
self._value_reference = value_reference
self._type = data_type
self._description = description
self._variability = variability
self._causality = causality
self._initial = initial
self._alias = alias
def _get_name(self):
return self._name
name = property(_get_name)
def _get_alias(self):
return self._alias
alias = property(_get_alias)
def _get_value_reference(self):
return self._value_reference
value_reference = property(_get_value_reference)
def _get_type(self):
return FMI3_Type(self._type)
type = property(_get_type)
def _get_description(self):
return self._description
description = property(_get_description)
def _get_variability(self):
return FMI3_Variability(self._variability)
variability = property(_get_variability)
def _get_causality(self):
return FMI3_Causality(self._causality)
causality = property(_get_causality)
def _get_initial(self):
return FMI3_Initial(self._initial)
initial = property(_get_initial)
cdef class FMI3EventInfo:
""" Class representing data related to event information."""
def __init__(self):
self.newDiscreteStatesNeeded = FMIL3.fmi3_false
self.terminateSimulation = FMIL3.fmi3_false
self.nominalsOfContinuousStatesChanged = FMIL3.fmi3_false
self.valuesOfContinuousStatesChanged = FMIL3.fmi3_false
self.nextEventTimeDefined = FMIL3.fmi3_false
self.nextEventTime = 0.0
cdef class DeclaredType3:
"""
Class defining data structure based on the XML element Type.
"""
def __init__(self, name, description = "", quantity = ""):
self._name = name
self._description = description
self._quantity = quantity
def _get_name(self):
"""
Get the value of the name attribute.
Returns::
The name attribute value as string.
"""
return self._name
name = property(_get_name)
def _get_description(self):
"""
Get the value of the description attribute.
Returns::
The description attribute value as string (empty string if
not set).
"""
return self._description
description = property(_get_description)
cdef class EnumerationType3(DeclaredType3):
"""
Class defining data structure based on the XML element Enumeration.
"""
def __init__(self, name, description = "", quantity = "", items = None):
DeclaredType3.__init__(self, name, description, quantity)
self._items = items
def _get_quantity(self):
"""
Get the quantity of the enumeration type.
Returns::
The quantity as string (empty string if
not set).
"""
return self._quantity
quantity = property(_get_quantity)
def _get_items(self):
"""
Get the items of the enumeration type.
Returns::
The items of the enumeration type as a dict. The key is the
enumeration value and the dict value is a tuple containing
the name and description of the enumeration item.
"""
return self._items
items = property(_get_items)
cdef inline void _check_input_sizes(np.ndarray input_valueref, np.ndarray set_value):
if np.size(input_valueref) != np.size(set_value):
raise FMUException('The length of valueref and values are inconsistent. Note: Array variables are not yet supported')
cdef inline FMIL3.fmi3_import_variable_t* _get_variable_by_name(FMIL3.fmi3_import_t* fmu, str variable_name):
cdef FMIL3.fmi3_import_variable_t* variable
cdef bytes variable_name_bytes = pyfmi_util.encode(variable_name)
cdef char* variablename = variable_name_bytes
variable = FMIL3.fmi3_import_get_variable_by_name(fmu, variablename)
if variable == NULL:
raise FMUException(f"The variable {variable_name} could not be found.")
return variable
cdef inline FMIL3.fmi3_import_variable_t* _get_variable_by_vr(FMIL3.fmi3_import_t* fmu, int valueref):
cdef FMIL3.fmi3_import_variable_t* variable
variable = FMIL3.fmi3_import_get_variable_by_vr(fmu, <FMIL3.fmi3_value_reference_t> valueref)
if variable == NULL:
raise FMUException("The variable with the valuref %i could not be found."%valueref)
return variable
cdef class FMUState3:
""" Class containing a pointer to a FMU-state. """
def __init__(self):
self.fmu_state = NULL
self._internal_state_variables = {'initialized_fmu': None,
'has_entered_init_mode': None,
'time': None,
'callback_log_level': None,
'event_info.new_discrete_states_needed': None,
'event_info.nominals_of_continuous_states_changed': None,
'event_info.terminate_simulation': None,
'event_info.values_of_continuous_states_changed': None,
'event_info.next_event_time_defined': None,
'event_info.next_event_time': None}
cdef class FMUModelBase3(FMI_BASE.ModelBase):
"""
FMI3 Model loaded from a dll.
"""
def __init__(self, fmu: Union[str, Path], log_file_name = None, log_level = FMI_DEFAULT_LOG_LEVEL,
_unzipped_dir = None, _connect_dll = True, allow_unzipped_fmu = False):
"""
Constructor of the model.
Parameters::
fmu --
Path to the FMU.
log_file_name --
Filename for file used to save log messages.
This argument can also be a stream if it supports 'write', for full functionality
it must also support 'seek' and 'readlines'. If the stream requires use of other methods, such as 'drain'
for asyncio-streams, then this needs to be implemented on the user-side, there is no additional methods invoked
on the stream instance after 'write' has been invoked on the PyFMI side.
The stream must also be open and writable during the entire time.
Default: None = Generates automatically as <model_identifier>_log.txt
log_level --
Determines the logging output. Can be set between 0
(no logging) and 7 (everything).
Default: 2 (log error messages)
allow_unzipped_fmu --
If set to True, the argument 'fmu' can be a path specifying a directory
to an unzipped FMU. The structure of the unzipped FMU must conform
to the FMI specification.
Default: False
Returns::
A model as an object from the class FMUModelFMU3
"""
logging.warning("FMI3 support is experimental.")
# Call super
FMI_BASE.ModelBase.__init__(self)
# Contains the log information
self._log = []
# Used for deallocation
self._initialized_fmu = 0
self._allocated_fmu = 0
self._allocated_dll = 0
self._allocated_context = 0
self._allocated_xml = 0
self._fmu_temp_dir = NULL
self._fmu_log_name = NULL
# Used to adjust behavior if FMU is unzipped
self._allow_unzipped_fmu = 1 if allow_unzipped_fmu else 0
# Default values
self._t = None
self._last_accepted_time = 0.0
# Caching
self._states_references = None
self._derivatives_references = None
self._inputs_references = None
self._outputs_references = None
self._outputs_states_dependencies = None
self._outputs_inputs_dependencies = None
self._outputs_states_dependencies_kind = None
self._outputs_inputs_dependencies_kind = None
self._derivatives_states_dependencies = None
self._derivatives_inputs_dependencies = None
self._derivatives_states_dependencies_kind = None
self._derivatives_inputs_dependencies_kind = None
self._group_A = None
self._group_B = None
self._group_C = None
self._group_D = None
# Internal values
self._enable_logging = False
self._eventInfo = FMI3EventInfo()
self._worker_object = _WorkerClass3()
# Specify the general callback functions
self.callbacks.malloc = FMIL.malloc
self.callbacks.calloc = FMIL.calloc
self.callbacks.realloc = FMIL.realloc
self.callbacks.free = FMIL.free
self.callbacks.logger = importlogger3
self.callbacks.context = <void*>self
self._setup_log_state(log_level)
self._loaded_with_log_level = log_level
fmu = os.path.abspath(fmu)
self._fmu_full_path = pyfmi_util.encode(fmu)
check_fmu_args(self._allow_unzipped_fmu, fmu, self._fmu_full_path)
# Create a struct for allocation
self._context = FMIL.fmi_import_allocate_context(&self.callbacks)
self._allocated_context = 1
# Get the FMI version of the provided model
if _unzipped_dir:
fmu_temp_dir = pyfmi_util.encode(_unzipped_dir)
elif self._allow_unzipped_fmu:
fmu_temp_dir = pyfmi_util.encode(fmu)
else:
fmu_temp_dir = pyfmi_util.encode(create_temp_dir())
fmu_temp_dir = os.path.abspath(fmu_temp_dir)
self._fmu_temp_dir = <char*>FMIL.malloc((FMIL.strlen(fmu_temp_dir)+1)*sizeof(char))
FMIL.strcpy(self._fmu_temp_dir, fmu_temp_dir)
if _unzipped_dir:
# If the unzipped directory is provided we assume that the version
# is correct. This is due to that the method to get the version
# unzips the FMU which we already have done.
self._version = FMIL.fmi_version_3_0_enu
else:
self._version = FMI_BASE.import_and_get_version(self._context, self._fmu_full_path,
fmu_temp_dir, self._allow_unzipped_fmu)
# Check the version
if self._version == FMIL.fmi_version_unknown_enu:
last_error = pyfmi_util.decode(FMIL.jm_get_last_error(&self.callbacks))
if self._enable_logging:
raise InvalidVersionException("The FMU could not be loaded. The FMU version could not be determined. " + last_error)
else:
raise InvalidVersionException("The FMU could not be loaded. The FMU version could not be determined. Enable logging for possibly more information.")
elif self._version != FMIL.fmi_version_3_0_enu:
last_error = pyfmi_util.decode(FMIL.jm_get_last_error(&self.callbacks))
if self._enable_logging:
raise InvalidVersionException("The FMU could not be loaded. The FMU version is not supported by this class. " + last_error)
else:
raise InvalidVersionException("The FMU could not be loaded. The FMU version is not supported by this class. Enable logging for possibly more information.")
# Parse xml and check fmu-kind
self._fmu = FMIL3.fmi3_import_parse_xml(self._context, self._fmu_temp_dir, NULL)
if self._fmu is NULL:
last_error = pyfmi_util.decode(FMIL.jm_get_last_error(&self.callbacks))
if self._enable_logging:
raise InvalidXMLException("The FMU could not be loaded. The model data from 'modelDescription.xml' within the FMU could not be read. " + last_error)
else:
raise InvalidXMLException("The FMU could not be loaded. The model data from 'modelDescription.xml' within the FMU could not be read. Enable logging for possible more information.")
self._fmu_kind = FMIL3.fmi3_import_get_fmu_kind(self._fmu)
self._allocated_xml = 1
# FMU kind is unknown
if self._fmu_kind & FMIL3.fmi3_fmu_kind_unknown:
last_error = pyfmi_util.decode(FMIL.jm_get_last_error(&self.callbacks))
if self._enable_logging:
raise InvalidVersionException("The FMU could not be loaded. The FMU kind could not be determined. " + last_error)
else:
raise InvalidVersionException("The FMU could not be loaded. The FMU kind could not be determined. Enable logging for possibly more information.")
else:
self._fmu_kind = self._get_fmu_kind()
# Connect the DLL
if _connect_dll:
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_create_dllfmu(self._fmu, self._fmu_kind, <FMIL3.fmi3_instance_environment_t>self._fmu, FMIL3.fmi3_log_forwarding)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status == FMIL.jm_status_error:
last_error = pyfmi_util.decode(FMIL3.fmi3_import_get_last_error(self._fmu))
if self._enable_logging:
raise InvalidBinaryException("The FMU could not be loaded. Error loading the binary. " + last_error)
else:
raise InvalidBinaryException("The FMU could not be loaded. Error loading the binary. Enable logging for possibly more information.")
self._allocated_dll = 1
# Note that below, values are retrieved from XML (via FMIL) if .dll/.so is not connected
self._modelId = self.get_identifier()
self._modelName = pyfmi_util.decode(FMIL3.fmi3_import_get_model_name(self._fmu))
if log_file_name is None:
log_file_name = self._get_default_log_file_name()
# TODO: The code below is identical between FMUModelBase2 and FMUModelBase3, perhaps we can refactor this
if not isinstance(log_file_name, (str, Path)):
self._set_log_stream(log_file_name)
for i in range(len(self._log)):
self._log_stream.write(
"FMIL: module = %s, log level = %d: %s\n" % (
self._log[i][0], self._log[i][1], self._log[i][2]
)
)
else:
log_file_name = str(log_file_name) # convert e.g. pathlib.Path objects
fmu_log_name = pyfmi_util.encode(log_file_name)
self._fmu_log_name = <char*>FMIL.malloc((FMIL.strlen(fmu_log_name)+1)*sizeof(char))
FMIL.strcpy(self._fmu_log_name, fmu_log_name)
# Create the log file
with open(self._fmu_log_name,'w') as file:
for i in range(len(self._log)):
file.write("FMIL: module = %s, log level = %d: %s\n" % (
self._log[i][0], self._log[i][1], self._log[i][2]
)
)
self._log = []
self._event_info_new_discrete_states_needed = FMIL3.fmi3_false
self._event_info_terminate_simulation = FMIL3.fmi3_false
self._event_info_nominals_of_continuous_states_changed = FMIL3.fmi3_false
self._event_info_values_of_continuous_states_changed = FMIL3.fmi3_true
self._event_info_next_event_time_defined = FMIL3.fmi3_false
self._event_info_next_event_time = 0.0
def _setup_log_state(self, log_level):
if isinstance(log_level, int) and (log_level >= FMIL.jm_log_level_nothing and log_level <= FMIL.jm_log_level_all):
self._enable_logging = log_level != FMIL.jm_log_level_nothing
self.callbacks.log_level = log_level
else:
raise FMUException(f"The log level must be an integer between {FMIL.jm_log_level_nothing} and {FMIL.jm_log_level_all}")
def __dealloc__(self):
""" Deallocate allocated memory. """
self._invoked_dealloc = 1
if self._initialized_fmu == 1:
FMIL3.fmi3_import_terminate(self._fmu)
if self._allocated_fmu == 1:
FMIL3.fmi3_import_free_instance(self._fmu)
if self._allocated_dll == 1:
FMIL3.fmi3_import_destroy_dllfmu(self._fmu)
if self._allocated_xml == 1:
FMIL3.fmi3_import_free(self._fmu)
if self._allocated_context == 1:
FMIL.fmi_import_free_context(self._context)
if self._fmu_temp_dir != NULL:
if not self._allow_unzipped_fmu:
FMIL.fmi_import_rmdir(&self.callbacks, self._fmu_temp_dir)
FMIL.free(self._fmu_temp_dir)
self._fmu_temp_dir = NULL
if self._fmu_log_name != NULL:
FMIL.free(self._fmu_log_name)
self._fmu_log_name = NULL
if self._log_stream:
self._log_stream = None
def initialize(
self,
tolerance_defined=True,
tolerance="Default",
start_time="Default",
stop_time_defined=False,
stop_time="Default"
):
"""
Initializes the model and computes initial values for all variables.
Args:
tolerance_defined --
Specifies if the model is to be solved with an error
controlled algorithm.
Default: True
tolerance --
The tolerance used by the error controlled algorithm.
Default: The tolerance defined in the model description
start_time --
Start time of the simulation.
Default: The start time defined in the model description.
stop_time_defined --
Defines if a fixed stop time is defined or not. If this is
set the simulation cannot go past the defined stop time.
Default: False
stop_time --
Stop time of the simulation.
Default: The stop time defined in the model description.
Calls the low-level FMI functions: fmi3EnterInitializationMode,
fmi3ExitInitializationMode
"""
log_open = self._log_open()
if not log_open and self.get_log_level() > 2:
self._open_log_file()
try:
self.enter_initialization_mode(
tolerance_defined,
tolerance,
start_time,
stop_time_defined,
stop_time
)
self.exit_initialization_mode()
finally:
if not log_open and self.get_log_level() > 2:
self._close_log_file()
self._initialized_fmu = 1
def enter_initialization_mode(
self,
tolerance_defined=True,
tolerance="Default",
start_time="Default",
stop_time_defined=False,
stop_time="Default"
):
""" Enters initialization mode by calling the low level FMI function fmi3EnterInitializationMode.
Note that the method initialize() performs both the enter and exit of initialization mode.
Args:
For a full description of the input arguments, see the docstring for method 'initialize'.
"""
cdef FMIL3.fmi3_status_t status
cdef FMIL3.fmi3_boolean_t stop_defined = FMIL3.fmi3_true if stop_time_defined else FMIL3.fmi3_false
cdef FMIL3.fmi3_boolean_t tol_defined = FMIL3.fmi3_true if tolerance_defined else FMIL3.fmi3_false
if tolerance == "Default":
tolerance = self.get_default_experiment_tolerance()
if start_time == "Default":
start_time = self.get_default_experiment_start_time()
if stop_time == "Default":
stop_time = self.get_default_experiment_stop_time()
self._t = start_time
self._last_accepted_time = start_time
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_enter_initialization_mode(
self._fmu,
tol_defined,
tolerance,
start_time,
stop_defined,
stop_time
)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status != FMIL3.fmi3_status_ok:
raise FMUException("Failed to enter initialization mode")
self._has_entered_init_mode = True
def exit_initialization_mode(self):
"""
Exit initialization mode by calling the low level FMI function
fmi3ExitInitializationMode.
Note that the method initialize() performs both the enter and
exit of initialization mode.
"""
cdef FMIL3.fmi3_status_t status
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_exit_initialization_mode(self._fmu)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status != FMIL3.fmi3_status_ok:
raise FMUException("Failed to exit initialization mode")
def get_variable_declared_type(self, variable_name):
"""
Return the given variables declared type.
Parameters::
variable_name --
The name of the variable.
Returns::
The declared type.
"""
cdef int item_value
cdef unsigned int enum_size
cdef FMIL3.fmi3_base_type_enu_t basetype
cdef FMIL3.fmi3_import_variable_t* variable
cdef FMIL3.fmi3_import_variable_typedef_t* variable_type
cdef FMIL3.fmi3_import_enumeration_typedef_t * enumeration_type
cdef FMIL3.fmi3_string_t type_name
cdef FMIL3.fmi3_string_t type_desc
cdef FMIL3.fmi3_string_t type_quantity
cdef FMIL3.fmi3_string_t item_desc
cdef FMIL3.fmi3_string_t item_name
variable_name_bytes = pyfmi_util.encode(variable_name)
cdef char* variablename = variable_name_bytes
variable = FMIL3.fmi3_import_get_variable_by_name(self._fmu, variablename)
if variable == NULL:
raise FMUException("The variable %s could not be found."%variable_name)
variable_type = FMIL3.fmi3_import_get_variable_declared_type(variable)
if variable_type == NULL:
raise FMUException("The variable %s does not have a declared type."%variable_name)
type_name = <FMIL3.fmi3_string_t>FMIL3.fmi3_import_get_type_name(variable_type)
type_desc = <FMIL3.fmi3_string_t>FMIL3.fmi3_import_get_type_description(variable_type)
type_quantity = <FMIL3.fmi3_string_t>FMIL3.fmi3_import_get_type_quantity(variable_type)
basetype = FMIL3.fmi3_import_get_variable_base_type(variable)
if basetype == FMIL3.fmi3_base_type_enum:
enumeration_type = FMIL3.fmi3_import_get_type_as_enum(variable_type)
enum_size = FMIL3.fmi3_import_get_enum_type_size(enumeration_type)
items = {}
for i in range(1, enum_size + 1):
item_value = FMIL3.fmi3_import_get_enum_type_item_value(enumeration_type, i)
item_name = <FMIL3.fmi3_string_t>FMIL3.fmi3_import_get_enum_type_item_name(enumeration_type, i)
item_desc = <FMIL3.fmi3_string_t>FMIL3.fmi3_import_get_enum_type_item_description(enumeration_type, i)
items[item_value] = (
pyfmi_util.decode(item_name) if item_name != NULL else "",
pyfmi_util.decode(item_desc) if item_desc != NULL else ""
)
return EnumerationType3(
pyfmi_util.decode(type_name) if type_name != NULL else "",
pyfmi_util.decode(type_desc) if type_desc != NULL else "",
pyfmi_util.decode(type_quantity) if type_quantity != NULL else "", items
)
else:
raise NotImplementedError
def terminate(self):
""" Calls the FMI function fmi3Terminate() on the FMU.
After this call, any call to a function changing the state of the FMU will fail.
"""
cdef FMIL3.fmi3_status_t status
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_terminate(self._fmu)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status != 0:
raise FMUException("Termination of FMU failed, see log for possible more information.")
def free_instance(self):
""" Calls the FMI function fmi3FreeInstance() on the FMU. Note that this is not needed generally. """
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
FMIL3.fmi3_import_free_instance(self._fmu)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
def reset(self):
""" Resets the FMU back to its original state. Note that the environment
has to initialize the FMU again after this function-call.
"""
cdef FMIL3.fmi3_status_t status
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_reset(self._fmu)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status != 0:
raise FMUException('An error occured when resetting the model, see the log for possible more information')
# Default values
self._t = None
self._has_entered_init_mode = False
# Reseting the allocation flags
self._initialized_fmu = 0
# Internal values
self._eventInfo = FMI3EventInfo()
self._log = []
self._setup_log_state(self._loaded_with_log_level)
super().reset()
def _get_fmu_kind(self):
raise FMUException("FMUModelBase3 cannot be used directly, use FMUModelME3.")
def instantiate(self, name: str = 'Model', visible: bool = False) -> None:
raise NotImplementedError # to implemented in FMUModel(ME|CS|SE)3
def _set(self, variable_name, value):
"""
Helper method to set, see docstring on set.
"""
cdef FMIL3.fmi3_value_reference_t ref
ref = self.get_variable_valueref(variable_name)
basetype: FMI3_Type = self.get_variable_data_type(variable_name)
if basetype is FMI3_Type.FLOAT64:
self.set_float64([ref], [value])
elif basetype is FMI3_Type.FLOAT32:
self.set_float32([ref], [value])
elif basetype is FMI3_Type.INT64:
self.set_int64([ref], [value])
elif basetype is FMI3_Type.INT32:
self.set_int32([ref], [value])
elif basetype is FMI3_Type.INT16:
self.set_int16([ref], [value])
elif basetype is FMI3_Type.INT8:
self.set_int8([ref], [value])
elif basetype is FMI3_Type.UINT64:
self.set_uint64([ref], [value])
elif basetype is FMI3_Type.UINT32:
self.set_uint32([ref], [value])
elif basetype is FMI3_Type.UINT16:
self.set_uint16([ref], [value])
elif basetype is FMI3_Type.UINT8:
self.set_uint8([ref], [value])
elif basetype is FMI3_Type.BOOL:
self.set_boolean([ref], [value])
elif basetype is FMI3_Type.STRING:
self.set_string([ref], [value])
elif basetype is FMI3_Type.ENUM:
self.set_enum([ref], [value])
else:
raise FMUException('Type not supported.')
cpdef set_float64(self, valueref, values):
"""
Sets the float64-values in the FMU as defined by the value reference(s).
Parameters::
valueref --
A list of value references.
values --
Values to be set.
Example::
model.set_float64([234, 235],[2.34, 10.4])
Calls the low-level FMI function: fmi3SetFloat64
"""
cdef int status
cdef np.ndarray[FMIL3.fmi3_value_reference_t, ndim=1, mode='c'] input_valueref = np.asarray(valueref, dtype = np.uint32).ravel()
cdef np.ndarray[FMIL3.fmi3_float64_t, ndim=1, mode='c'] set_value = np.asarray(values, dtype = np.double).ravel()
_check_input_sizes(input_valueref, set_value)
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_set_float64(
self._fmu,
<FMIL3.fmi3_value_reference_t*> input_valueref.data,
np.size(input_valueref),
<FMIL3.fmi3_float64_t*> set_value.data,
np.size(set_value)
)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status != 0:
raise FMUException('Failed to set the Float64 values. See the log for possibly more information.')
cdef FMIL3.fmi3_status_t _set_float64(self, FMIL3.fmi3_value_reference_t* vrefs, FMIL3.fmi3_float64_t* values, size_t _size):
"""Internal method for efficient setting of float64 variables."""
cdef FMIL3.fmi3_status_t status
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
# XXX: arrays?
status = FMIL3.fmi3_import_set_float64(self._fmu, vrefs, _size, values, _size)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
return status
cpdef set_float32(self, valueref, values):
"""
Sets the float32-values in the FMU as defined by the value reference(s).
Parameters::
valueref --
A list of value references.
values --
Values to be set.
Example::
model.set_float32([234, 235],[2.34, 10.4])
Calls the low-level FMI function: fmi3SetFloat32
"""
cdef int status
cdef np.ndarray[FMIL3.fmi3_value_reference_t, ndim=1, mode='c'] input_valueref = np.asarray(valueref, dtype = np.uint32).ravel()
cdef np.ndarray[FMIL3.fmi3_float32_t, ndim=1, mode='c'] set_value = np.asarray(values, dtype = np.float32).ravel()
_check_input_sizes(input_valueref, set_value)
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_set_float32(
self._fmu,
<FMIL3.fmi3_value_reference_t*> input_valueref.data,
np.size(input_valueref),
<FMIL3.fmi3_float32_t*> set_value.data,
np.size(set_value)
)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status != 0:
raise FMUException('Failed to set the Float32 values. See the log for possibly more information.')
cpdef set_int64(self, valueref, values):
"""
Sets the int64-values in the FMU as defined by the value reference(s).
Parameters::
valueref --
A list of value references.
values --
Values to be set.
Example::
model.set_int64([234, 235],[2, 10])
Calls the low-level FMI function: fmi3SetInt64
"""
cdef int status
cdef np.ndarray[FMIL3.fmi3_value_reference_t, ndim=1, mode='c'] input_valueref = np.asarray(valueref, dtype = np.uint32).ravel()
cdef np.ndarray[FMIL3.fmi3_int64_t, ndim=1, mode='c'] set_value = np.asarray(values, dtype = np.int64).ravel()
_check_input_sizes(input_valueref, set_value)
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_set_int64(
self._fmu,
<FMIL3.fmi3_value_reference_t*> input_valueref.data,
np.size(input_valueref),
<FMIL3.fmi3_int64_t*> set_value.data,
np.size(set_value)
)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status != 0:
raise FMUException('Failed to set the Int64 values. See the log for possibly more information.')
cpdef set_int32(self, valueref, values):
"""
Sets the int32-values in the FMU as defined by the value reference(s).
Parameters::
valueref --
A list of value references.
values --
Values to be set.
Example::
model.set_int32([234, 235],[2, 10])
Calls the low-level FMI function: fmi3SetInt32
"""
cdef int status
cdef np.ndarray[FMIL3.fmi3_value_reference_t, ndim=1, mode='c'] input_valueref = np.asarray(valueref, dtype = np.uint32).ravel()
cdef np.ndarray[FMIL3.fmi3_int32_t, ndim=1, mode='c'] set_value = np.asarray(values, dtype = np.int32).ravel()
_check_input_sizes(input_valueref, set_value)
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_set_int32(
self._fmu,
<FMIL3.fmi3_value_reference_t*> input_valueref.data,
np.size(input_valueref),
<FMIL3.fmi3_int32_t*> set_value.data,
np.size(set_value)
)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status != 0:
raise FMUException('Failed to set the Int32 values. See the log for possibly more information.')
cpdef set_int16(self, valueref, values):
"""
Sets the int16-values in the FMU as defined by the value reference(s).
Parameters::
valueref --
A list of value references.
values --
Values to be set.
Example::
model.set_int16([234, 235],[2, 10])
Calls the low-level FMI function: fmi3SetInt16
"""
cdef int status
cdef np.ndarray[FMIL3.fmi3_value_reference_t, ndim=1, mode='c'] input_valueref = np.asarray(valueref, dtype = np.uint32).ravel()
cdef np.ndarray[FMIL3.fmi3_int16_t, ndim=1, mode='c'] set_value = np.asarray(values, dtype = np.int16).ravel()
_check_input_sizes(input_valueref, set_value)
self._log_handler.capi_start_callback(self._max_log_size_msg_sent, self._current_log_size)
status = FMIL3.fmi3_import_set_int16(
self._fmu,
<FMIL3.fmi3_value_reference_t*> input_valueref.data,
np.size(input_valueref),
<FMIL3.fmi3_int16_t*> set_value.data,
np.size(set_value)
)
self._log_handler.capi_end_callback(self._max_log_size_msg_sent, self._current_log_size)
if status != 0:
raise FMUException('Failed to set the Int16 values. See the log for possibly more information.')
cpdef set_int8(self, valueref, values):
"""
Sets the int8-values in the FMU as defined by the value reference(s).
Parameters::
valueref --
A list of value references.
values --
Values to be set.
Example::
model.set_int8([234, 235],[2, 10])
Calls the low-level FMI function: fmi3SetInt8