-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathtest_fmi3.py
More file actions
1669 lines (1419 loc) · 72.3 KB
/
Copy pathtest_fmi3.py
File metadata and controls
1669 lines (1419 loc) · 72.3 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 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import logging
from io import StringIO
from pathlib import Path
import contextlib
import pytest
import numpy as np
import scipy.sparse as sps
from pyfmi import load_fmu
from pyfmi.fmi import (
FMUModelME3,
FMUModelCS3,
FMI_OK,
)
from pyfmi.fmi3 import (
FMI3_Type,
FMI3_Causality,
FMI3_Variability,
FMI3_Initial,
FMI3_DependencyKind,
FMI3EventInfo,
)
from pyfmi.exceptions import (
FMUException,
InvalidFMUException,
InvalidVersionException
)
from tests.utils import _get_fmu, get_fmi3_reference_fmu
this_dir = Path(__file__).parent
FMI3_REF_FMU_PATH = Path(this_dir) / 'files' / 'reference_fmus' / '3.0'
# TODO: A lot of the tests here could be parameterized with the tests in test_fmi.py
# This would however require one of the following:
# a) Changing the tests in test_fmi.py to use the FMI1/2 reference FMUs
# b) Mocking the FMUs in some capacity
NUMPY_MAJOR_VERSION = int(np.__version__[0])
OVERFLOW_TEST_SET = [ # parameters for overflow testing
("Int32_input", 2_147_483_650),
("Int32_input", -2_147_483_650),
("Int16_input", 32_770),
("Int16_input", -32_770),
("Int8_input", 200),
("Int8_input", -200),
("UInt64_input", -1),
("UInt32_input", 4_294_967_300),
("UInt32_input", -1),
("UInt16_input", 65_540),
("UInt16_input", -1),
("UInt8_input", 260),
("UInt8_input", -1),
]
@contextlib.contextmanager
def temp_dir_context(tmpdir):
"""Provides a temporary directory as a context."""
yield Path(tmpdir)
class FMUModelME3MockGetFloat(FMUModelME3):
"""Auxiliary class mocking get_float32|64 for display value tests."""
def get_float32(self, vr):
return np.array([0.]*len(vr))
def get_float64(self, vr):
return np.array([0.]*len(vr))
class TestFMI3LoadFMU:
"""Basic unit tests for FMI3 loading via 'load_fmu'."""
@pytest.mark.parametrize("ref_fmu", [
FMI3_REF_FMU_PATH / "BouncingBall.fmu",
FMI3_REF_FMU_PATH / "Dahlquist.fmu",
FMI3_REF_FMU_PATH / "Resource.fmu",
FMI3_REF_FMU_PATH / "StateSpace.fmu",
FMI3_REF_FMU_PATH / "Feedthrough.fmu",
FMI3_REF_FMU_PATH / "Stair.fmu",
FMI3_REF_FMU_PATH / "VanDerPol.fmu",
])
def test_load_kind_auto(self, caplog, ref_fmu):
"""Test loading a ME FMU via kind 'auto'"""
caplog.set_level(logging.WARNING)
fmu = load_fmu(ref_fmu, kind = "auto")
assert isinstance(fmu, FMUModelME3)
experimental_msg = "FMI3 support is experimental."
assert any(experimental_msg in msg for msg in caplog.messages)
@pytest.mark.parametrize("ref_fmu", [FMI3_REF_FMU_PATH / "Clocks.fmu"])
def test_load_kind_auto_SE(self, ref_fmu):
"""Test loading a SE only FMU via kind 'auto'"""
msg = "Import of FMI3 Scheduled Execution FMUs is not supported"
with pytest.raises(InvalidFMUException, match = re.escape(msg)):
load_fmu(ref_fmu, kind = "auto")
@pytest.mark.parametrize("ref_fmu", [FMI3_REF_FMU_PATH / "VanDerPol.fmu"])
def test_load_kind_ME(self, ref_fmu):
"""Test loading an FMU with kind 'ME'"""
fmu = load_fmu(ref_fmu, kind = "ME")
assert isinstance(fmu, FMUModelME3)
def test_get_event_info_1(self,):
"""Test get_event_info() works as expected; no event."""
fmu = get_fmi3_reference_fmu("VanDerPol")
fmu.initialize()
fmu.event_update()
event_info = fmu.get_event_info()
assert isinstance(event_info, FMI3EventInfo)
assert not event_info.newDiscreteStatesNeeded
assert not event_info.terminateSimulation
assert not event_info.nominalsOfContinuousStatesChanged
assert not event_info.valuesOfContinuousStatesChanged
assert not event_info.nextEventTimeDefined
assert event_info.nextEventTime == pytest.approx(0.0) # Could be anything really though
def test_get_event_info_2(self):
"""Test get_event_info() works as expected; time events."""
fmu = get_fmi3_reference_fmu("Stair")
fmu.initialize()
fmu.event_update()
event_info = fmu.get_event_info()
assert isinstance(event_info, FMI3EventInfo)
assert not event_info.newDiscreteStatesNeeded
assert not event_info.terminateSimulation
assert not event_info.nominalsOfContinuousStatesChanged
assert not event_info.valuesOfContinuousStatesChanged
assert event_info.nextEventTimeDefined
assert event_info.nextEventTime == pytest.approx(1.0)
@pytest.mark.parametrize("ref_fmu", [FMI3_REF_FMU_PATH / "VanDerPol.fmu"])
def test_load_kind_CS(self, ref_fmu):
"""Test loading an FMU with kind 'CS'"""
load_fmu(ref_fmu, kind = "CS")
@pytest.mark.parametrize("ref_fmu", [FMI3_REF_FMU_PATH / "Clocks.fmu"])
def test_load_kind_SE(self, ref_fmu):
"""Test loading an FMU with kind 'SE'"""
msg = "Import of FMI3 Scheduled Execution FMUs is not supported."
with pytest.raises(FMUException, match = re.escape(msg)):
load_fmu(ref_fmu, kind = "SE")
def test_get_model_identifier(self):
"""Test that model identifier is retrieved as expected."""
fmu = get_fmi3_reference_fmu("VanDerPol")
assert fmu.get_identifier() == 'VanDerPol'
def test_get_version(self):
"""Test that FMI version is retrieved as expected."""
fmu = get_fmi3_reference_fmu("VanDerPol")
assert fmu.get_version() == '3.0'
def test_instantiation(self, tmpdir):
""" Test that instantiation works by verifying the output in the log."""
with temp_dir_context(tmpdir) as temp_path:
# log_level set to 5 required by test
fmu = load_fmu(FMI3_REF_FMU_PATH / "VanDerPol.fmu", log_level=5)
substring_to_find = 'Successfully loaded all the interface functions'
assert any(substring_to_find in line for line in fmu.get_log())
@pytest.mark.parametrize("ref_fmu", [
"BouncingBall",
"Dahlquist",
"Resource",
"StateSpace",
"Feedthrough",
"Stair",
"VanDerPol",
])
def test_initialize_reset_terminate(self, ref_fmu):
"""Test initialize, reset and terminate of all the ME reference FMUs. """
fmu = get_fmi3_reference_fmu(ref_fmu)
# Should simply pass without any exceptions
fmu.initialize()
fmu.reset()
# Test initialize again after resetting followed by terminate,
# since terminating does not require reset.
fmu.initialize()
fmu.terminate()
@pytest.mark.parametrize("ref_fmu", [
"BouncingBall",
"Dahlquist",
"Resource",
"StateSpace",
"Feedthrough",
"Stair",
"VanDerPol",
])
def test_enter_continuous_time_mode(self, ref_fmu):
"""Test entering continuous time mode. """
fmu = get_fmi3_reference_fmu(ref_fmu)
# Should simply pass without any exceptions
fmu.initialize()
fmu.enter_continuous_time_mode()
fmu.terminate()
@pytest.mark.parametrize("ref_fmu", [
"BouncingBall",
"Dahlquist",
"Resource",
"StateSpace",
"Feedthrough",
"Stair",
"VanDerPol",
])
def test_enter_event_mode(self, ref_fmu):
"""Test enter event mode. """
fmu = get_fmi3_reference_fmu(ref_fmu)
# Should simply pass without any exceptions
fmu.initialize()
fmu.enter_continuous_time_mode()
fmu.enter_event_mode()
fmu.terminate()
@pytest.mark.parametrize("ref_fmu", [
"BouncingBall",
"Dahlquist",
"Resource",
"StateSpace",
"Feedthrough",
"Stair",
"VanDerPol",
])
def test_initialize_manually(self, ref_fmu):
"""Test initialize all the ME reference FMUs by entering/exiting initialization mode manually. """
fmu = get_fmi3_reference_fmu(ref_fmu)
assert fmu.time is None
# Should simply pass without any exceptions
fmu.enter_initialization_mode()
fmu.exit_initialization_mode()
assert fmu.time == 0.0
def test_get_double_terminate(self):
"""Test invalid call sequence raises an error. """
fmu = get_fmi3_reference_fmu("VanDerPol")
fmu.initialize()
fmu.terminate()
msg = "Termination of FMU failed, see log for possible more information."
with pytest.raises(FMUException, match = msg):
fmu.terminate()
def test_free_instance_after_load(self):
"""Test invoke free instance after loading. """
fmu = load_fmu(FMI3_REF_FMU_PATH / "VanDerPol.fmu")
fmu.free_instance()
def test_free_instance_after_initialization(self):
"""Test invoke free instance after initialization. """
fmu = load_fmu(FMI3_REF_FMU_PATH / "VanDerPol.fmu")
fmu.initialize()
fmu.free_instance()
def test_get_states_list(self):
"""Test retrieving states list and check its attributes. """
fmu = get_fmi3_reference_fmu("VanDerPol")
states = fmu.get_states_list()
assert len(states) == 2
x0 = states['x0']
x1 = states['x1']
assert x0.description == 'the first state'
assert x1.description == 'the second state'
assert x0.type == FMI3_Type.FLOAT64
assert x1.type == FMI3_Type.FLOAT64
assert x0.causality is FMI3_Causality.OUTPUT
assert x1.causality is FMI3_Causality.OUTPUT
assert x0.variability is FMI3_Variability.CONTINUOUS
assert x1.variability is FMI3_Variability.CONTINUOUS
assert x0.value_reference == 1
assert x1.value_reference == 3
assert x0.initial is FMI3_Initial.EXACT
assert x1.initial is FMI3_Initial.EXACT
def test_get_states_list_no_states(self):
"""Test retrieving states list for model without states. """
fmu = get_fmi3_reference_fmu("Stair")
assert len(fmu.get_states_list()) == 0
def test_get_derivatives_list(self):
"""Test retrieving derivatives list and check its attributes. """
fmu = get_fmi3_reference_fmu("VanDerPol")
derivatives = fmu.get_derivatives_list()
assert len(derivatives) == 2
derx0 = derivatives['der(x0)']
derx1 = derivatives['der(x1)']
assert derx0.description == ''
assert derx1.description == ''
assert derx0.type == FMI3_Type.FLOAT64
assert derx1.type == FMI3_Type.FLOAT64
assert derx0.causality is FMI3_Causality.LOCAL
assert derx1.causality is FMI3_Causality.LOCAL
assert derx0.variability is FMI3_Variability.CONTINUOUS
assert derx1.variability is FMI3_Variability.CONTINUOUS
assert derx0.value_reference == 2
assert derx1.value_reference == 4
assert derx0.initial is FMI3_Initial.CALCULATED
assert derx1.initial is FMI3_Initial.CALCULATED
def test_get_derivatives_list_no_states(self):
"""Test retrieving derivatives list for model without derivatives. """
fmu = get_fmi3_reference_fmu("Stair")
assert len(fmu.get_derivatives_list()) == 0
def test_get_relative_tolerance(self):
"""Test get_relative_tolerance(). """
fmu = get_fmi3_reference_fmu("VanDerPol")
assert fmu.get_relative_tolerance() == 0.0001
def test_get_absolute_tolerances(self):
"""Test get_absolute_tolerances(). """
fmu = get_fmi3_reference_fmu("VanDerPol")
fmu.initialize()
np.testing.assert_array_almost_equal(fmu.get_absolute_tolerances(), np.array([1e-6, 1e-6]))
def test_get_tolerances(self):
"""Test get_tolerances(). """
fmu = get_fmi3_reference_fmu("VanDerPol")
fmu.initialize()
tolerances = fmu.get_tolerances()
assert tolerances[0] == 0.0001
assert tolerances[0] == fmu.get_relative_tolerance()
np.testing.assert_array_almost_equal(tolerances[1], np.array([1e-6, 1e-6]))
def test_get_tolerances_exception(self):
"""Test that FMUException is raised if FMU is not initialized before get_tolerances()."""
fmu = get_fmi3_reference_fmu("VanDerPol")
msg = "Unable to retrieve the absolute tolerance, FMU needs to be initialized."
with pytest.raises(FMUException, match = msg):
fmu.get_tolerances()
def test_get_and_set_states(self):
"""Test get and set of states."""
fmu = get_fmi3_reference_fmu("VanDerPol")
assert fmu.get('x0') == np.array([2.])
fmu.set('x0', 3.0)
assert fmu.get('x0') == np.array([3.])
assert fmu.get('x1') == np.array([0.])
fmu.set('x1', 1.12)
assert fmu.get('x1') == np.array([1.12])
def test_get_derivatives_with_states_set(self):
"""Test retrieve derivatives, verify values combined with setting of states."""
fmu = get_fmi3_reference_fmu("VanDerPol")
fmu.initialize()
# Note:
# M(x0) = 2;
# M(x1) = 0;
# M(mu) = 1;
# M(der_x0) = M(x1);
# M(der_x1) = M(mu) * ((1.0 - M(x0) * M(x0)) * M(x1)) - M(x0);
assert all(fmu.get_derivatives() == np.array([0., -2.]))
fmu.set('x0', 5)
assert all(fmu.get_derivatives() == np.array([0., -5.]))
fmu.set('x1', 1)
assert all(fmu.get_derivatives() == np.array([1, -29]))
def test_get_description(self):
"""Test get descriptions."""
fmu = get_fmi3_reference_fmu("VanDerPol")
assert fmu.get_variable_description('x0') == 'the first state'
assert fmu.get_variable_description('x1') == 'the second state'
assert fmu.get_variable_description('mu') == ''
def test_get_description_variable_not_found(self):
"""Test get description on a variable that does not exist."""
fmu = get_fmi3_reference_fmu("VanDerPol")
with pytest.raises(FMUException, match = "The variable idontexist could not be found."):
fmu.get_variable_description('idontexist')
def test_get_model_variables(self):
""" Test get_model_variables with default arguments. """
fmu = get_fmi3_reference_fmu("VanDerPol")
variables = fmu.get_model_variables()
assert len(variables) == 6
v = variables['time']
assert v.description == 'Simulation time'
assert v.name == 'time'
assert v.value_reference == 0
assert v.causality is FMI3_Causality.INDEPENDENT
assert v.initial is FMI3_Initial.UNKNOWN
assert v.type is FMI3_Type.FLOAT64
assert v.variability is FMI3_Variability.CONTINUOUS
v = variables['x0']
assert v.description == 'the first state'
assert v.name == 'x0'
assert v.value_reference == 1
assert v.causality is FMI3_Causality.OUTPUT
assert v.initial is FMI3_Initial.EXACT
assert v.type is FMI3_Type.FLOAT64
assert v.variability is FMI3_Variability.CONTINUOUS
v = variables['der(x0)']
assert v.description == ''
assert v.name == 'der(x0)'
assert v.value_reference == 2
assert v.causality is FMI3_Causality.LOCAL
assert v.initial is FMI3_Initial.CALCULATED
assert v.type is FMI3_Type.FLOAT64
assert v.variability is FMI3_Variability.CONTINUOUS
v = variables['x1']
assert v.description == 'the second state'
assert v.name == 'x1'
assert v.value_reference == 3
assert v.causality is FMI3_Causality.OUTPUT
assert v.initial is FMI3_Initial.EXACT
assert v.type is FMI3_Type.FLOAT64
assert v.variability is FMI3_Variability.CONTINUOUS
v = variables['der(x1)']
assert v.description == ''
assert v.name == 'der(x1)'
assert v.value_reference == 4
assert v.causality is FMI3_Causality.LOCAL
assert v.initial is FMI3_Initial.CALCULATED
assert v.type is FMI3_Type.FLOAT64
assert v.variability is FMI3_Variability.CONTINUOUS
v = variables['mu']
assert v.description == ''
assert v.name == 'mu'
assert v.value_reference == 5
assert v.causality is FMI3_Causality.PARAMETER
assert v.initial is FMI3_Initial.EXACT
assert v.type is FMI3_Type.FLOAT64
assert v.variability is FMI3_Variability.FIXED
def test_get_model_variables_causality(self):
""" Test get_model_variables by specifying causality. """
fmu = get_fmi3_reference_fmu("VanDerPol")
variables = fmu.get_model_variables(causality=FMI3_Causality.PARAMETER)
assert len(variables) == 1
assert 'mu' in variables
def test_get_model_variables_type(self):
""" Test get_model_variables by specifying type. """
fmu = get_fmi3_reference_fmu("Feedthrough")
variables = fmu.get_model_variables(type=FMI3_Type.FLOAT64)
assert len(variables) == 7
expected = [
'time',
'Float64_fixed_parameter',
'Float64_tunable_parameter',
'Float64_continuous_input',
'Float64_continuous_output',
'Float64_discrete_input',
'Float64_discrete_output',
]
assert expected == list(variables.keys())
def test_get_model_variables_variability(self):
""" Test get_model_variables by specifying variability. """
fmu = get_fmi3_reference_fmu("VanDerPol")
variables = fmu.get_model_variables(variability=FMI3_Variability.CONTINUOUS)
assert len(variables) == 5
assert 'mu' not in variables
def test_get_model_variables_multiple(self):
""" Test get_model_variables by specifying multiple arguments. """
fmu = get_fmi3_reference_fmu("VanDerPol")
variables = fmu.get_model_variables(type=FMI3_Type.FLOAT64, variability=FMI3_Variability.FIXED)
assert len(variables) == 1
assert 'mu' in variables
def test_get_model_variables_several(self):
""" Test get_model_variables by specifying several arguments. """
fmu = get_fmi3_reference_fmu("Feedthrough")
variables = fmu.get_model_variables(
type=FMI3_Type.FLOAT64,
causality=FMI3_Causality.INPUT,
variability=FMI3_Variability.DISCRETE)
assert len(variables) == 1
assert 'Float64_discrete_input' in variables
def test_get_model_variables_only_start(self):
""" Test get_model_variables by specifying 'only_start'. """
fmu = get_fmi3_reference_fmu("Feedthrough")
variables = fmu.get_model_variables(only_start = True)
expected = [
'Float32_continuous_input',
'Float32_discrete_input',
'Float64_fixed_parameter',
'Float64_tunable_parameter',
'Float64_continuous_input',
'Float64_discrete_input',
'Int8_input',
'UInt8_input',
'Int16_input',
'UInt16_input',
'Int32_input',
'UInt32_input',
'Int64_input',
'UInt64_input',
'Boolean_input',
'String_input',
'Binary_input',
'Enumeration_input']
assert expected == list(variables.keys())
def test_get_model_variables_only_fixed(self):
""" Test get_model_variables by specifying 'only_fixed'. """
fmu = get_fmi3_reference_fmu("Feedthrough")
variables = fmu.get_model_variables(only_fixed = True)
expected = ['Float64_fixed_parameter']
assert expected == list(variables.keys())
def test_get_model_variables_filter(self):
""" Test get_model_variables by specifying filter. """
fmu = get_fmi3_reference_fmu("VanDerPol")
variables = fmu.get_model_variables(filter="der*")
assert len(variables) == 2
assert 'der(x0)' in variables
assert 'der(x1)' in variables
def test_get_model_variables_multiple_filters(self):
""" Test get_model_variables by specifying multiple filters. """
fmu = get_fmi3_reference_fmu("Feedthrough")
variables = fmu.get_model_variables(filter=['*parameter', 'UInt16*'])
expected = [
'Float64_fixed_parameter',
'Float64_tunable_parameter',
'UInt16_input',
'UInt16_output'
]
assert expected == list(variables.keys())
def test_get_model_variables_many_args(self):
""" Test get_model_variables by specifying almost all inputs. """
fmu = get_fmi3_reference_fmu("Feedthrough")
variables = fmu.get_model_variables(
type=FMI3_Type.FLOAT64,
causality=FMI3_Causality.PARAMETER,
variability=FMI3_Variability.FIXED)
expected = [
'Float64_fixed_parameter']
assert expected == list(variables.keys())
variables = fmu.get_model_variables(
type=FMI3_Type.FLOAT64,
causality=FMI3_Causality.PARAMETER,
variability=FMI3_Variability.FIXED,
filter="idontexist")
expected = []
assert expected == list(variables.keys())
def test_get_input_list(self):
""" Test get_input_list. """
fmu = get_fmi3_reference_fmu("Feedthrough")
inputs = fmu.get_input_list()
expected = ['Float64_continuous_input']
assert expected == list(inputs.keys())
def test_get_output_list(self):
""" Test get_output_list. """
fmu = get_fmi3_reference_fmu("Feedthrough")
outputs = fmu.get_output_list()
expected = ['Float64_continuous_output']
assert expected == list(outputs.keys())
def test_get_output_dependencies(self):
""" Test get_output_dependencies, Feedthrough."""
fmu = get_fmi3_reference_fmu("Feedthrough")
num_outputs = len(fmu.get_output_list())
state_deps, input_deps = fmu.get_output_dependencies()
assert num_outputs == 1
assert len(state_deps) == num_outputs
assert state_deps["Float64_continuous_output"] == []
assert len(input_deps) == num_outputs
assert input_deps["Float64_continuous_output"] == ["Float64_continuous_input"]
def test_get_output_dependencies_2(self):
""" Test get_output_dependencies, VanDerPol."""
fmu = get_fmi3_reference_fmu("VanDerPol")
num_outputs = len(fmu.get_output_list())
state_deps, input_deps = fmu.get_output_dependencies()
assert num_outputs == 2
assert len(state_deps) == num_outputs
assert state_deps["x0"] == ["x0"]
assert state_deps["x1"] == ["x1"]
assert len(input_deps) == num_outputs
assert input_deps["x0"] == []
assert input_deps["x1"] == []
def test_get_output_dependencies_kind(self):
""" Test get_output_dependencies_kind."""
fmu = get_fmi3_reference_fmu("Feedthrough")
num_outputs = len(fmu.get_output_list())
state_deps_kinds, input_deps_kinds = fmu.get_output_dependencies_kind()
assert num_outputs == 1
assert len(state_deps_kinds) == num_outputs
assert state_deps_kinds["Float64_continuous_output"] == []
assert len(input_deps_kinds) == num_outputs
assert input_deps_kinds["Float64_continuous_output"] == [FMI3_DependencyKind.CONSTANT]
def test_get_derivatives_dependencies(self):
""" Test get_derivatives_dependencies."""
fmu = get_fmi3_reference_fmu("VanDerPol")
num_ders = len(fmu.get_derivatives_list())
state_deps, input_deps = fmu.get_derivatives_dependencies()
assert num_ders == 2
assert len(state_deps) == num_ders
assert state_deps["der(x0)"] == ["x1"]
assert state_deps["der(x1)"] == ["x0", "x1"]
assert len(input_deps) == num_ders
assert input_deps["der(x0)"] == []
assert input_deps["der(x1)"] == []
def test_get_derivatives_dependencies_kind(self):
""" Test get_derivatives_dependencies_kind."""
fmu = get_fmi3_reference_fmu("VanDerPol")
num_ders = len(fmu.get_derivatives_list())
state_deps_kinds, input_deps_kinds = fmu.get_derivatives_dependencies_kind()
assert num_ders == 2
assert len(state_deps_kinds) == num_ders
assert state_deps_kinds["der(x0)"] == [FMI3_DependencyKind.CONSTANT]
assert state_deps_kinds["der(x1)"] == [FMI3_DependencyKind.DEPENDENT, FMI3_DependencyKind.DEPENDENT]
assert len(input_deps_kinds) == num_ders
assert input_deps_kinds["der(x0)"] == []
assert input_deps_kinds["der(x1)"] == []
@pytest.mark.parametrize("function_name, valuerefs, expected_result, expected_dtype",
[
("get_float64", [5, 6], np.array([0, 0], dtype=np.float64), np.float64),
("get_float32", [1, 2], np.array([0, 0], dtype=np.float32), np.float32),
("get_int64", [23, 24], np.array([0, 0], dtype=np.int64), np.int64),
("get_int32", [19, 20], np.array([0, 0], dtype=np.int32), np.int32),
("get_int16", [15, 16], np.array([0, 0], dtype=np.int16), np.int16),
("get_int8", [11, 12], np.array([0, 0], dtype=np.int8), np.int8),
("get_uint64", [25, 26], np.array([0, 0], dtype=np.uint64), np.uint64),
("get_uint32", [21, 22], np.array([0, 0], dtype=np.uint32), np.uint32),
("get_uint16", [17, 18], np.array([0, 0], dtype=np.uint16), np.uint16),
("get_uint8", [13, 14], np.array([0, 0], dtype=np.uint8), np.uint8),
("get_boolean", [27, 28], np.array([False, False], dtype=np.bool_), np.bool_),
("get_enum", [33, 34], np.array([1, 1], dtype=np.int64), np.int64),
]
)
def test_getX(self, function_name, valuerefs, expected_result, expected_dtype):
"""Test the various get_TYPE([<valueref>]) functions."""
fmu = get_fmi3_reference_fmu("Feedthrough")
res = getattr(fmu, function_name)(valuerefs) # fmu.<function_name>(valuerefs)
np.testing.assert_equal(res, expected_result)
assert res.dtype == expected_dtype
def test_get_string(self):
"""Test the get_string function."""
fmu = get_fmi3_reference_fmu("Feedthrough")
res = fmu.get_string([29])
np.testing.assert_equal(res, ["Set me!"])
assert type(res) == list
@pytest.mark.parametrize("model_class", [FMUModelME3, FMUModelCS3])
@pytest.mark.parametrize("variable_name, value, expected_dtype",
[
("Float64_continuous_input", 3.14, np.double),
("Float32_continuous_input", np.float32(3.14), np.float32),
("Int64_input", 9_223_372_036_854_775_806, np.int64),
("Int32_input", 2_147_483_647, np.int32),
("Int16_input", 32_766, np.int16),
("Int8_input", 126, np.int8),
("UInt64_input", 18_446_744_073_709_551_615, np.uint64),
("UInt32_input", 4_294_967_294, np.uint32),
("UInt16_input", 65_534, np.uint16),
("UInt8_input", 254, np.uint8),
("Boolean_input", True, np.bool_),
("Enumeration_input", 2, np.int64),
]
)
def test_set_get(self, model_class, variable_name, value, expected_dtype):
"""Test getting and setting variables of various types, for both ME and CS FMUs."""
fmu = get_fmi3_reference_fmu("Feedthrough", model_class = model_class)
fmu.set(variable_name, value)
res = fmu.get(variable_name)
assert res.dtype == expected_dtype
assert res[0] == value
@pytest.mark.skipif(NUMPY_MAJOR_VERSION > 1, reason = "Error for numpy>=2")
@pytest.mark.parametrize("variable_name, value", OVERFLOW_TEST_SET)
# XXX: Redundant in the future
def test_set_get_out_of_bounds_overflow_old_numpy(self, variable_name, value):
"""Test setting too large/small value for various integer types."""
fmu = get_fmi3_reference_fmu("Feedthrough")
with pytest.warns(DeprecationWarning, match = "overflow"):
fmu.set(variable_name, value)
@pytest.mark.skipif(NUMPY_MAJOR_VERSION < 2, reason = "Only deprecated for numpy<2")
@pytest.mark.parametrize("variable_name, value", OVERFLOW_TEST_SET)
def test_set_get_out_of_bounds_overflow_new_numpy(self, variable_name, value):
"""Test setting too large/small value for various integer types."""
fmu = get_fmi3_reference_fmu("Feedthrough")
with pytest.raises(OverflowError):
fmu.set(variable_name, value)
@pytest.mark.parametrize("variable_name, value",
[
("Int64_input", 9_223_372_036_854_775_810),
("Int64_input", -9_223_372_036_854_775_810),
("UInt64_input", 18_446_744_073_709_551_620),
]
)
def test_set_large_int_overflow(self, variable_name, value):
"""Test setting too large/small value for various integer types."""
fmu = get_fmi3_reference_fmu("Feedthrough")
with pytest.raises(OverflowError):
fmu.set(variable_name, value)
def test_set_get_string(self):
"""Test getting and setting of string variables."""
fmu = get_fmi3_reference_fmu("Feedthrough")
variable_name = "String_input"
value = "hello string"
fmu.set(variable_name, value)
res = fmu.get(variable_name)
assert type(res) == list
assert res[0] == value
def test_directional_derivatives(self):
"""Test directional derivatives."""
fmu = get_fmi3_reference_fmu("VanDerPol")
fmu.set("mu", 2)
fmu.initialize()
fmu.enter_continuous_time_mode()
fmu.continuous_states = np.array([1., 1.])
# sequence from FMUModelME3.get_directional_derivative docstring
states = fmu.get_states_list()
states_references = [s.value_reference for s in states.values()]
derivatives = fmu.get_derivatives_list()
derivatives_references = [d.value_reference for d in derivatives.values()]
v = np.array([1., 1.])
dv = fmu.get_directional_derivative(states_references, derivatives_references, v)
assert dv[0] == 1
assert dv[1] == -5
def test_get_variable_by_valueref(self):
"""Test get_variable_by_valueref."""
fmu = get_fmi3_reference_fmu("Feedthrough")
# Testing for backwards compatibility
assert fmu.get_variable_by_valueref(0) == "time"
assert fmu.get_variable_by_valueref(1) == "Float32_continuous_input"
def test_get_variable_name_by_valueref(self):
"""Test get_variable_name_by_valueref."""
fmu = get_fmi3_reference_fmu("Feedthrough")
assert fmu.get_variable_name_by_valueref(0) == "time"
assert fmu.get_variable_name_by_valueref(1) == "Float32_continuous_input"
def test_get_variable_name_by_valueref_no_var(self):
"""Test get_variable_name_by_valueref for non-existing variable."""
fmu = get_fmi3_reference_fmu("Feedthrough")
err_msg = "The variable with the valuref 10000 could not be found."
with pytest.raises(FMUException, match = re.escape(err_msg)):
fmu.get_variable_name_by_valueref(10000)
def test_get_variable_variability(self):
"""Test get_variable_variability."""
fmu = get_fmi3_reference_fmu("Feedthrough")
assert fmu.get_variable_variability("Float64_fixed_parameter") is FMI3_Variability.FIXED
assert fmu.get_variable_variability("Float64_tunable_parameter") is FMI3_Variability.TUNABLE
assert fmu.get_variable_variability("Float64_discrete_input") is FMI3_Variability.DISCRETE
assert fmu.get_variable_variability("Float64_continuous_input") is FMI3_Variability.CONTINUOUS
def test_get_variable_variability_no_var(self):
"""Test get_variable_variability for non-existing variable."""
fmu = get_fmi3_reference_fmu("Feedthrough")
err_msg = "The variable aaa could not be found."
with pytest.raises(FMUException, match = re.escape(err_msg)):
fmu.get_variable_variability("aaa")
def test_get_variable_initial(self):
"""Test get_variable_initial."""
fmu = get_fmi3_reference_fmu("Feedthrough")
assert fmu.get_variable_initial("Float64_continuous_input") is FMI3_Initial.EXACT
assert fmu.get_variable_initial("Float64_continuous_output") is FMI3_Initial.CALCULATED
def test_get_variable_initial_no_var(self):
"""Test get_variable_initial for non-existing variable."""
fmu = get_fmi3_reference_fmu("Feedthrough")
err_msg = "The variable aaa could not be found."
with pytest.raises(FMUException, match = re.escape(err_msg)):
fmu.get_variable_initial("aaa")
@pytest.mark.parametrize("var_name, expected_value, expected_type",
[
("float64", np.float64(-6.4), np.float64),
("float32", np.float32(-3.2), np.float32),
("int64", -9223372036854775806, np.int64),
("int32", -2147483646, np.int32),
("int16", -32766, np.int16),
("int8", -126, np.int8),
("uint64", 2, np.uint64),
("uint32", 2, np.uint32),
("uint16", 2, np.uint16),
("uint8", 2, np.uint8),
("enum", 1, np.int64),
]
)
def test_get_variable_min(self, var_name, expected_value, expected_type):
"""Test get_variable_min."""
fmu = _get_fmu(str(this_dir / "files" / "FMUs" / "XML" / "ME3.0" / "variableAttributes"),
allow_unzipped_fmu = True, _connect_dll = False)
res = fmu.get_variable_min(var_name)
assert isinstance(res, expected_type)
assert res == expected_value
def test_get_variable_min_no_var(self):
"""Test get_variable_min for non-existing variable."""
fmu = get_fmi3_reference_fmu("Feedthrough")
err_msg = "The variable aaa could not be found."
with pytest.raises(FMUException, match = re.escape(err_msg)):
fmu.get_variable_min("aaa")
def test_get_variable_min_invalid_basetype(self):
"""Test get_variable_min for a basetype that does not have minimums."""
fmu = get_fmi3_reference_fmu("Feedthrough")
err_msg = "Given variable type does not have a minimum."
with pytest.raises(FMUException, match = re.escape(err_msg)):
fmu.get_variable_min("String_input")
@pytest.mark.parametrize("var_name, expected_value, expected_type",
[
("float64", np.float64(6.4), np.float64),
("float32", np.float32(3.2), np.float32),
("int64", 9223372036854775805, np.int64),
("int32", 2147483645, np.int32),
("int16", 32765, np.int16),
("int8", 125, np.int8),
("uint64", 18446744073709551613, np.uint64),
("uint32", 4294967293, np.uint32),
("uint16", 65533, np.uint16),
("uint8", 253, np.uint8),
("enum", 2, np.int64),
]
)
def test_get_variable_max(self, var_name, expected_value, expected_type):
"""Test get_variable_max."""
fmu = _get_fmu(str(this_dir / "files" / "FMUs" / "XML" / "ME3.0" / "variableAttributes"),
allow_unzipped_fmu = True, _connect_dll = False)
res = fmu.get_variable_max(var_name)
assert isinstance(res, expected_type)
assert res == expected_value
def test_get_variable_max_no_var(self):
"""Test get_variable_max for non-existing variable."""
fmu = get_fmi3_reference_fmu("Feedthrough")
err_msg = "The variable aaa could not be found."
with pytest.raises(FMUException, match = re.escape(err_msg)):
fmu.get_variable_max("aaa")
def test_get_variable_max_invalid_basetype(self):
"""Test get_variable_max for a basetype that does not have minimums."""
fmu = get_fmi3_reference_fmu("Feedthrough")
err_msg = "Given variable type does not have a maximum."
with pytest.raises(FMUException, match = re.escape(err_msg)):
fmu.get_variable_max("String_input")
def test_get_variable_nominal(self):
"""Test get_variable_nominal."""
fmu = _get_fmu(str(this_dir / "files" / "FMUs" / "XML" / "ME3.0" / "variableAttributes"),
allow_unzipped_fmu = True, _connect_dll = False)
assert fmu.get_variable_nominal("float64") == 0.1
assert fmu.get_variable_nominal("float32") == np.float32(0.2)
def test_get_variable_nominal_invalid_basetype(self):
"""Test get_variable_nominal for a basetype that does not have nominals."""
fmu = get_fmi3_reference_fmu("Feedthrough")
err_msg = "Given variable type does not have a nominal."
with pytest.raises(FMUException, match = re.escape(err_msg)):
fmu.get_variable_nominal("String_input")
def test_get_variable_nominal_by_valueref(self):
"""Test get_variable_nominal_by_valueref."""
fmu = _get_fmu(str(this_dir / "files" / "FMUs" / "XML" / "ME3.0" / "variableAttributes"),
allow_unzipped_fmu = True, _connect_dll = False)
assert fmu.get_variable_nominal_by_valueref(1) == 0.1
assert fmu.get_variable_nominal_by_valueref(2) == np.float32(0.2)
@pytest.mark.parametrize("value_reference, expected_value, expected_message",
[
(3, 1.0, "The nominal value for nominal_zero is 0.0 which is illegal according to the FMI specification. Setting the nominal to 1.0."),
(4, 0.1, "The nominal value for nominal64_negative is <0.0 which is illegal according to the FMI specification. Setting the nominal to abs"),
(5, np.float32(0.2), "The nominal value for nominal32_negative is <0.0 which is illegal according to the FMI specification. Setting the nominal to abs"),
])
def test_invalid_nominals(self, caplog, value_reference, expected_value, expected_message):
"""Test getting variable nominals that are auto-corrected to be non-negative"""
fmu = FMUModelME3(str(this_dir / "files" / "FMUs" / "XML" / "ME3.0" / "variableAttributes"),
allow_unzipped_fmu = True, _connect_dll = False, log_level = 3)
caplog.set_level(logging.WARNING)
assert fmu.get_variable_nominal_by_valueref(value_reference) == expected_value
assert any(expected_message in msg for msg in caplog.messages)
def test_invalid_nominals_overwrite(self):
"""Test getting variable nominals that are auto-corrected to be non-negative"""
fmu = _get_fmu(str(this_dir / "files" / "FMUs" / "XML" / "ME3.0" / "variableAttributes"),
allow_unzipped_fmu = True, _connect_dll = False)
assert fmu.get_variable_nominal_by_valueref(3, _override_erroneous_nominal = False) == 0.0
assert fmu.get_variable_nominal_by_valueref(4, _override_erroneous_nominal = False) == -0.1
assert fmu.get_variable_nominal_by_valueref(5, _override_erroneous_nominal = False) == -np.float32(0.2)
def test_get_variable_nominal_by_valueref_invalid_basetype(self):
"""Test get_variable_nominal_by_valueref for a basetype that does not have nominals."""
fmu = get_fmi3_reference_fmu("Feedthrough")
err_msg = "Given variable type does not have a nominal."
with pytest.raises(FMUException, match = re.escape(err_msg)):
fmu.get_variable_nominal_by_valueref(11)
@pytest.mark.parametrize("var_name, expected_value, expected_type",
[
("float64", np.float64(1.23), np.float64),
("float32", np.float32(2.34), np.float32),
("int64", 11, np.int64),
("int32", 12, np.int32),
("int16", 13, np.int16),
("int8", 14, np.int8),
("uint64", 15, np.uint64),
("uint32", 16, np.uint32),
("uint16", 17, np.uint16),
("uint8", 18, np.uint8),
("enum", 2, np.int64),
("string", "aa", str),
("string_no_start", "", str),
("bool", True, np.bool_),
]
)