source: trunk/Python/src/tests_jmodelica/simulation/test_assimulo_interface_fmi.py @ 13366

Last change on this file since 13366 was 13366, checked in by Christian Andersson, 3 months ago

Removed tests that has been migrated to PyFMI. Related to ticket:5781

File size: 81.1 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4# Copyright (C) 2010 Modelon AB
5#
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, version 3 of the License.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program. If not, see <http://www.gnu.org/licenses/>.
17"""Tests for the pyfmi.simulation.assimulo module."""
18import logging
19import nose
20import os
21import numpy as N
22import pylab as P
23from scipy.io.matlab.mio import loadmat
24
25from pymodelica.compiler import compile_fmu
26from pyfmi.fmi import FMUModel, load_fmu, FMUException, TimeLimitExceeded
27from pyfmi.common.io import ResultDymolaTextual
28from tests_jmodelica import testattr, get_files_path
29
30try:
31    from pyfmi.simulation.assimulo_interface import FMIODE
32    from pyfmi.simulation.assimulo_interface import write_data
33    from pyfmi.common.core import TrajectoryLinearInterpolation
34    from assimulo.solvers import CVode
35    from assimulo.solvers import IDA
36except (NameError, ImportError):
37    logging.warning('Could not load Assimulo module. Check pyfmi.check_packages()')
38
39path_to_fmus = os.path.join(get_files_path(), 'FMUs')
40path_to_fmus_me1 = os.path.join(path_to_fmus,"ME1.0")
41path_to_fmus_cs1 = os.path.join(path_to_fmus,"CS1.0")
42path_to_mos  = os.path.join(get_files_path(), 'Modelica')
43 
44
45def input_linear(t):
46    if t < 0.5:
47        return t
48    elif t < 1.0:
49        return 0.5
50    elif t < 1.5:
51        return t-0.5
52    elif t < 2.0:
53        return 2.5-t
54    elif t < 2.5:
55        return 0.5
56    else:
57        return 3.0-t
58       
59input_object = (["u"],input_linear)
60
61class Test_When:
62    @classmethod
63    def setUpClass(cls):
64        file_name = os.path.join(get_files_path(), 'Modelica', 'WhenTests.mo')
65       
66        compile_fmu("WhenTests.WhenTest5", file_name)
67       
68    @testattr(stddist_full = True)
69    def test_sequence_of_pre(self):
70        model = load_fmu("WhenTests_WhenTest5.fmu")
71       
72        res = model.simulate(final_time=3.5)
73       
74        assert res.final("nextTime") == 4.0
75        assert res.final("nextTime2") == 3.0
76        assert res.final("nextTime3") == 8.0
77       
78class Test_Sparse_Linear_Block:
79    @classmethod
80    def setUpClass(cls):
81
82        _cc_name = compile_fmu("Modelica.Mechanics.Rotational.Examples.CoupledClutches", 
83                                version=1.0)
84        _cc_name_sparse = compile_fmu("Modelica.Mechanics.Rotational.Examples.CoupledClutches", 
85                                version=1.0,
86                                compiler_options={"generate_sparse_block_jacobian_threshold": 0},
87                                compile_to=_cc_name[:-4]+"_sparse"+_cc_name[-4:])
88   
89    @testattr(stddist_base = True)
90    def test_cc(self):
91        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
92       
93        res1 = model.simulate()
94       
95        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches_sparse.fmu")
96       
97        res2 = model.simulate()
98       
99        #Assert that sparse handling has no impact on the number of steps
100        assert res1.solver.statistics["nsteps"] == res2.solver.statistics["nsteps"]
101        nose.tools.assert_almost_equal(res1.final("J1.w"), res2.final("J1.w"), 3)
102       
103    @testattr(stddist_base = True)
104    def test_multiple_sparse_systems(self):
105        file_name = os.path.join(get_files_path(), 'Modelica', 'Linear.mo')
106
107        fmu_name = compile_fmu("LinearTest.TwoTornSystems1", file_name, version=1.0,
108                        compiler_options={"generate_sparse_block_jacobian_threshold": 0})
109
110class Test_Time_Events_FMU10:
111    @classmethod
112    def setUpClass(cls):
113        """
114        Compile the test model.
115        """
116        file_name = os.path.join(get_files_path(), 'Modelica', 'TimeEvents.mo')
117
118        compile_fmu("TimeEvents.Basic1", file_name, compiler_options={"relational_time_events":True}, compiler_log_level="debug:log.txt", version="1.0")
119        compile_fmu("TimeEvents.Basic2", file_name, compiler_options={"relational_time_events":True}, version="1.0")
120        compile_fmu("TimeEvents.Basic3", file_name, compiler_options={"relational_time_events":True}, version="1.0")
121        compile_fmu("TimeEvents.Basic4", file_name, compiler_options={"relational_time_events":True}, version="1.0")
122       
123        compile_fmu("TimeEvents.Advanced1", file_name, compiler_options={"relational_time_events":True}, version="1.0")
124        compile_fmu("TimeEvents.Advanced2", file_name, compiler_options={"relational_time_events":True}, version="1.0")
125        compile_fmu("TimeEvents.Advanced3", file_name, compiler_options={"relational_time_events":True}, version="1.0")
126        compile_fmu("TimeEvents.Advanced4", file_name, compiler_options={"relational_time_events":True}, version="1.0")
127       
128        compile_fmu("TimeEvents.Mixed1", file_name, compiler_options={"relational_time_events":True}, version="1.0")
129        compile_fmu("TimeEvents.TestSampling1", file_name, version="1.0")
130        compile_fmu("TimeEvents.TestSampling2", file_name, version="1.0")
131        compile_fmu("TimeEvents.TestSampling3", file_name, version="1.0")
132        compile_fmu("TimeEvents.TestSampling4", file_name, version="1.0")
133        compile_fmu("TimeEvents.TestSampling5", file_name, version="1.0")
134        compile_fmu("TimeEvents.TestSampling6", file_name, version="1.0")
135        compile_fmu("TimeEvents.TestSampling7", file_name, version="1.0")
136        compile_fmu("TimeEvents.TestSampling8", file_name, version="1.0")
137        compile_fmu("TimeEvents.TestSampling9", file_name, version="1.0")
138        compile_fmu("TimeEvents.StateEventAfterTimeEvent", file_name, version="1.0")
139   
140    @testattr(stddist_full = True)
141    def test_time_event_basic_1(self):
142        model = load_fmu("TimeEvents_Basic1.fmu")
143        model.initialize()
144        ev = model.get_event_info()
145        print ev.nextEventTime
146        assert ev.nextEventTime == 1
147       
148    @testattr(stddist_full = True)
149    def test_time_event_basic_2(self):
150        model = load_fmu("TimeEvents_Basic2.fmu")
151        model.initialize()
152        ev = model.get_event_info()
153        print ev.nextEventTime
154        assert ev.nextEventTime == 2
155        assert ev.nextEventTime == model.get("p")
156       
157    @testattr(stddist_full = True)
158    def test_time_event_basic_3(self):
159        model = load_fmu("TimeEvents_Basic3.fmu")
160        model.initialize()
161        ev = model.get_event_info()
162        print ev.nextEventTime
163        assert ev.nextEventTime == 1.5
164       
165    @testattr(stddist_full = True)
166    def test_time_event_basic_4(self):
167        model = load_fmu("TimeEvents_Basic4.fmu")
168       
169        model.initialize()
170        ev = model.get_event_info()
171        assert ev.upcomingTimeEvent == False
172        assert model.get("x")== 2
173       
174        model.reset()
175        model.time = 1
176        model.initialize()
177       
178        assert ev.upcomingTimeEvent == False
179        assert model.get("x") == 1
180       
181    @testattr(stddist_base = True)
182    def test_time_event_advanced1(self):
183        model = load_fmu("TimeEvents_Advanced1.fmu")
184        model.initialize()
185        ev = model.get_event_info()
186        print ev.nextEventTime
187        assert ev.nextEventTime == 0.5
188       
189        model.simulate(options={"initialize":False})
190       
191        print "i (should be 2): ", model.get("i") 
192        assert model.get("i") == 2
193       
194    @testattr(stddist_base = True)
195    def test_time_event_advanced2(self):
196        model = load_fmu("TimeEvents_Advanced2.fmu")
197        model.initialize()
198        ev = model.get_event_info()
199        print ev.nextEventTime
200        assert ev.nextEventTime == 0.5
201       
202        model.simulate(options={"initialize":False})
203       
204        print "i (should be 2): ", model.get("i") 
205        assert model.get("i") == 2
206       
207    @testattr(stddist_base = True)
208    def test_time_event_advanced3(self):
209        model = load_fmu("TimeEvents_Advanced3.fmu")
210        model.initialize()
211        ev = model.get_event_info()
212        print ev.nextEventTime
213        assert ev.nextEventTime == 0.5
214       
215        model.simulate(options={"initialize":False})
216       
217        print "i (should be 2): ", model.get("i") 
218        print "j (should be 1): ", model.get("j") 
219        assert model.get("i") == 2
220        assert model.get("j") == 1
221       
222    @testattr(stddist_base = True)
223    def test_time_event_advanced4(self):
224        model = load_fmu("TimeEvents_Advanced4.fmu")
225        model.initialize()
226        ev = model.get_event_info()
227        print ev.nextEventTime
228        assert ev.nextEventTime == 0.5
229       
230        model.simulate(options={"initialize":False})
231       
232        print "i (should be 1): ", model.get("i") 
233        print "j (should be 1): ", model.get("j") 
234        assert model.get("i") == 1
235        assert model.get("j") == 1
236       
237    @testattr(stddist_full = True)
238    def test_time_event_mixed1(self):
239        model = load_fmu("TimeEvents_Mixed1.fmu")
240        model.initialize()
241        ev = model.get_event_info()
242        print ev.nextEventTime
243        assert ev.nextEventTime == 1.5
244       
245        res = model.simulate(final_time=4, options={"initialize":False})
246       
247        print "x: ", res["x"]
248        print "dx: ", res["der(x)"]
249       
250        assert res.solver.statistics["ntimeevents"] == 2
251        assert res.solver.statistics["nstateevents"] == 2
252
253    """                 """
254    """ Sampling tests. """
255    """                 """
256
257    """ Basic test using only interval. """
258
259    @testattr(sample = True)
260    def test_time_event_sampling1(self):
261        model = load_fmu("TimeEvents_TestSampling1.fmu")
262        model.initialize()
263        res = model.simulate(0, 1e3, options={"initialize":False});
264        assert res.solver.statistics["ntimeevents"] == 1e4
265
266    """ Only small interval. """
267
268    @testattr(sample = True)
269    def test_time_event_sampling2(self):
270        model = load_fmu("TimeEvents_TestSampling2.fmu")
271        model.initialize()
272        res = model.simulate(0,1e-6, options={"initialize":False});
273        assert res.solver.statistics["ntimeevents"] == 1e4
274
275    """ Only big interval. """
276
277    @testattr(sample = True)
278    def test_time_event_sampling3(self):
279        model = load_fmu("TimeEvents_TestSampling3.fmu")
280        model.initialize()
281        res = model.simulate(0,1e64, options={"initialize":False});
282        assert res.solver.statistics["ntimeevents"] == 1e4
283
284    """ Basic test using offset. """
285
286    @testattr(sample = True)
287    def test_time_event_sampling4(self):
288        model = load_fmu("TimeEvents_TestSampling4.fmu")
289        model.initialize()
290        res = model.simulate(0,2e-6, options={"initialize":False});
291        assert res.solver.statistics["ntimeevents"] == (1e4)+1
292
293    """ Big interval, small offset. """
294
295    @testattr(sample = True)
296    def test_time_event_sampling5(self):
297        model = load_fmu("TimeEvents_TestSampling5.fmu")
298        model.initialize()
299        res = model.simulate(0,1e64, options={"initialize":False});
300        assert res.solver.statistics["ntimeevents"] == 1e4
301
302    """ Big interval and offset. """
303
304    @testattr(sample = True)
305    def test_time_event_sampling6(self):
306        model = load_fmu("TimeEvents_TestSampling6.fmu")
307        model.initialize()
308        res = model.simulate(0,1e64, options={"initialize":False});
309        assert res.solver.statistics["ntimeevents"] == 1e4
310
311    @testattr(sample = True)
312    def test_time_event_sampling7(self):
313        model = load_fmu("TimeEvents_TestSampling7.fmu")
314        model.initialize()
315        res = model.simulate(0,1e5, options={"initialize":False});
316        assert res.solver.statistics["ntimeevents"] == 1e4
317
318    """ Test 8 verifies that sampling raises an exception when a too small step is required. """
319
320    @testattr(sample = True)
321    def test_time_event_sampling8(self):
322        model = load_fmu("TimeEvents_TestSampling8.fmu")
323        nose.tools.assert_raises(model.initialize)
324
325    """ Same interval and offset. """
326
327    @testattr(sample = True)
328    def test_time_event_sampling9(self):
329        model = load_fmu("TimeEvents_TestSampling9.fmu")
330        model.initialize()
331        res = model.simulate(0,1, options={"initialize":False});
332        assert res.solver.statistics["ntimeevents"] == 10
333
334    @testattr(stddist_base = True)
335    def test_time_event_state_event_after_time_event(self):
336        model = load_fmu("TimeEvents_StateEventAfterTimeEvent.fmu")
337        opts = model.simulate_options()
338        opts["solver"] = "CVode"
339        opts["CVode_options"]["rtol"] = 1e-4
340        res = model.simulate(0,1, options=opts);
341        nose.tools.assert_almost_equal(model.get("s"), 2.8)
342        assert res.solver.statistics["ntimeevents"] == 2     
343
344class Test_Time_Events_FMU20:
345    @classmethod
346    def setUpClass(cls):
347        """
348        Compile the test model.
349        """
350        file_name = os.path.join(get_files_path(), 'Modelica', 'TimeEvents.mo')
351
352        compile_fmu("TimeEvents.Basic1", file_name, compiler_options={"relational_time_events":True}, compiler_log_level="debug:log.txt", version="2.0")
353        compile_fmu("TimeEvents.Basic2", file_name, compiler_options={"relational_time_events":True}, version="2.0")
354        compile_fmu("TimeEvents.Basic3", file_name, compiler_options={"relational_time_events":True}, version="2.0")
355        compile_fmu("TimeEvents.Basic4", file_name, compiler_options={"relational_time_events":True}, version="2.0")
356       
357        compile_fmu("TimeEvents.Advanced1", file_name, compiler_options={"relational_time_events":True}, version="2.0")
358        compile_fmu("TimeEvents.Advanced2", file_name, compiler_options={"relational_time_events":True}, version="2.0")
359        compile_fmu("TimeEvents.Advanced3", file_name, compiler_options={"relational_time_events":True}, version="2.0")
360        compile_fmu("TimeEvents.Advanced4", file_name, compiler_options={"relational_time_events":True}, version="2.0")
361       
362        compile_fmu("TimeEvents.Mixed1", file_name, compiler_options={"relational_time_events":True}, version="2.0")
363        compile_fmu("TimeEvents.TestSampling1", file_name, version="2.0")
364        compile_fmu("TimeEvents.TestSampling2", file_name, version="2.0")
365        compile_fmu("TimeEvents.TestSampling3", file_name, version="2.0")
366        compile_fmu("TimeEvents.TestSampling4", file_name, version="2.0")
367        compile_fmu("TimeEvents.TestSampling5", file_name, version="2.0")
368        compile_fmu("TimeEvents.TestSampling6", file_name, version="2.0")
369        compile_fmu("TimeEvents.TestSampling7", file_name, version="2.0")
370        compile_fmu("TimeEvents.TestSampling8", file_name, version="2.0")
371        compile_fmu("TimeEvents.TestSampling9", file_name, version="2.0")
372        compile_fmu("TimeEvents.StateEventAfterTimeEvent", file_name, version="2.0")
373   
374    @testattr(stddist_full = True)
375    def test_time_event_basic_1(self):
376        model = load_fmu("TimeEvents_Basic1.fmu")
377        model.initialize()
378        model.event_update()
379        model.enter_continuous_time_mode()
380        ev = model.get_event_info()
381        print ev.nextEventTime
382        assert ev.nextEventTime == 1
383       
384    @testattr(stddist_full = True)
385    def test_time_event_basic_2(self):
386        model = load_fmu("TimeEvents_Basic2.fmu")
387        model.initialize()
388        model.event_update()
389        model.enter_continuous_time_mode()
390        ev = model.get_event_info()
391        print ev.nextEventTime
392        assert ev.nextEventTime == 2
393        assert ev.nextEventTime == model.get("p")
394       
395    @testattr(stddist_full = True)
396    def test_time_event_basic_3(self):
397        model = load_fmu("TimeEvents_Basic3.fmu")
398        model.initialize()
399        model.event_update()
400        model.enter_continuous_time_mode()
401        ev = model.get_event_info()
402        print ev.nextEventTime
403        assert ev.nextEventTime == 1.5
404       
405    @testattr(stddist_full = True)
406    def test_time_event_basic_4(self):
407        model = load_fmu("TimeEvents_Basic4.fmu")
408       
409        model.initialize()
410        model.event_update()
411        model.enter_continuous_time_mode()
412        ev = model.get_event_info()
413        assert ev.nextEventTimeDefined == False
414        assert model.get("x")== 2
415       
416        model.reset()
417        model.time = 1
418        model.initialize()
419        model.event_update()
420        model.enter_continuous_time_mode()
421       
422        assert ev.nextEventTimeDefined == False
423        assert model.get("x") == 1
424       
425    @testattr(stddist_base = True)
426    def test_time_event_advanced1(self):
427        model = load_fmu("TimeEvents_Advanced1.fmu")
428        model.initialize()
429        model.event_update()
430        model.enter_continuous_time_mode()
431        ev = model.get_event_info()
432        print ev.nextEventTime
433        assert ev.nextEventTime == 0.5
434       
435        model.simulate(options={"initialize":False})
436       
437        print "i (should be 2): ", model.get("i") 
438        assert model.get("i") == 2
439       
440    @testattr(stddist_base = True)
441    def test_time_event_advanced2(self):
442        model = load_fmu("TimeEvents_Advanced2.fmu")
443        model.initialize()
444        model.event_update()
445        model.enter_continuous_time_mode()
446        ev = model.get_event_info()
447        print ev.nextEventTime
448        assert ev.nextEventTime == 0.5
449       
450        model.simulate(options={"initialize":False})
451       
452        print "i (should be 2): ", model.get("i") 
453        assert model.get("i") == 2
454       
455    @testattr(stddist_base = True)
456    def test_time_event_advanced3(self):
457        model = load_fmu("TimeEvents_Advanced3.fmu")
458        model.initialize()
459        model.event_update()
460        model.enter_continuous_time_mode()
461        ev = model.get_event_info()
462        print ev.nextEventTime
463        assert ev.nextEventTime == 0.5
464       
465        model.simulate(options={"initialize":False})
466       
467        print "i (should be 2): ", model.get("i") 
468        print "j (should be 1): ", model.get("j") 
469        assert model.get("i") == 2
470        assert model.get("j") == 1
471       
472    @testattr(stddist_base = True)
473    def test_time_event_advanced4(self):
474        model = load_fmu("TimeEvents_Advanced4.fmu")
475        model.initialize()
476        model.event_update()
477        model.enter_continuous_time_mode()
478        ev = model.get_event_info()
479        assert ev.nextEventTime == 0.5
480       
481        model.simulate(options={"initialize":False})
482       
483        print "i (should be 1): ", model.get("i") 
484        print "j (should be 1): ", model.get("j") 
485        assert model.get("i") == 1
486        assert model.get("j") == 1
487       
488    @testattr(stddist_full = True)
489    def test_time_event_mixed1(self):
490        model = load_fmu("TimeEvents_Mixed1.fmu")
491        model.initialize()
492        model.event_update()
493        model.enter_continuous_time_mode()
494        ev = model.get_event_info()
495        print ev.nextEventTime
496        assert ev.nextEventTime == 1.5
497       
498        res = model.simulate(final_time=4, options={"initialize":False})
499       
500        print "x: ", res["x"]
501        print "dx: ", res["der(x)"]
502       
503        assert res.solver.statistics["ntimeevents"] == 2
504        assert res.solver.statistics["nstateevents"] == 2
505
506    """                 """
507    """ Sampling tests. """
508    """                 """
509
510    """ Basic test using only interval. """
511
512    @testattr(sample = True)
513    def test_time_event_sampling1(self):
514        model = load_fmu("TimeEvents_TestSampling1.fmu")
515        model.initialize()
516        res = model.simulate(0, 1e3, options={"initialize":False});
517        assert res.solver.statistics["ntimeevents"] == 1e4
518
519    """ Only small interval. """
520
521    @testattr(sample = True)
522    def test_time_event_sampling2(self):
523        model = load_fmu("TimeEvents_TestSampling2.fmu")
524        model.initialize()
525        res = model.simulate(0,1e-6, options={"initialize":False});
526        assert res.solver.statistics["ntimeevents"] == 1e4
527
528    """ Only big interval. """
529
530    @testattr(sample = True)
531    def test_time_event_sampling3(self):
532        model = load_fmu("TimeEvents_TestSampling3.fmu")
533        model.initialize()
534        res = model.simulate(0,1e64, options={"initialize":False});
535        assert res.solver.statistics["ntimeevents"] == 1e4
536
537    """ Basic test using offset. """
538
539    @testattr(sample = True)
540    def test_time_event_sampling4(self):
541        model = load_fmu("TimeEvents_TestSampling4.fmu")
542        model.initialize()
543        res = model.simulate(0,2e-6, options={"initialize":False});
544        assert res.solver.statistics["ntimeevents"] == (1e4)+1
545
546    """ Big interval, small offset. """
547
548    @testattr(sample = True)
549    def test_time_event_sampling5(self):
550        model = load_fmu("TimeEvents_TestSampling5.fmu")
551        model.initialize()
552        res = model.simulate(0,1e64, options={"initialize":False});
553        assert res.solver.statistics["ntimeevents"] == 1e4
554
555    """ Big interval and offset. """
556
557    @testattr(sample = True)
558    def test_time_event_sampling6(self):
559        model = load_fmu("TimeEvents_TestSampling6.fmu")
560        model.initialize()
561        res = model.simulate(0,1e64, options={"initialize":False});
562        assert res.solver.statistics["ntimeevents"] == 1e4
563
564    @testattr(sample = True)
565    def test_time_event_sampling7(self):
566        model = load_fmu("TimeEvents_TestSampling7.fmu")
567        model.initialize()
568        res = model.simulate(0,1e5, options={"initialize":False});
569        assert res.solver.statistics["ntimeevents"] == 1e4
570
571    """ Test 8 verifies that sampling raises an exception when a too small step is required. """
572
573    @testattr(sample = True)
574    def test_time_event_sampling8(self):
575        model = load_fmu("TimeEvents_TestSampling8.fmu")
576        nose.tools.assert_raises(model.initialize)
577
578    """ Same interval and offset. """
579
580    @testattr(sample = True)
581    def test_time_event_sampling9(self):
582        model = load_fmu("TimeEvents_TestSampling9.fmu")
583        model.initialize()
584        res = model.simulate(0,1, options={"initialize":False});
585        assert res.solver.statistics["ntimeevents"] == 10
586
587    @testattr(stddist_base = True)
588    def test_time_event_state_event_after_time_event(self):
589        model = load_fmu("TimeEvents_StateEventAfterTimeEvent.fmu")
590        opts = model.simulate_options()
591        opts["solver"] = "CVode"
592        opts["CVode_options"]["rtol"] = 1e-4
593        res = model.simulate(0,1, options=opts);
594        nose.tools.assert_almost_equal(model.get("s"), 2.8)
595        assert res.solver.statistics["ntimeevents"] == 2               
596
597class Test_DynamicStates:
598    @classmethod
599    def setUpClass(cls):
600        """
601        Compile the test model.
602        """
603        file_name = os.path.join(get_files_path(), 'Modelica', 'RevoluteConstraint.mo')
604
605        compile_fmu("StrippedRevoluteConstraint", file_name)
606       
607    @testattr(stddist_full = True)
608    def test_no_switch_of_states(self):
609        model = load_fmu("StrippedRevoluteConstraint.fmu")
610       
611        res = model.simulate(final_time=10)
612       
613        #No step events triggered
614        assert res.solver.statistics["nstepevents"] == 0 
615       
616        var = res["freeMotionScalarInit.angle_2"]
617       
618        nose.tools.assert_almost_equal(abs(max(var)), 0.00, 2)
619        nose.tools.assert_almost_equal(abs(min(var)), 2.54, 2)
620
621class Test_Events:
622    @classmethod
623    def setUpClass(cls):
624        """
625        Compile the test model.
626        """
627        file_name = os.path.join(get_files_path(), 'Modelica', 'EventIter.mo')
628
629        compile_fmu("EventIter.EventInfiniteIteration1", file_name)
630        compile_fmu("EventIter.EventInfiniteIteration2", file_name)
631        compile_fmu("EventIter.EventInfiniteIteration3", file_name)
632        compile_fmu("EventIter.EnhancedEventIteration1", file_name)
633        compile_fmu("EventIter.EnhancedEventIteration2", file_name)
634        compile_fmu("EventIter.EnhancedEventIteration3", file_name)
635        compile_fmu("EventIter.SingularSystem1", file_name)
636        compile_fmu("EventIter.InitialPhasing1", file_name)
637        compile_fmu("EventIter.EventIterDiscreteReals", file_name)
638        compile_fmu("EventIter.EventAfterTimeEvent", file_name)
639   
640    @testattr(stddist_full = True)
641    def test_reinit_after_two_time_events(self):
642        model = load_fmu("EventIter_EventAfterTimeEvent.fmu")
643       
644        res = model.simulate()
645       
646        nose.tools.assert_almost_equal(res.final("s"), -1.0)
647   
648    @testattr(stddist_full = True)
649    def test_event_infinite_iteration_1(self):
650        model = load_fmu("EventIter_EventInfiniteIteration1.fmu")
651        nose.tools.assert_raises(FMUException, model.initialize)
652       
653    @testattr(stddist_full = True)
654    def test_event_infinite_iteration_2(self):
655        model = load_fmu("EventIter_EventInfiniteIteration2.fmu")
656        nose.tools.assert_raises(FMUException, model.initialize)
657       
658    @testattr(stddist_full = True)
659    def test_event_infinite_iteration_3(self):
660        model = load_fmu("EventIter_EventInfiniteIteration3.fmu")
661        nose.tools.assert_raises(FMUException, model.simulate)
662       
663    @testattr(stddist_full = True)
664    def test_singular_system_event_1(self):
665        model = load_fmu("EventIter_SingularSystem1.fmu")
666       
667        #Check that we can initialize without error!
668        model.initialize()
669       
670        nose.tools.assert_almost_equal(model.get("mode"), 0.0)
671        nose.tools.assert_almost_equal(model.get("sa"), 0.0)
672       
673    @testattr(stddist_base = True)
674    def test_enhanced_event_iteration_1(self):
675        model = load_fmu("EventIter_EnhancedEventIteration1.fmu")
676        res = model.simulate()
677       
678        nose.tools.assert_almost_equal(res["x[1]"][-1], 0)
679        nose.tools.assert_almost_equal(res["x[2]"][-1], 0)
680        nose.tools.assert_almost_equal(res["x[3]"][-1], 0)
681        nose.tools.assert_almost_equal(res["x[4]"][-1], -0.406)
682        nose.tools.assert_almost_equal(res["x[5]"][-1], -0.406)
683        nose.tools.assert_almost_equal(res["x[6]"][-1], -0.406)
684        nose.tools.assert_almost_equal(res["x[7]"][-1], 0.94)
685       
686    @testattr(stddist_base = True)
687    def test_enhanced_event_iteration_2(self):
688        model = load_fmu("EventIter_EnhancedEventIteration2.fmu")
689        res = model.simulate(final_time=2.0)
690       
691        nose.tools.assert_almost_equal(res["y"][0], 1.0)
692        nose.tools.assert_almost_equal(res["w"][0], 0.0)
693        nose.tools.assert_almost_equal(res["x"][-1], 2.0)
694        nose.tools.assert_almost_equal(res["y"][-1],1.58385,4)
695        nose.tools.assert_almost_equal(res["z"][-1], 0.0)
696        nose.tools.assert_almost_equal(res["w"][-1], 1.0)
697       
698    @testattr(stddist_base = True)
699    def test_enhanced_event_iteration_3(self):
700        model = load_fmu("EventIter_EnhancedEventIteration3.fmu")
701        model.initialize(tolerance=1e-1)
702       
703        nose.tools.assert_almost_equal(model.get("x"), -1e-6)
704   
705    @testattr(stddist_full = True)
706    def test_initial_phasing_1(self):
707        model = load_fmu("EventIter_InitialPhasing1.fmu")
708        res = model.simulate(final_time=0.1)
709        nose.tools.assert_almost_equal(res["b1"][0], 0.0)
710        nose.tools.assert_almost_equal(res["b2"][0], 1.0)
711       
712    @testattr(stddist_base=True)
713    def test_discrete_real_event_iteration(self):
714        model = load_fmu("EventIter_EventIterDiscreteReals.fmu")
715        res = model.simulate(final_time=1.0)
716        nose.tools.assert_almost_equal(res["T1"][0], 0.0)
717        nose.tools.assert_almost_equal(res["start"][0], 1.0)
718        nose.tools.assert_almost_equal(res["T2"][0], 0.0)
719
720class Test_Relations:
721    @classmethod
722    def setUpClass(cls):
723        """
724        Compile the test model.
725        """
726        file_name = os.path.join(get_files_path(), 'Modelica', 'RelationTests.mo')
727
728        compile_fmu("RelationTests.RelationLE", file_name)
729        compile_fmu("RelationTests.RelationGE", file_name)
730        compile_fmu("RelationTests.RelationLEInv", file_name)
731        compile_fmu("RelationTests.RelationGEInv", file_name)
732        compile_fmu("RelationTests.RelationLEInit", file_name)
733        compile_fmu("RelationTests.RelationGEInit", file_name)
734        compile_fmu("RelationTests.TestRelationalOp1", file_name)
735       
736    @testattr(stddist_full = True)
737    def test_relation_le(self):
738        model = load_fmu("RelationTests_RelationLE.fmu")
739        opts = model.simulate_options()
740        opts["CVode_options"]["maxh"] = 0.001
741        res = model.simulate(final_time=3.5, input=input_object,options=opts)
742       
743        nose.tools.assert_almost_equal(N.interp(0.75,res["time"],res["y"]),0.5,places=2)
744        nose.tools.assert_almost_equal(N.interp(2.25,res["time"],res["y"]),0.5,places=2)
745        nose.tools.assert_not_almost_equal(N.interp(0.25,res["time"],res["y"]),0.5,places=2)
746        nose.tools.assert_not_almost_equal(N.interp(2.75,res["time"],res["y"]),0.5,places=2)
747        nose.tools.assert_not_almost_equal(N.interp(0.75,res["time"],res["x"]),0.5,places=2)
748        nose.tools.assert_not_almost_equal(N.interp(2.25,res["time"],res["x"]),0.5,places=2)
749        nose.tools.assert_almost_equal(N.interp(1.5,res["time"],res["y"]),0.5,places=2)
750       
751    @testattr(stddist_full = True)
752    def test_relation_leinv(self):
753        model = load_fmu("RelationTests_RelationLEInv.fmu")
754        opts = model.simulate_options()
755        opts["CVode_options"]["maxh"] = 0.001
756        res = model.simulate(final_time=3.5, input=input_object,options=opts)
757       
758        nose.tools.assert_almost_equal(N.interp(0.75,res["time"],res["y"]),0.5,places=2)
759        nose.tools.assert_almost_equal(N.interp(2.25,res["time"],res["y"]),0.5,places=2)
760        nose.tools.assert_not_almost_equal(N.interp(0.25,res["time"],res["y"]),0.5,places=2)
761        nose.tools.assert_not_almost_equal(N.interp(2.75,res["time"],res["y"]),0.5,places=2)
762        nose.tools.assert_not_almost_equal(N.interp(0.75,res["time"],res["x"]),0.5,places=2)
763        nose.tools.assert_not_almost_equal(N.interp(2.25,res["time"],res["x"]),0.5,places=2)
764        nose.tools.assert_almost_equal(N.interp(1.5,res["time"],res["y"]),0.5,places=2)
765       
766    @testattr(stddist_full = True)
767    def test_relation_ge(self):
768        model = load_fmu("RelationTests_RelationGE.fmu")
769        opts = model.simulate_options()
770        opts["CVode_options"]["maxh"] = 0.001
771        res = model.simulate(final_time=3.5, input=input_object,options=opts)
772       
773        nose.tools.assert_almost_equal(N.interp(0.75,res["time"],res["y"]),0.5,places=2)
774        nose.tools.assert_almost_equal(N.interp(2.25,res["time"],res["y"]),0.5,places=2)
775        nose.tools.assert_not_almost_equal(N.interp(0.25,res["time"],res["y"]),0.5,places=2)
776        nose.tools.assert_not_almost_equal(N.interp(2.75,res["time"],res["y"]),0.5,places=2)
777        nose.tools.assert_not_almost_equal(N.interp(0.75,res["time"],res["x"]),0.5,places=2)
778        nose.tools.assert_not_almost_equal(N.interp(2.25,res["time"],res["x"]),0.5,places=2)
779        nose.tools.assert_almost_equal(N.interp(1.5,res["time"],res["y"]),0.5,places=2)
780       
781    @testattr(stddist_full = True)
782    def test_relation_geinv(self):
783        model = load_fmu("RelationTests_RelationGEInv.fmu")
784        opts = model.simulate_options()
785        opts["CVode_options"]["maxh"] = 0.001
786        res = model.simulate(final_time=3.5, input=input_object,options=opts)
787       
788        nose.tools.assert_almost_equal(N.interp(0.75,res["time"],res["y"]),0.5,places=2)
789        nose.tools.assert_almost_equal(N.interp(2.25,res["time"],res["y"]),0.5,places=2)
790        nose.tools.assert_not_almost_equal(N.interp(0.25,res["time"],res["y"]),0.5,places=2)
791        nose.tools.assert_not_almost_equal(N.interp(2.75,res["time"],res["y"]),0.5,places=2)
792        nose.tools.assert_not_almost_equal(N.interp(0.75,res["time"],res["x"]),0.5,places=2)
793        nose.tools.assert_not_almost_equal(N.interp(2.25,res["time"],res["x"]),0.5,places=2)
794        nose.tools.assert_almost_equal(N.interp(1.5,res["time"],res["y"]),0.5,places=2)
795       
796    @testattr(stddist_full = True)
797    def test_relation_leinit(self):
798        model = load_fmu("RelationTests_RelationLEInit.fmu")
799       
800        res = model.simulate(final_time=0.1)
801       
802        nose.tools.assert_almost_equal(res.initial("x"),1.0,places=3)
803        nose.tools.assert_almost_equal(res.initial("y"),0.0,places=3)
804       
805    @testattr(stddist_full = True)
806    def test_relation_geinit(self):
807        model = load_fmu("RelationTests_RelationGEInit.fmu")
808       
809        res = model.simulate(final_time=0.1)
810       
811        nose.tools.assert_almost_equal(res.initial("x"),0.0,places=3)
812        nose.tools.assert_almost_equal(res.initial("y"),1.0,places=3)
813
814    @testattr(stddist_full = True)
815    def test_relation_op_1(self):
816        model = load_fmu("RelationTests_TestRelationalOp1.fmu")
817       
818        res = model.simulate(final_time=10)
819       
820        nose.tools.assert_almost_equal(N.interp(3.00,res["time"],res["der(v1)"]),1.0,places=3)
821        nose.tools.assert_almost_equal(N.interp(3.40,res["time"],res["der(v1)"]),0.0,places=3)
822        nose.tools.assert_almost_equal(N.interp(8.00,res["time"],res["der(v1)"]),0.0,places=3)
823        nose.tools.assert_almost_equal(N.interp(8.25,res["time"],res["der(v1)"]),1.0,places=3)
824        nose.tools.assert_almost_equal(N.interp(4.00,res["time"],res["der(v2)"]),1.0,places=3)
825        nose.tools.assert_almost_equal(N.interp(4.20,res["time"],res["der(v2)"]),0.0,places=3)
826        nose.tools.assert_almost_equal(N.interp(7.00,res["time"],res["der(v2)"]),0.0,places=3)
827        nose.tools.assert_almost_equal(N.interp(7.20,res["time"],res["der(v2)"]),1.0,places=3)
828
829class Test_NonLinear_Systems:
830   
831    @classmethod
832    def setUpClass(cls):
833        """
834        Compile the test model.
835        """
836        file_name = os.path.join(get_files_path(), 'Modelica', 'NonLinear.mo')
837
838        compile_fmu("NonLinear.NominalStart1", file_name)
839        compile_fmu("NonLinear.NominalStart2", file_name)
840        compile_fmu("NonLinear.NominalStart3", file_name)
841        compile_fmu("NonLinear.NominalStart4", file_name)
842        compile_fmu("NonLinear.NominalStart5", file_name)
843        compile_fmu("NonLinear.NominalStart6", file_name)
844        compile_fmu("NonLinear.DoubleRoot1", file_name)
845        compile_fmu("NonLinear.NonLinear3", file_name)
846        compile_fmu("NonLinear.NonLinear4", file_name)
847        compile_fmu("NonLinear.ResidualHeuristicScaling1", file_name)
848        compile_fmu("NonLinear.EventIteration1", file_name)
849        compile_fmu("NonLinear.NonLinear6", file_name)
850        compile_fmu("NonLinear.NonLinear7", file_name)
851        compile_fmu("NonLinear.RealTimeSolver1", file_name, compile_to="RT_init.fmu", version=1.0, compiler_options={"init_nonlinear_solver":"realtime"})
852        compile_fmu("NonLinear.RealTimeSolver1", file_name, compile_to="RT_ode.fmu", version=1.0, compiler_options={"nonlinear_solver":"realtime"})
853   
854    @testattr(stddist_base= True)
855    def test_realtime_solver_init(self):
856        model = load_fmu("RT_init.fmu", log_level=4)
857        model.set("_log_level", 4)
858       
859        model.initialize()
860       
861        from pyjmi.log import parser
862       
863        log = parser.parse_jmi_log("RT_init_log.txt")
864        assert len(log.find("RealtimeConvergence")) > 0
865       
866    @testattr(stddist_base= True)
867    def test_realtime_solver(self):
868        model = load_fmu("RT_ode.fmu", log_level=4)
869        model.set("_log_level", 4)
870       
871        model.initialize()
872       
873        from pyjmi.log import parser
874       
875        log = parser.parse_jmi_log("RT_ode_log.txt")
876        assert len(log.find("RealtimeConvergence")) == 3 #Three invocations during initialization
877       
878        model.simulate(options={"initialize":False})
879       
880        log = parser.parse_jmi_log("RT_ode_log.txt")
881        assert len(log.find("RealtimeConvergence")) > 3
882   
883    @testattr(windows_base = True)
884    def test_Brent_AD(self):
885       
886        model = load_fmu(os.path.join(get_files_path(), "FMUs/ME2.0", "NonLinear_NonLinear5.fmu"), log_level=6)
887        model.set("_log_level", 8)
888       
889        model.initialize()
890       
891        def get_history(filename):
892            import re
893            data = [[],[]]
894            with open(filename, 'r') as f:
895                line = f.readline()
896                while line:
897                    if line.find("Iteration variable") != -1:
898                        iv = re.search('<value name="ivs">(.*)</value>, Function', line).group(1).strip()
899                        df = re.search('<value name="df">(.*)</value>, Delta', line).group(1).strip()
900                        data[0].append(float(iv))
901                        data[1].append(float(df))
902                    line = f.readline()
903            return data[0], data[1]
904           
905        ivs,df = get_history("NonLinear_NonLinear5_log.txt")
906
907        fprime = lambda y: -200*y;
908
909        for i,iv in enumerate(ivs):
910            nose.tools.assert_almost_equal(fprime(iv) ,df[i], places=12) 
911           
912    @testattr(stddist_base = True)
913    def test_Brent_double_root1(self):
914        def run_model(init):
915            model = load_fmu("NonLinear_DoubleRoot1.fmu")
916            model.set("_use_Brent_in_1d", True)
917            model.set("p", init)
918            model.initialize()
919            return model.get("x")
920       
921        sol_pos = N.sqrt(1e-7)+1.5
922        sol_neg =-N.sqrt(1e-7)+1.5
923
924        nose.tools.assert_almost_equal(run_model(sol_pos+1e-16) ,sol_pos)
925        nose.tools.assert_almost_equal(run_model(sol_pos-1e-16) ,sol_pos)
926        nose.tools.assert_almost_equal(run_model(sol_pos+1e-14) ,sol_pos)
927        nose.tools.assert_almost_equal(run_model(sol_pos-1e-14) ,sol_pos)
928       
929        nose.tools.assert_almost_equal(run_model(sol_neg+1e-16) ,sol_neg)
930        nose.tools.assert_almost_equal(run_model(sol_neg-1e-16) ,sol_neg)
931        nose.tools.assert_almost_equal(run_model(sol_neg+1e-14) ,sol_neg)
932        nose.tools.assert_almost_equal(run_model(sol_neg-1e-14) ,sol_neg)
933       
934    @testattr(stddist_base = True)
935    def test_Brent_close_to_root(self):
936        model = load_fmu("NonLinear_NonLinear3.fmu")
937        model.set("_use_Brent_in_1d", True)
938       
939        model.set("i",-9.9760004108556469E-03)
940        model.initialize()
941       
942        nose.tools.assert_almost_equal(model.get("i"),-9.9760004108556469E-03)
943       
944    @testattr(stddist_base = True)
945    def test_Brent_close_to_root(self):
946        model = load_fmu("NonLinear_NonLinear4.fmu")
947        model.set("_use_Brent_in_1d", True)
948       
949        scale = model.get("scale")
950        i = -9.9760004108556469E-03*scale
951        model.set("i_start",i)
952        model.initialize()
953        nose.tools.assert_almost_equal(model.get("i"),i)
954       
955        model.reset()
956       
957        model.set("i_start", i+i*1e-15)
958        model.initialize()
959        nose.tools.assert_almost_equal(model.get("i"),i)
960       
961        model.reset()
962       
963        model.set("i_start", i-i*1e-15)
964        model.initialize()
965        nose.tools.assert_almost_equal(model.get("i"),i)
966       
967       
968   
969    @testattr(stddist_base = True)
970    def test_nominals_fallback_1(self):
971        model = load_fmu("NonLinear_NominalStart1.fmu")
972        model.set("_nle_solver_use_nominals_as_fallback", True)
973        model.initialize()
974   
975    @testattr(stddist_base = True)
976    def test_nominals_fallback_2(self):
977        model = load_fmu("NonLinear_NominalStart1.fmu")
978        model.set("_nle_solver_use_nominals_as_fallback", False)
979        nose.tools.assert_raises(FMUException, model.initialize)
980       
981    @testattr(stddist_base = True)
982    def test_nominals_fallback_3(self):
983        model = load_fmu("NonLinear_NominalStart2.fmu")
984        model.set("_nle_solver_use_nominals_as_fallback", True)
985        nose.tools.assert_raises(FMUException, model.initialize)
986       
987    @testattr(stddist_base = True)
988    def test_nominals_fallback_4(self):
989        model = load_fmu("NonLinear_NominalStart4.fmu")
990        model.set("_use_Brent_in_1d", False)
991        model.set("_nle_solver_use_nominals_as_fallback", True)
992        nose.tools.assert_raises(FMUException, model.initialize)
993
994    @testattr(stddist_base = True)
995    def test_nominals_fallback_5(self):
996        model = load_fmu("NonLinear_NominalStart5.fmu")
997        model.set("_use_Brent_in_1d", False)
998        model.set("_nle_solver_use_nominals_as_fallback", True)
999        nose.tools.assert_raises(FMUException, model.initialize)
1000       
1001    @testattr(stddist_base = True)
1002    def test_nominals_fallback_6(self):
1003        model = load_fmu("NonLinear_NominalStart3.fmu")
1004        model.set("_use_Brent_in_1d", False)
1005        model.set("_nle_solver_use_nominals_as_fallback", True)
1006        model.set('_nle_jacobian_update_mode', 0)
1007        model.initialize()
1008       
1009        nose.tools.assert_almost_equal(model.get("x") ,2.76929235)
1010       
1011    @testattr(stddist_base = True)
1012    def test_nominals_fallback_7(self):
1013        model = load_fmu("NonLinear_NominalStart6.fmu")
1014        model.set("_nle_solver_use_nominals_as_fallback", True)
1015        model.initialize()
1016       
1017        nose.tools.assert_almost_equal(model.get("x"), 0.680716920494911)
1018        nose.tools.assert_almost_equal(model.get("y"), 0.0)
1019       
1020    @testattr(stddist_base = True)
1021    def test_residual_scaling_heuristics(self):
1022        model = load_fmu("NonLinear_ResidualHeuristicScaling1.fmu")
1023        model.set("_use_Brent_in_1d", False)
1024        model.initialize()
1025        nose.tools.assert_almost_equal(model.get('state_a_p'), 17.78200351)
1026       
1027    @testattr(stddist_base = True)
1028    def test_event_iternation_inf_check_warmup(self):
1029        # Test where event inf check cannot only look at the switches but need
1030        # to look at the iteration variables too. Generally this is needed for
1031        # models with systems that have many solutions and bad start values. In
1032        # this model the variable iter_var_1 will go from 300 to ca 874 and then
1033        # if it don't get stuck in inf check it will go to 872.98062403
1034        model = load_fmu("NonLinear_EventIteration1.fmu")
1035        model.initialize()
1036        nose.tools.assert_almost_equal(model.get('iter_var_1'), 872.98062403)
1037       
1038    @testattr(stddist_base = True)
1039    def test_fixed_false_start_attribute(self):
1040        model = load_fmu("NonLinear_NonLinear6.fmu")
1041        model.initialize()
1042        nose.tools.assert_almost_equal(model.get('x'), 1.0)
1043        nose.tools.assert_almost_equal(model.get('z'), -1.0)
1044       
1045    @testattr(stddist_base = True)
1046    def test_fixed_false_start_attribute_brent(self):
1047        model = load_fmu("NonLinear_NonLinear7.fmu")
1048        model.initialize()
1049        nose.tools.assert_almost_equal(model.get('x'), 1.0)
1050        nose.tools.assert_almost_equal(model.get('z'), 1.0)
1051   
1052class Test_Singular_Systems:
1053   
1054    @classmethod
1055    def setUpClass(cls):
1056        """
1057        Compile the test model.
1058        """
1059        file_name = os.path.join(get_files_path(), 'Modelica', 'Singular.mo')
1060
1061        compile_fmu("Singular.LinearInf", file_name)
1062        compile_fmu("Singular.Linear2", file_name)
1063        compile_fmu("Singular.LinearEvent1", file_name)
1064        compile_fmu("Singular.LinearEvent2", file_name)
1065        compile_fmu("Singular.NonLinear1", file_name)
1066        compile_fmu("Singular.NonLinear4", file_name)
1067        compile_fmu("Singular.NonLinear5", file_name)
1068        compile_fmu("Singular.NoMinimumNormSolution", file_name)
1069        compile_fmu("Singular.ZeroColumnJacobian", file_name)
1070        compile_fmu("Singular.ZeroColumnJacobian2", file_name)
1071        compile_fmu("Singular.LinearEvent3", file_name)
1072   
1073    @testattr(stddist_base = True)
1074    def test_linear_event_1(self):
1075        model = load_fmu("Singular_LinearEvent1.fmu", log_level=3)
1076        model.set("_log_level", 3)
1077       
1078        res = model.simulate(final_time=2)
1079        nose.tools.assert_almost_equal(res.final('y') ,1.000000000)
1080       
1081    @testattr(stddist_base = True)
1082    def test_linear_event_2(self):
1083        model = load_fmu("Singular_LinearEvent2.fmu", log_level=3)
1084        model.set("_log_level", 3)
1085       
1086        res = model.simulate(final_time=4)
1087        nose.tools.assert_almost_equal(res.final('y') ,1.000000000)
1088        nose.tools.assert_almost_equal(res.final('w') ,2.000000000)
1089       
1090    @testattr(stddist_base = True)
1091    def test_linear_event_3(self):
1092        model = load_fmu("Singular_LinearEvent3.fmu", log_level=3)
1093        model.set("_log_level", 3)
1094       
1095        opts = model.simulate_options()
1096        opts["ncp"] = 7
1097        opts["CVode_options"]["maxh"] = 0.49
1098       
1099        res = model.simulate(final_time=1, options=opts)
1100        x = res["x"]
1101        for i in range(4):
1102            nose.tools.assert_almost_equal(x[i] ,0.000000000)
1103        for i in range(4,8):
1104            nose.tools.assert_almost_equal(x[i] ,0.0100000)
1105   
1106    @testattr(stddist_base = True)
1107    def test_linear_inf_1(self):
1108       
1109        model = load_fmu("Singular_LinearInf.fmu", log_level=6)
1110        model.set("_log_level", 6)
1111       
1112        model.set("a22", N.inf)
1113        nose.tools.assert_raises(FMUException, model.initialize)
1114       
1115    @testattr(stddist_base = True)
1116    def test_linear_inf_2(self):
1117       
1118        model = load_fmu("Singular_LinearInf.fmu", log_level=6)
1119        model.set("_log_level", 6)
1120       
1121        model.set("a33", 0)
1122        model.set("a22", N.inf)
1123        nose.tools.assert_raises(FMUException, model.initialize)
1124       
1125    @testattr(stddist_base = True)
1126    def test_linear_inf_3(self):
1127       
1128        model = load_fmu("Singular_LinearInf.fmu", log_level=6)
1129        model.set("_log_level", 6)
1130       
1131        model.set("b[1]", N.inf)
1132        nose.tools.assert_raises(FMUException, model.initialize)
1133       
1134    @testattr(stddist_base = True)
1135    def test_nonlinear_1(self):
1136       
1137        model = load_fmu("Singular_NonLinear1.fmu")
1138        model.set("a33", 0)
1139        model.set("b[3]", 0)
1140       
1141        model.initialize()
1142       
1143        nose.tools.assert_almost_equal(model.get("x") ,1.000000000)
1144        nose.tools.assert_almost_equal(model.get("y") ,2.000000000)
1145        nose.tools.assert_almost_equal(model.get("z") ,0.000000000)
1146       
1147    @testattr(stddist_base = True)
1148    def test_nonlinear_2(self):
1149       
1150        model = load_fmu("Singular_NonLinear1.fmu")
1151        model.set("a33", 0)
1152        model.set("b[3]", 3)
1153       
1154        nose.tools.assert_raises(FMUException, model.initialize)
1155       
1156    @testattr(stddist_base = True)
1157    def test_nonlinear_3(self):
1158       
1159        model = load_fmu("Singular_NonLinear1.fmu")
1160        model.set("a33", 0)
1161        model.set("a22", 1e-5)
1162        model.set("b[3]", 0)
1163       
1164        model.initialize()
1165       
1166        nose.tools.assert_almost_equal(model.get("x") ,1.000000000)
1167        nose.tools.assert_almost_equal(model.get("y") ,200000.0000)
1168        nose.tools.assert_almost_equal(model.get("z") ,0.000000000)
1169       
1170    @testattr(stddist_base = True)
1171    def test_nonlinear_4(self):
1172       
1173        model = load_fmu("Singular_NonLinear1.fmu")
1174        model.set("a33", 0)
1175        model.set("a22", 1e10)
1176        model.set("b[3]", 0)
1177       
1178        model.initialize()
1179       
1180        nose.tools.assert_almost_equal(model.get("x") ,1.000000000)
1181        nose.tools.assert_almost_equal(model.get("y") ,2e-10)
1182        nose.tools.assert_almost_equal(model.get("z") ,0.000000000)
1183       
1184    @testattr(stddist_base = True)
1185    def test_nonlinear_6(self):
1186       
1187        model = load_fmu("Singular_NonLinear5.fmu")
1188       
1189        model.initialize()
1190       
1191        nose.tools.assert_almost_equal(model.get("x") ,5)
1192        nose.tools.assert_almost_equal(model.get("y") ,0)
1193        nose.tools.assert_almost_equal(model.get("z") ,0.000000000)
1194   
1195    @testattr(stddist_base = True)
1196    def test_nonlinear_5(self):
1197        model = load_fmu("Singular_NonLinear4.fmu")
1198
1199        model.set("b[3]", 0)
1200        model.set("a31", 1)
1201        model.set("a32", -0.5)
1202
1203        res = model.simulate()
1204       
1205        nose.tools.assert_almost_equal(res["z"][0] ,0.000000000)
1206        nose.tools.assert_almost_equal(res["z"][-1] ,-1.000000000)
1207   
1208    @testattr(stddist_base = True)
1209    def test_no_valid_minimum_norm_sol(self):
1210        model = load_fmu("Singular_NoMinimumNormSolution.fmu", log_level=3)
1211        model.set("_log_level", 3)
1212        model.set_log_level(3)
1213        nose.tools.assert_raises(FMUException, model.initialize)
1214   
1215    @testattr(stddist_base = True)
1216    def test_zero_column_jacobian(self):
1217        model = load_fmu("Singular_ZeroColumnJacobian.fmu");
1218        res = model.simulate();
1219        nose.tools.assert_almost_equal(res["x"][0], -1)
1220       
1221    @testattr(stddist_base = True)
1222    def test_zero_column_jacobian2(self):
1223        model = load_fmu("Singular_ZeroColumnJacobian2.fmu");
1224        res = model.simulate();
1225        nose.tools.assert_almost_equal(res["x"][0], -1)
1226
1227class Test_FMI_ODE_CS_2:
1228    @classmethod
1229    def setUpClass(cls):
1230        """
1231        Compile the test model.
1232        """
1233        file_name = os.path.join(get_files_path(), 'Modelica', 'noState.mo')
1234        file_name_in = os.path.join(get_files_path(), 'Modelica', 'InputTests.mo')
1235        file_name_linear = os.path.join(get_files_path(), 'Modelica', 'Linear.mo')
1236        file_name_time_event = os.path.join(get_files_path(), 'Modelica', 'TimeEvents.mo')
1237
1238        _in3_name = compile_fmu("LinearTest.Linear1", file_name_linear, version=2.0, target="cs")
1239        _t1_name = compile_fmu("TimeEvents.Basic5", file_name_time_event, version=2.0, target="cs")
1240        _t1_name = compile_fmu("TimeEvents.Advanced5", file_name_time_event, version=2.0, target="cs")
1241        compile_fmu("Inputs.PlantDiscreteInputs", file_name_in, version=2.0, target="cs")
1242       
1243    @testattr(stddist_base = True)
1244    def test_changing_discrete_inputs(self):
1245        model = load_fmu("Inputs_PlantDiscreteInputs.fmu")
1246        opts = model.simulate_options()
1247       
1248        def step(time):
1249            "A step function that goes from 1 to 0 at time=0.28"
1250            return time < 0.28
1251       
1252        input = ('onSwitch', step)
1253        res = model.simulate(final_time=0.8, options=opts, input=input)
1254        nose.tools.assert_almost_equal(res.final("T"), 11.22494, 2)
1255       
1256    @testattr(stddist_base = True)
1257    def test_changing_discrete_inputs_many_times(self):
1258        model = load_fmu("Inputs_PlantDiscreteInputs.fmu")
1259        opts = model.simulate_options()
1260       
1261        def step(time):
1262            """
1263            A step function that goes from 1 to 0 at time=0.28
1264            and from 0 to 1 at time=0.55
1265            """
1266            return time < 0.28 or time > 0.55
1267       
1268        input = ('onSwitch', step)
1269        res = model.simulate(final_time=0.8, options=opts, input=input)
1270        nose.tools.assert_almost_equal(res.final("T"), 20.67587, 2)
1271       
1272    @testattr(stddist_full = True)
1273    def test_updated_values_in_result(self):
1274        model = load_fmu("LinearTest_Linear1.fmu")
1275        opts = model.simulate_options()
1276       
1277        res = model.simulate(final_time=1,options=opts)
1278       
1279        for i in range(len(res["der(x)"])):
1280            assert res["der(x)"][i] == 0.0
1281
1282    @testattr(stddist_full = True)
1283    def test_time_event_basic_5(self):
1284        model = load_fmu("TimeEvents_Basic5.fmu")
1285        opts = model.simulate_options()
1286       
1287        res = model.simulate(final_time=1,options=opts)
1288       
1289        assert res["der(x)"][-1] == -1.0
1290       
1291    @testattr(stddist_base = True)
1292    def test_time_event_at_do_step_end(self):
1293        model = load_fmu("TimeEvents_Advanced5.fmu")
1294        opts = model.simulate_options()
1295        opts["ncp"] = 100
1296        res = model.simulate(final_time=1,options=opts)
1297       
1298        nose.tools.assert_almost_equal(res.final("x"), 3.89, 2)
1299
1300class Test_FMI_ODE_CS:
1301    @classmethod
1302    def setUpClass(cls):
1303        """
1304        Compile the test model.
1305        """
1306        file_name = os.path.join(get_files_path(), 'Modelica', 'noState.mo')
1307        file_name_in = os.path.join(get_files_path(), 'Modelica', 'InputTests.mo')
1308        file_name_linear = os.path.join(get_files_path(), 'Modelica', 'Linear.mo')
1309        file_name_time_event = os.path.join(get_files_path(), 'Modelica', 'TimeEvents.mo')
1310
1311        _in3_name = compile_fmu("LinearTest.Linear1", file_name_linear, target="cs", version=1.0)
1312        _t1_name = compile_fmu("TimeEvents.Advanced5", file_name_time_event, target="cs", version=1.0)
1313        _cc_name = compile_fmu("Modelica.Mechanics.Rotational.Examples.CoupledClutches", target="cs", version=1.0)
1314   
1315    @testattr(stddist_full = True)
1316    def test_time_out(self):
1317        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1318       
1319        res = model.simulate() #Verify that it works to simulate
1320        model.reset()
1321       
1322        opts = model.simulate_options()
1323        opts["time_limit"] = 0.001
1324       
1325        nose.tools.assert_raises(TimeLimitExceeded, model.simulate, options=opts)
1326        model.reset()
1327       
1328        opts["time_limit"] = 10
1329        res = model.simulate() #Verify that it works with a high time out
1330       
1331   
1332    @testattr(stddist_base = True)
1333    def test_time_event_at_do_step_end(self):
1334        model = load_fmu("TimeEvents_Advanced5.fmu")
1335        opts = model.simulate_options()
1336        opts["ncp"] = 100
1337        res = model.simulate(final_time=1,options=opts)
1338       
1339        nose.tools.assert_almost_equal(res.final("x"), 3.89, 2)
1340       
1341    @testattr(stddist_full = True)
1342    def test_updated_values_in_result(self):
1343        model = load_fmu("LinearTest_Linear1.fmu")
1344        opts = model.simulate_options()
1345       
1346        res = model.simulate(final_time=1,options=opts)
1347       
1348        for i in range(len(res["der(x)"])):
1349            assert res["der(x)"][i] == 0.0
1350           
1351
1352class Test_FMI_ODE_2:
1353    """
1354    This class tests pyfmi.simulation.assimulo.FMIODE and together
1355    with Assimulo. Requires that Assimulo is installed.
1356    """
1357   
1358    @classmethod
1359    def setUpClass(cls):
1360        """
1361        Compile the test model.
1362        """
1363        file_name = os.path.join(get_files_path(), 'Modelica', 'noState.mo')
1364        file_name_in = os.path.join(get_files_path(), 'Modelica', 'InputTests.mo')
1365        file_name_linear = os.path.join(get_files_path(), 'Modelica', 'Linear.mo')
1366
1367        _ex1_name = compile_fmu("NoState.Example1", file_name, version=2.0)
1368        _ex2_name = compile_fmu("NoState.Example2", file_name, version=2.0)
1369        _in1_name = compile_fmu("Inputs.SimpleInput", file_name_in, version=2.0)
1370        _in_disc_name = compile_fmu("Inputs.PlantDiscreteInputs", file_name_in, version=2.0)
1371        _cc_name = compile_fmu("Modelica.Mechanics.Rotational.Examples.CoupledClutches", version=2.0)
1372        #_in3_name = compile_fmu("LinearTest.Linear1", file_name_linear)
1373   
1374    @testattr(stddist_full = True)
1375    def test_discrete_input(self):
1376        model = load_fmu("Inputs_PlantDiscreteInputs.fmu")
1377       
1378        input_object = (["Tenv","onSwitch"], N.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]))
1379       
1380        res = model.simulate(input=input_object)
1381       
1382        nose.tools.assert_almost_equal(res.final('onSwitch') ,1.000000000) 
1383       
1384        model.reset()
1385       
1386        input_object = (["Tenv","onSwitch"], N.array([[0.0, 0.0], [1.0, 1.0]]))
1387       
1388        nose.tools.assert_raises(FMUException, model.simulate, input=input_object)
1389   
1390   
1391    @testattr(stddist_full = True)
1392    def test_simple_input(self):
1393        model = load_fmu("Inputs_SimpleInput.fmu")
1394       
1395        input_object = ("u", N.array([[0.0, 0.0], [1.0, 1.0]]))
1396       
1397        res = model.simulate(input=input_object)
1398       
1399        nose.tools.assert_almost_equal(res.final('y') ,1.000000000)
1400        nose.tools.assert_almost_equal(res.final('u') ,1.000000000)
1401       
1402        model.reset()
1403       
1404        input_object = ("u", N.array([[0.0, 0.0], [1.0, 1.0]]))
1405       
1406        res = model.simulate(input=input_object)
1407       
1408        nose.tools.assert_almost_equal(res.final('y') ,1.000000000)
1409        nose.tools.assert_almost_equal(res.final('u') ,1.000000000)
1410   
1411    @testattr(stddist_full = True)
1412    def test_input_values_not_input(self):
1413        model = load_fmu("Inputs_SimpleInput.fmu")
1414       
1415        input_object = ("y", N.array([[0.0, 0.0], [1.0, 1.0]]))
1416       
1417        nose.tools.assert_raises(FMUException, model.simulate, input=input_object)
1418   
1419    @testattr(stddist_base = True)
1420    def test_cc_with_radau(self):
1421        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1422        opts = model.simulate_options()
1423        opts["solver"] = "Radau5ODE"
1424       
1425        res = model.simulate(final_time=1.5,options=opts)
1426       
1427        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-3
1428   
1429    @testattr(stddist_base = True)
1430    def test_cc_with_sparse(self):
1431
1432        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1433        opts = model.simulate_options()
1434        opts["solver"] = "CVode"
1435        opts["with_jacobian"] = True
1436        opts["CVode_options"]["rtol"] = 1e-7
1437        opts["CVode_options"]["linear_solver"] = "SPARSE"
1438       
1439        res = model.simulate(final_time=1.5,options=opts)
1440       
1441        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
1442   
1443    @testattr(stddist_base = True)
1444    def test_with_jacobian(self):
1445
1446        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1447        opts = model.simulate_options()
1448        opts["CVode_options"]["rtol"] = 1e-7
1449        assert opts["with_jacobian"] == "Default"
1450       
1451        res = model.simulate(final_time=1.5,options=opts)
1452        print res.final("J1.w")
1453        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
1454        assert res.solver.statistics["nfcnjacs"] > 0
1455       
1456        opts["with_jacobian"] = True
1457        model.reset()
1458   
1459        res = model.simulate(final_time=1.5,options=opts)
1460        print res.final("J1.w")
1461        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
1462        assert res.solver.statistics["nfcnjacs"] == 0
1463       
1464        opts["CVode_options"]["usejac"] = False
1465        model.reset()
1466   
1467        res = model.simulate(final_time=1.5,options=opts)
1468        print res.final("J1.w")
1469        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
1470        assert res.solver.statistics["nfcnjacs"] > 0
1471       
1472        opts["with_jacobian"] = False
1473        model.reset()
1474   
1475        res = model.simulate(final_time=1.5,options=opts)
1476        print res.final("J1.w")
1477        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
1478        assert res.solver.statistics["nfcnjacs"] > 0
1479
1480    @testattr(stddist_full = True)
1481    def test_no_state1(self):
1482        """
1483        Tests simulation when there is no state in the model (Example1).
1484        """
1485        model = load_fmu("NoState_Example1.fmu")
1486       
1487        res = model.simulate(final_time=10)
1488       
1489        nose.tools.assert_almost_equal(res.initial('x') ,1.000000000)
1490        nose.tools.assert_almost_equal(res.final('x'),-2.000000000)
1491        nose.tools.assert_almost_equal(res.initial('y') ,-1.000000000)
1492        nose.tools.assert_almost_equal(res.final('y'),-1.000000000)
1493        nose.tools.assert_almost_equal(res.initial('z') ,1.000000000)
1494        nose.tools.assert_almost_equal(res.final('z'),4.000000000)
1495       
1496    @testattr(stddist_full = True)
1497    def test_no_state2(self):
1498        """
1499        Tests simulation when there is no state in the model (Example2).
1500        """
1501        model = load_fmu("NoState_Example2.fmu")
1502       
1503        res = model.simulate(final_time=10)
1504       
1505        nose.tools.assert_almost_equal(res.initial('x') ,-1.000000000)
1506        nose.tools.assert_almost_equal(res.final('x'),-1.000000000)
1507       
1508    @testattr(stddist_full = True)
1509    def test_no_state1_radau(self):
1510        """
1511        Tests simulation when there is no state in the model (Example1).
1512        """
1513        model = load_fmu("NoState_Example1.fmu")
1514       
1515        res = model.simulate(final_time=10, options={"solver": "Radau5ODE"})
1516       
1517        nose.tools.assert_almost_equal(res.initial('x') ,1.000000000)
1518        nose.tools.assert_almost_equal(res.final('x'),-2.000000000)
1519        nose.tools.assert_almost_equal(res.initial('y') ,-1.000000000)
1520        nose.tools.assert_almost_equal(res.final('y'),-1.000000000)
1521        nose.tools.assert_almost_equal(res.initial('z') ,1.000000000)
1522        nose.tools.assert_almost_equal(res.final('z'),4.000000000)
1523
1524class Test_FMI_ODE:
1525    """
1526    This class tests pyfmi.simulation.assimulo.FMIODE and together
1527    with Assimulo. Requires that Assimulo is installed.
1528    """
1529   
1530    @classmethod
1531    def setUpClass(cls):
1532        """
1533        Compile the test model.
1534        """
1535        file_name = os.path.join(get_files_path(), 'Modelica', 'noState.mo')
1536        file_name_in = os.path.join(get_files_path(), 'Modelica', 'InputTests.mo')
1537        file_name_linear = os.path.join(get_files_path(), 'Modelica', 'Linear.mo')
1538
1539        _ex1_name = compile_fmu("NoState.Example1", file_name, version=1.0)
1540        _ex2_name = compile_fmu("NoState.Example2", file_name, version=1.0)
1541        _in1_name = compile_fmu("Inputs.SimpleInput", file_name_in, version=1.0)
1542        _in3_name = compile_fmu("Inputs.SimpleInput3", file_name_in, version=1.0)
1543        _cc_name = compile_fmu("Modelica.Mechanics.Rotational.Examples.CoupledClutches", version=1.0)
1544        _in3_name = compile_fmu("LinearTest.Linear1", file_name_linear, version=1.0)
1545       
1546    def setUp(self):
1547        """
1548        Load the test model.
1549        """
1550        self._bounce  = load_fmu('bouncingBall.fmu',path_to_fmus_me1)
1551        self._dq = load_fmu('dq.fmu',path_to_fmus_me1)
1552        self._bounce.initialize()
1553        self._dq.initialize()
1554        self._bounceSim = FMIODE(self._bounce)
1555        self._dqSim     = FMIODE(self._dq)
1556       
1557    @testattr(stddist_full = True)
1558    def test_max_log_file_size(self):
1559        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu", log_level=5)
1560        model.set("_log_level", 5)
1561        model.set_max_log_size(10)
1562       
1563        model.simulate()
1564       
1565        with open("Modelica_Mechanics_Rotational_Examples_CoupledClutches_log.txt") as f:
1566            for line in f:
1567                pass
1568            assert "The log file has reached its maximum size" in line
1569       
1570    @testattr(stddist_full = True)
1571    def test_updated_values_in_result(self):
1572        model = load_fmu("LinearTest_Linear1.fmu")
1573        opts = model.simulate_options()
1574        opts["solver"] = "CVode"
1575       
1576        res = model.simulate(final_time=1,options=opts)
1577       
1578        for i in range(len(res["der(x)"])):
1579            assert res["der(x)"][i] == 0.0
1580
1581    @testattr(stddist_base = True)
1582    def test_cc_with_cvode(self):
1583        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1584        opts = model.simulate_options()
1585        opts["solver"] = "CVode"
1586        opts["CVode_options"]["rtol"] = 1e-7
1587       
1588        res = model.simulate(final_time=1.5,options=opts)
1589       
1590        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
1591
1592    @testattr(stddist_full = True)
1593    def test_reset_internal_variables(self):
1594        model = load_fmu("Inputs_SimpleInput.fmu")
1595       
1596        model.initialize()
1597       
1598        model.set("u",2)
1599        model.time = 1
1600        assert model.get("u") == 2.0
1601       
1602        model.time = 0.5
1603        assert model.get("u") == 2.0
1604       
1605    @testattr(stddist_full = True)
1606    def test_reset_internal_variables2(self):
1607        model = load_fmu("Inputs_SimpleInput3.fmu")
1608       
1609        model.initialize()
1610       
1611        model.set("p",2)
1612        model.time = 1
1613        assert model.get("p") == 2.0
1614       
1615        model.time = 0.5
1616        assert model.get("p") == 2.0
1617       
1618    @testattr(stddist_base = True)
1619    def test_cc_with_radau(self):
1620        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1621        opts = model.simulate_options()
1622        opts["solver"] = "Radau5ODE"
1623       
1624        res = model.simulate(final_time=1.5,options=opts)
1625       
1626        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-3
1627   
1628    @testattr(stddist_base = True)
1629    def test_cc_with_dopri(self):
1630        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1631        opts = model.simulate_options()
1632        opts["solver"] = "Dopri5"
1633       
1634        res = model.simulate(final_time=1.5,options=opts)
1635       
1636        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-3
1637       
1638    @testattr(stddist_base = True)
1639    def test_cc_with_lsodar(self):
1640        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1641        opts = model.simulate_options()
1642        opts["solver"] = "LSODAR"
1643        opts["LSODAR_options"]["rtol"] = 1e-6
1644       
1645        res = model.simulate(final_time=1.5,options=opts)
1646       
1647        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-3
1648       
1649    @testattr(stddist_base = True)
1650    def test_cc_with_rodas(self):
1651        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1652        opts = model.simulate_options()
1653        opts["solver"] = "RodasODE"
1654        opts["RodasODE_options"]["rtol"] = 1e-6
1655       
1656        res = model.simulate(final_time=1.5,options=opts)
1657       
1658        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-3
1659       
1660    @testattr(stddist_base = True)
1661    def test_cc_with_impliciteuler(self):
1662        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1663        opts = model.simulate_options()
1664        opts["solver"] = "ImplicitEuler"
1665        opts["ImplicitEuler_options"]["rtol"] = 1e-8
1666        opts["ImplicitEuler_options"]["atol"] = 1e-8
1667        opts["ImplicitEuler_options"]["h"] = 0.001
1668       
1669        res = model.simulate(final_time=1.5,options=opts)
1670        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-2
1671       
1672    @testattr(stddist_base = True)
1673    def test_cc_with_expliciteuler(self):
1674        model = load_fmu("Modelica_Mechanics_Rotational_Examples_CoupledClutches.fmu")
1675        opts = model.simulate_options()
1676        opts["solver"] = "ExplicitEuler"
1677        opts["ExplicitEuler_options"]["h"] = 0.001
1678
1679        res = model.simulate(final_time=1.5,options=opts)
1680        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-2
1681       
1682    @testattr(stddist_full = True)
1683    def test_no_state1(self):
1684        """
1685        Tests simulation when there is no state in the model (Example1).
1686        """
1687        model = load_fmu("NoState_Example1.fmu")
1688       
1689        res = model.simulate(final_time=10)
1690       
1691        nose.tools.assert_almost_equal(res.initial('x') ,1.000000000)
1692        nose.tools.assert_almost_equal(res.final('x'),-2.000000000)
1693        nose.tools.assert_almost_equal(res.initial('y') ,-1.000000000)
1694        nose.tools.assert_almost_equal(res.final('y'),-1.000000000)
1695        nose.tools.assert_almost_equal(res.initial('z') ,1.000000000)
1696        nose.tools.assert_almost_equal(res.final('z'),4.000000000)
1697       
1698    @testattr(stddist_full = True)
1699    def test_no_state2(self):
1700        """
1701        Tests simulation when there is no state in the model (Example2).
1702        """
1703        model = load_fmu("NoState_Example2.fmu")
1704       
1705        res = model.simulate(final_time=10)
1706       
1707        nose.tools.assert_almost_equal(res.initial('x') ,-1.000000000)
1708        nose.tools.assert_almost_equal(res.final('x'),-1.000000000)
1709       
1710    @testattr(stddist_full = True)
1711    def test_result_enumeration_2(self):
1712        file_name = os.path.join(get_files_path(), 'Modelica', 'Enumerations.mo')
1713
1714        enum_name = compile_fmu("Enumerations.Enumeration2", file_name)
1715        model = load_fmu(enum_name)
1716       
1717        opts = model.simulate_options()
1718       
1719        res = model.simulate(options=opts)
1720        assert res["one"][0] == 1
1721        assert res["one"][-1] == 3
1722        assert res["two"][0] == 2
1723        assert res["two"][-1] == 2
1724        assert res["three"][0] == 3
1725        assert res["three"][-1] == 3
1726       
1727        model.reset()
1728        opts["result_handling"] = "memory"
1729       
1730        res = model.simulate(options=opts)
1731       
1732        assert res["one"][0] == 1
1733        assert res["one"][-1] == 3
1734        assert res["two"][0] == 2
1735        assert res["two"][-1] == 2
1736        assert res["three"][0] == 3
1737        assert res["three"][-1] == 3
1738       
1739        from pyfmi.common.io import ResultHandlerCSV
1740        model.reset()
1741        opts["result_handling"] = "custom"
1742        opts["result_handler"] = ResultHandlerCSV(model)
1743       
1744        res = model.simulate(options=opts)
1745       
1746        assert res["one"][0] == 1
1747        assert res["one"][-1] == 3
1748        assert res["two"][0] == 2
1749        assert res["two"][-1] == 2
1750        assert res["three"][0] == 3
1751        assert res["three"][-1] == 3
1752   
1753    @testattr(stddist_full = True)
1754    def test_init(self):
1755        """
1756        This tests the functionality of the method init.
1757        """
1758        assert self._bounceSim._f_nbr == 2
1759        assert self._bounceSim._g_nbr == 1
1760        assert self._bounceSim.state_events == self._bounceSim.g
1761        assert self._bounceSim.y0[0] == 1.0
1762        assert self._bounceSim.y0[1] == 0.0
1763        assert self._dqSim._f_nbr == 1
1764        assert self._dqSim._g_nbr == 0
1765        try:
1766            self._dqSim.state_events
1767            raise FMUException('')
1768        except AttributeError:
1769            pass
1770       
1771        #sol = self._bounceSim._sol_real
1772       
1773        #nose.tools.assert_almost_equal(sol[0][0],1.000000000)
1774        #nose.tools.assert_almost_equal(sol[0][1],0.000000000)
1775        #nose.tools.assert_almost_equal(sol[0][2],0.000000000)
1776        #nose.tools.assert_almost_equal(sol[0][3],-9.81000000)
1777       
1778    @testattr(stddist_full = True)
1779    def test_f(self):
1780        """
1781        This tests the functionality of the rhs.
1782        """
1783        t = 1.0
1784        y = N.array([1.0,1.0])
1785       
1786        rhs = self._bounceSim.rhs(t,y)
1787       
1788        nose.tools.assert_almost_equal(rhs[0],1.00000000)
1789        nose.tools.assert_almost_equal(rhs[1],-9.8100000)
1790
1791   
1792    @testattr(stddist_full = True)
1793    def test_g(self):
1794        """
1795        This tests the functionality of the event indicators.
1796        """
1797        t = 1.0
1798        y = N.array([1.0,1.0])
1799       
1800        event = self._bounceSim.g(t,y,None)
1801       
1802        nose.tools.assert_almost_equal(event[0],1.00000000)
1803       
1804        y = N.array([0.5,1.0])
1805        event = self._bounceSim.g(t,y,None)
1806       
1807        nose.tools.assert_almost_equal(event[0],0.50000000)
1808
1809       
1810    @testattr(stddist_full = True)
1811    def test_t(self):
1812        """
1813        This tests the functionality of the time events.
1814        """
1815        t = 1.0
1816        y = N.array([1.0,1.0])
1817       
1818        time = self._bounceSim.t(t,y,None)
1819       
1820        assert time == None
1821        #Further testing of the time event function is needed.
1822       
1823       
1824    @testattr(stddist_full = True)
1825    def test_handle_event(self):
1826        """
1827        This tests the functionality of the method handle_event.
1828        """
1829        y = N.array([1.,1.])
1830        self._bounceSim._model.continuous_states = y
1831        solver = lambda x:1
1832        solver.rtol = 1.e-4
1833        solver.t = 1.0
1834        solver.y = y
1835        solver.y_sol = [y]
1836        solver.report_continuously = False
1837       
1838        self._bounceSim.initialize(solver)
1839        self._bounceSim.handle_event(solver, None)
1840
1841        nose.tools.assert_almost_equal(solver.y[0],1.00000000)
1842        nose.tools.assert_almost_equal(solver.y[1],-0.70000000)
1843       
1844        #Further testing of the handle_event function is needed.
1845   
1846    @testattr(stddist_full = True)
1847    def test_completed_step(self):
1848        """
1849        This tests the functionality of the method completed_step.
1850        """
1851        y = N.array([1.,1.])
1852        solver = lambda x:1
1853        solver.t = 1.0
1854        solver.y = y
1855        assert self._bounceSim.step_events(solver) == 0
1856        #Further testing of the completed step function is needed.
1857       
1858    @testattr(windows_base = True)
1859    def test_simulation_completed_step_cvode(self):
1860        """
1861        This tests a simulation of a Pendulum with dynamic state selection.
1862        """
1863        model = load_fmu('Pendulum_0Dynamic.fmu', path_to_fmus_me1)
1864       
1865        opts = model.simulate_options()
1866        opts["CVode_options"]["atol"] = 1e-8
1867        opts["CVode_options"]["rtol"] = 1e-8
1868        res = model.simulate(final_time=10, options=opts)
1869   
1870        nose.tools.assert_almost_equal(res.initial('x'), 1.000000, 4)
1871        nose.tools.assert_almost_equal(res.initial('y'), 0.000000, 4)
1872        nose.tools.assert_almost_equal(res.final('x'), 0.27510283167449501, 4)
1873        nose.tools.assert_almost_equal(res.final('y'), -0.96141480746068897, 4)
1874       
1875    @testattr(windows_base = True)
1876    def test_simulation_completed_step_radau(self):
1877        model = load_fmu('Pendulum_0Dynamic.fmu', path_to_fmus_me1)
1878       
1879        opts = model.simulate_options()
1880        opts["solver"] = "Radau5ODE"
1881        res = model.simulate(final_time=10, options=opts)
1882   
1883        assert N.abs(res.final('y')+0.96069759894208395) < 1e-2
1884        assert N.abs(res.final('x')-0.27759705219420999) < 1e-1
1885       
1886    @testattr(windows_base = True)
1887    def test_simulation_completed_step_dopri(self):
1888        model = load_fmu('Pendulum_0Dynamic.fmu', path_to_fmus_me1)
1889       
1890        opts = model.simulate_options()
1891        opts["solver"] = "Dopri5"
1892        res = model.simulate(final_time=10, options=opts)
1893   
1894        assert N.abs(res.final('y')+0.95766129067717698) < 1e-1
1895        assert N.abs(res.final('x')-0.28789729477457998) < 1e-1
1896   
1897    @testattr(windows_base = True)
1898    def test_simulation_completed_step_rodas(self):
1899        model = load_fmu('Pendulum_0Dynamic.fmu', path_to_fmus_me1)
1900       
1901        opts = model.simulate_options()
1902        opts["solver"] = "RodasODE"
1903        res = model.simulate(final_time=10, options=opts)
1904   
1905        assert N.abs(res.final('y')+0.96104146428710602) < 1e-1
1906        assert N.abs(res.final('x')-0.27640424005592701) < 1e-1
1907       
1908    @testattr(windows_base = True)
1909    def test_simulation_completed_step_lsodar(self):
1910        model = load_fmu('Pendulum_0Dynamic.fmu', path_to_fmus_me1)
1911       
1912        opts = model.simulate_options()
1913        opts["solver"] = "LSODAR"
1914        res = model.simulate(final_time=10, options=opts)
1915   
1916        assert N.abs(res.final('y')+0.96311062033198303) < 1e-1
1917        assert N.abs(res.final('x')-0.26910580261997902) < 1e-1
1918   
1919    @testattr(windows_base = True)
1920    def test_terminate_simulation(self):
1921        """
1922        This tests a simulation with an event of terminate simulation.
1923        """
1924        model = load_fmu('Robot.fmu', path_to_fmus_me1)
1925       
1926        res = model.simulate(final_time=2.0)
1927        solver = res.solver
1928       
1929        nose.tools.assert_almost_equal(solver.t, 1.856045, places=3)   
1930       
1931    @testattr(windows_full = True)
1932    def test_typeDefinitions_simulation(self):
1933        """
1934        This tests a FMU with typeDefinitions including StringType and BooleanType
1935        """
1936        model = load_fmu('Robot3d_0MultiBody.fmu', path_to_fmus_me1)
1937       
1938        res = model.simulate(final_time=2.0)
1939        solver = res.solver
1940       
1941        nose.tools.assert_almost_equal(solver.t, 1.856045, places=3)       
1942
1943    @testattr(noncompliantfmi = True)
1944    def test_assert_raises_sensitivity_parameters(self):
1945        """
1946        This tests that an exception is raised if a sensitivity calculation
1947        is to be perfomed and the parameters are not contained in the model.
1948        """
1949        fmu_name = compile_fmu('EventIter.EventMiddleIter', os.path.join(path_to_mos,'EventIter.mo'))
1950
1951        model = load_fmu(fmu_name)
1952        opts = model.simulate_options()
1953        opts["sensitivities"] = ["hej", "hopp"]
1954       
1955        nose.tools.assert_raises(FMUException,model.simulate,0,1,(),'AssimuloFMIAlg',opts)
1956       
1957    @testattr(windows_full = True)
1958    def test_assert_raises_sensitivity_without_jmodelica(self):
1959        model = load_fmu("CoupledClutches_Mod_Generation_Tool.fmu", path_to_fmus_me1)
1960        opts = model.simulate_options()
1961        opts["sensitivities"] = ["J1.w"]
1962       
1963        nose.tools.assert_raises(FMUException,model.simulate,0,1,(),'AssimuloFMIAlg',opts)
1964
1965    @testattr(stddist_full = True)
1966    def test_event_iteration(self):
1967        """
1968        This tests FMUs with event iteration (JModelica.org).
1969        """
1970        fmu_name = compile_fmu('EventIter.EventMiddleIter', os.path.join(path_to_mos,'EventIter.mo'))
1971
1972        model = load_fmu(fmu_name)
1973
1974        sim_res = model.simulate(final_time=10)
1975
1976        nose.tools.assert_almost_equal(sim_res.initial('x'), 2.00000, 4)
1977        nose.tools.assert_almost_equal(sim_res.final('x'), 10.000000, 4)
1978        nose.tools.assert_almost_equal(sim_res.final('y'), 3.0000000, 4)
1979        nose.tools.assert_almost_equal(sim_res.final('z'), 2.0000000, 4)
1980       
1981        fmu_name = compile_fmu('EventIter.EventStartIter', os.path.join(path_to_mos,'EventIter.mo'))
1982       
1983        model = load_fmu(fmu_name)
1984
1985        sim_res = model.simulate(final_time=10)
1986
1987        nose.tools.assert_almost_equal(sim_res.initial('x'), 1.00000, 4)
1988        nose.tools.assert_almost_equal(sim_res.initial('y'), -1.00000, 4)
1989        nose.tools.assert_almost_equal(sim_res.initial('z'), 1.00000, 4)
1990        nose.tools.assert_almost_equal(sim_res.final('x'), -2.000000, 4)
1991        nose.tools.assert_almost_equal(sim_res.final('y'), -1.0000000, 4)
1992        nose.tools.assert_almost_equal(sim_res.final('z'), 4.0000000, 4)
1993   
1994    @testattr(stddist_base = True)
1995    def test_changed_starttime(self):
1996        """
1997        This tests a simulation with different start time.
1998        """
1999        bounce = load_fmu('bouncingBall.fmu', path_to_fmus_me1)
2000        #bounce.initialize()
2001        opts = bounce.simulate_options()
2002        opts["CVode_options"]["rtol"] = 1e-4
2003        opts["CVode_options"]["atol"] = 1e-6
2004        res = bounce.simulate(start_time=2.,final_time=5.,options=opts)
2005
2006        nose.tools.assert_almost_equal(res.initial('h'),1.000000,5)
2007        nose.tools.assert_almost_equal(res.final('h'),-0.98048862,4)
2008        nose.tools.assert_almost_equal(res.final('time'),5.000000,5)
2009       
2010   
2011    @testattr(stddist_base = True)
2012    def test_basic_simulation(self):
2013        """
2014        This tests the basic simulation and writing.
2015        """
2016        #Writing continuous
2017        bounce = load_fmu('bouncingBall.fmu', path_to_fmus_me1)
2018        #bounce.initialize()
2019        opts = bounce.simulate_options()
2020        opts["CVode_options"]["rtol"] = 1e-4
2021        opts["CVode_options"]["atol"] = 1e-6
2022        res = bounce.simulate(final_time=3., options=opts)
2023       
2024        nose.tools.assert_almost_equal(res.initial('h'),1.000000,5)
2025        nose.tools.assert_almost_equal(res.final('h'),-0.9804523,5)
2026        nose.tools.assert_almost_equal(res.final('time'),3.000000,5)
2027       
2028        #Writing after
2029        bounce = load_fmu('bouncingBall.fmu', path_to_fmus_me1)
2030        bounce.initialize()
2031        opt = bounce.simulate_options()
2032        opt['initialize']=False
2033        opt["CVode_options"]["rtol"] = 1e-4
2034        opt["CVode_options"]["atol"] = 1e-6
2035        res = bounce.simulate(final_time=3., options=opt)
2036       
2037        nose.tools.assert_almost_equal(res.initial('h'),1.000000,5)
2038        nose.tools.assert_almost_equal(res.final('h'),-0.9804523,5)
2039        nose.tools.assert_almost_equal(res.final('time'),3.000000,5)
2040       
2041        #Test with predefined FMUModel
2042        model = load_fmu(os.path.join(path_to_fmus_me1,'bouncingBall.fmu'))
2043        #model.initialize()
2044        res = model.simulate(final_time=3.,options=opts)
2045
2046        nose.tools.assert_almost_equal(res.initial('h'),1.000000,5)
2047        nose.tools.assert_almost_equal(res.final('h'),-0.9804523,5)
2048        nose.tools.assert_almost_equal(res.final('time'),3.000000,5)
2049
2050
2051    @testattr(stddist_base = True)
2052    def test_default_simulation(self):
2053        """
2054        This test the default values of the simulation using simulate.
2055        """
2056        #Writing continuous
2057        bounce = load_fmu('bouncingBall.fmu', path_to_fmus_me1)
2058        opts = bounce.simulate_options()
2059        opts["CVode_options"]["rtol"] = 1e-4
2060        opts["CVode_options"]["atol"] = 1e-6
2061        res = bounce.simulate(final_time=3., options=opts)
2062
2063        nose.tools.assert_almost_equal(res.solver.rtol, 1e-4, 6)
2064        assert res.solver.iter == 'Newton'
2065       
2066        nose.tools.assert_almost_equal(res.initial('h'),1.000000,5)
2067        nose.tools.assert_almost_equal(res.final('h'),-0.9804523,5)
2068        nose.tools.assert_almost_equal(res.final('time'),3.000000,5)
2069       
2070        #Writing continuous
2071        bounce = load_fmu('bouncingBall.fmu', path_to_fmus_me1)
2072        #bounce.initialize(options={'initialize':False})
2073        res = bounce.simulate(final_time=3.,
2074            options={'initialize':True,'CVode_options':{'iter':'FixedPoint','rtol':1e-6,'atol':1e-6}})
2075   
2076        nose.tools.assert_almost_equal(res.solver.rtol, 0.00000100, 7)
2077        assert res.solver.iter == 'FixedPoint'
2078       
2079        nose.tools.assert_almost_equal(res.initial('h'),1.000000,5)
2080        nose.tools.assert_almost_equal(res.final('h'),-0.98018113,5)
2081        nose.tools.assert_almost_equal(res.final('time'),3.000000,5)
2082
2083    @testattr(stddist_base = True)
2084    def test_reset(self):
2085        """
2086        Test resetting an FMU. (Multiple instances is NOT supported on Dymola
2087        FMUs)
2088        """
2089        #Writing continuous
2090        bounce = load_fmu('bouncingBall.fmu', path_to_fmus_me1)
2091        opts = bounce.simulate_options()
2092        opts["CVode_options"]["rtol"] = 1e-4
2093        opts["CVode_options"]["atol"] = 1e-6
2094        #bounce.initialize()
2095        res = bounce.simulate(final_time=3., options=opts)
2096       
2097        nose.tools.assert_almost_equal(res.initial('h'),1.000000,5)
2098        nose.tools.assert_almost_equal(res.final('h'),-0.9804523,5)
2099       
2100        bounce.reset()
2101        #bounce.initialize()
2102       
2103        nose.tools.assert_almost_equal(bounce.get('h'), 1.00000,5)
2104       
2105        res = bounce.simulate(final_time=3.,options=opts)
2106
2107        nose.tools.assert_almost_equal(res.initial('h'),1.000000,5)
2108        nose.tools.assert_almost_equal(res.final('h'),-0.9804523,5)
2109   
Note: See TracBrowser for help on using the repository browser.