/[ascend]/trunk/test.py
ViewVC logotype

Contents of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1118 - (show annotations) (download) (as text)
Thu Jan 11 12:08:12 2007 UTC (13 years, 3 months ago) by johnpye
File MIME type: text/x-python
File size: 23651 byte(s)
Fixed up test.py to allow "ASCENDLIBRARY=~/freesteam/ascend ./test.py"
Fixed up keyboard shortcuts in PyGTK tools menu
1 #!/usr/bin/env python
2 # ASCEND modelling environment
3 # Copyright (C) 2006 Carnegie Mellon University
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2, or (at your option)
8 # any later version.
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, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330,
18 # Boston, MA 02111-1307, USA.
19
20 # This script gives a test suite for the high-level interface of ASCEND via
21 # Python. It is also planned to be a wrapper for the CUnit test suite, although
22 # this is still experimental.
23
24 import unittest
25 import os, sys
26 import math
27 import atexit
28
29 import platform
30 if platform.system() != "Windows":
31 import dl
32 sys.setdlopenflags(dl.RTLD_GLOBAL|dl.RTLD_NOW)
33
34 class Ascend(unittest.TestCase):
35
36 def setUp(self):
37 import ascpy
38 self.L = ascpy.Library()
39
40 def tearDown(self):
41 self.L.clear()
42 del self.L
43
44 class AscendSelfTester(Ascend):
45
46 def _run(self,modelname,solvername="QRSlv",filename=None):
47 if filename==None:
48 filename = 'johnpye/%s.a4c' % modelname
49 self.L.load(filename)
50 T = self.L.findType(modelname)
51 M = T.getSimulation('sim')
52 M.build()
53 M.solve(ascpy.Solver(solvername),ascpy.SolverReporter())
54 M.run(T.getMethod('self_test'))
55 return M
56
57 class TestCompiler(Ascend):
58
59 def testloading(self):
60 pass
61
62 def testsystema4l(self):
63 self.L.load('system.a4l')
64
65 def testatomsa4l(self):
66 self.L.load('atoms.a4l')
67
68 class TestSolver(AscendSelfTester):
69
70 def testlog10(self):
71 self._run('testlog10')
72
73 def testconopt(self):
74 self._run('testconopt',"CONOPT")
75
76 def testcmslv2(self):
77 self._run('testcmslv2',"CMSlv")
78
79 def testsunpos1(self):
80 self._run('example_1_6_1',"QRSlv","johnpye/sunpos.a4c")
81
82 def testsunpos2(self):
83 self._run('example_1_6_2',"QRSlv","johnpye/sunpos.a4c")
84
85 def testsunpos3(self):
86 self._run('example_1_7_1',"QRSlv","johnpye/sunpos.a4c")
87
88 def testsunpos4(self):
89 self._run('example_1_7_2',"QRSlv","johnpye/sunpos.a4c")
90
91 def testsunpos5(self):
92 self._run('example_1_7_3',"QRSlv","johnpye/sunpos.a4c")
93
94 def testsunpos6(self):
95 self._run('example_1_8_1',"QRSlv","johnpye/sunpos.a4c")
96
97 def testinstanceas(self):
98 M = self._run('example_1_6_1',"QRSlv","johnpye/sunpos.a4c")
99 self.assertAlmostEqual( float(M.t_solar), M.t_solar.as("s"))
100 self.assertAlmostEqual( float(M.t_solar)/3600, M.t_solar.as("h"))
101
102 class TestIntegrator(Ascend):
103
104 def testListIntegrators(self):
105 I = ascpy.Integrator.getEngines()
106 s1 = sorted([str(i) for i in I.values()])
107 s2 = sorted(['IDA','LSODE','AWW'])
108 assert s1==s2
109
110 # this routine is reused by both testIDA and testLSODE
111 def _testIntegrator(self,integratorname):
112 self.L.load('johnpye/shm.a4c')
113 M = self.L.findType('shm').getSimulation('sim')
114 M.setSolver(ascpy.Solver('QRSlv'))
115 print M.getChildren()
116 assert float(M.x) == 10.0
117 assert float(M.v) == 0.0
118 t_end = math.pi
119
120 I = ascpy.Integrator(M)
121 I.setReporter(ascpy.IntegratorReporterNull(I))
122 I.setEngine(integratorname);
123 I.setLinearTimesteps(ascpy.Units("s"), 0.0, t_end, 100);
124 I.setMinSubStep(0.0005); # these limits are required by IDA at present (numeric diff)
125 I.setMaxSubStep(0.02);
126 I.setInitialSubStep(0.001);
127 I.setMaxSubSteps(200);
128 if(integratorname=='IDA'):
129 I.setParameter('autodiff',False)
130 I.analyse();
131 I.solve();
132 print "At end of simulation,"
133 print "x = %f" % M.x
134 print "v = %f" % M.v
135 assert abs(float(M.x) + 10) < 1e-2
136 assert abs(float(M.v)) < 1e-2
137 assert I.getNumObservedVars() == 3
138
139 def testInvalidIntegrator(self):
140 self.L.load('johnpye/shm.a4c')
141 M = self.L.findType('shm').getSimulation('sim')
142 M.setSolver(ascpy.Solver('QRSlv'))
143 I = ascpy.Integrator(M)
144 try:
145 I.setEngine('___NONEXISTENT____')
146 except RuntimeError:
147 return
148 self.fail("setEngine did not raise error!")
149
150 def testLSODE(self):
151 self._testIntegrator('LSODE')
152
153 def testIDA(self):
154 self._testIntegrator('IDA')
155
156 def testparameters(self):
157 self.L.load('johnpye/shm.a4c')
158 M = self.L.findType('shm').getSimulation('sim')
159 M.build()
160 I = ascpy.Integrator(M)
161 I.setEngine('IDA')
162 P = I.getParameters()
163 for p in P:
164 print p.getName(),"=",p.getValue()
165 assert len(P)==11
166 assert P[0].isStr()
167 assert P[0].getName()=="linsolver"
168 assert P[0].getValue()=='SPGMR'
169 assert P[2].getName()=="autodiff"
170 assert P[2].getValue()==True
171 assert P[7].getName()=="atolvect"
172 assert P[7].getBoolValue() == True
173 P[2].setBoolValue(False)
174 assert P[2].getBoolValue()==False
175 I.setParameters(P)
176 assert I.getParameterValue('autodiff')==False
177 I.setParameter('autodiff',True)
178 try:
179 v = I.getParameterValue('nonexist')
180 except KeyError:
181 pass
182 else:
183 self.fail('Failed to trip invalid Integrator parameter')
184
185 class TestLSODE(Ascend):
186
187 def testzill(self):
188 self.L.load('johnpye/zill.a4c')
189 T = self.L.findType('zill')
190 M = T.getSimulation('sim')
191 M.setSolver(ascpy.Solver('QRSlv'))
192 I = ascpy.Integrator(M)
193 I.setEngine('LSODE')
194 I.setMinSubStep(1e-7)
195 I.setMaxSubStep(0.001)
196 I.setMaxSubSteps(10000)
197 I.setReporter(ascpy.IntegratorReporterConsole(I))
198 I.setLinearTimesteps(ascpy.Units(), 1.0, 1.5, 5)
199 I.analyse()
200 I.solve()
201 M.run(T.getMethod('self_test'))
202
203 def testnewton(self):
204 sys.stderr.write("STARTING TESTNEWTON\n")
205 self.L.load('johnpye/newton.a4c')
206 T = self.L.findType('newton')
207 M = T.getSimulation('sim')
208 M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
209 I = ascpy.Integrator(M)
210 I.setEngine('LSODE')
211 I.setParameter('rtolvect',False)
212 I.setParameter('rtol',1e-7)
213 I.setParameter('atolvect',False)
214 I.setParameter('atol',1e-7)
215 I.setMinSubStep(1e-7)
216 I.setMaxSubStep(0.001)
217 I.setMaxSubSteps(10000)
218
219 I.setReporter(ascpy.IntegratorReporterConsole(I))
220 I.setLinearTimesteps(ascpy.Units("s"), 0, 2*float(M.v)/float(M.g), 2)
221 I.analyse()
222 I.solve()
223 print "At end of simulation,"
224 print "x = %f" % M.x
225 print "v = %f" % M.v
226 M.run(T.getMethod('self_test'))
227
228 def testlotka(self):
229 self.L.load('johnpye/lotka.a4c')
230 M = self.L.findType('lotka').getSimulation('sim')
231 M.setSolver(ascpy.Solver("QRSlv"))
232 I = ascpy.Integrator(M)
233 I.setEngine('LSODE')
234 I.setReporter(ascpy.IntegratorReporterConsole(I))
235 I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 5)
236 I.analyse()
237 print "Number of vars = %d" % I.getNumVars()
238 assert I.getNumVars()==2
239 I.solve()
240 assert I.getNumObservedVars() == 3;
241 assert abs(M.R - 832) < 1.0
242 assert abs(M.F - 21.36) < 0.1
243
244 #-------------------------------------------------------------------------------
245 # Testing of a external blackbox functions
246
247 class TestBlackBox(AscendSelfTester):
248 def testparsefail0(self):
249 try:
250 self.L.load('test/blackbox/parsefail0.a4c')
251 self.fail("parsefail0 should not have loaded without errors")
252 except:
253 pass
254
255 def testparsefail1(self):
256 try:
257 self.L.load('test/blackbox/parsefail1.a4c')
258 self.fail("parsefail1 should not have loaded without errors")
259 except:
260 pass
261
262 def testparsefail2(self):
263 try:
264 self.L.load('test/blackbox/parsefail2.a4c')
265 self.fail("parsefail2 should not have loaded without errors")
266 except:
267 pass
268
269 def testparsefail3(self):
270 try:
271 self.L.load('test/blackbox/parsefail3.a4c')
272 self.fail("parsefail3 should not have loaded without errors")
273 except:
274 pass
275
276 def testparsefail4(self):
277 try:
278 self.L.load('test/blackbox/parsefail4.a4c')
279 self.fail("parsefail4 should not have loaded")
280 except:
281 pass
282
283 def testfail1(self):
284 """Mismatched arg counts check-- tests bbox, not ascend."""
285 self.L.load('test/blackbox/fail1.a4c')
286 try:
287 M = self.L.findType('fail1').getSimulation('sim')
288 self.fail("expected exception was not raised")
289 except RuntimeError,e:
290 print "Caught exception '%s', assumed ok" % e
291
292 def testfail2(self):
293 """Incorrect data arg check -- tests bbox, not ascend"""
294 self.L.load('test/blackbox/fail2.a4c')
295 try:
296 M = self.L.findType('fail2').getSimulation('sim')
297 self.fail("expected exception was not raised")
298 except RuntimeError,e:
299 print "Caught exception '%s', assumed ok (should mention errors during instantiation)" % e
300
301 def testpass1(self):
302 """simple single bbox forward solve"""
303 M = self._run('pass1',filename='test/blackbox/pass.a4c')
304
305 def testpass2(self):
306 """simple single bbox reverse solve"""
307 M = self._run('pass2',filename='test/blackbox/pass.a4c')
308
309 def testpass3(self):
310 """simple double bbox solve"""
311 M = self._run('pass3',filename='test/blackbox/pass3.a4c')
312
313 def testpass4(self):
314 """simple double bbox reverse solve"""
315 M = self._run('pass4',filename='test/blackbox/pass3.a4c')
316
317 def testpass5(self):
318 M = self._run('pass5',filename='test/blackbox/pass5.a4c')
319
320 def testpass6(self):
321 M = self._run('pass6',filename='test/blackbox/pass5.a4c')
322
323 def testpass7(self):
324 M = self._run('pass7',filename='test/blackbox/passmerge.a4c')
325
326 def testpass8(self):
327 M = self._run('pass8',filename='test/blackbox/passmerge.a4c')
328
329 def testpass9(self):
330 M = self._run('pass9',filename='test/blackbox/passmerge.a4c')
331
332 def testpass10(self):
333 M = self._run('pass10',filename='test/blackbox/passmerge.a4c')
334
335 def testpass11(self):
336 M = self._run('pass11',filename='test/blackbox/passmerge.a4c')
337
338 def testpass12(self):
339 M = self._run('pass12',filename='test/blackbox/passmerge.a4c')
340
341 # this test doesn't work: 'system is inconsistent' -- and structurally singular
342 # def testpass13(self):
343 # """cross-merged input/output solve"""
344 # M = self._run('pass13',filename='test/blackbox/passmerge.a4c')
345
346 def testpass14(self):
347 """cross-merged input/output reverse solve"""
348 M = self._run('pass14',filename='test/blackbox/passmerge.a4c')
349
350 def testpass20(self):
351 M = self._run('pass20',filename='test/blackbox/passarray.a4c')
352
353 def testparsefail21(self):
354 """dense array of black boxes wrong syntax"""
355 try:
356 self.L.load('test/blackbox/parsefail21.a4c')
357 self.fail("parsefail21 should not have loaded without errors")
358 except:
359 pass
360
361 def testpass22(self):
362 M = self._run('pass22',filename='test/blackbox/passarray.a4c')
363
364 def testpass23(self):
365 M = self._run('pass23',filename='test/blackbox/passarray.a4c')
366
367 def testpass61(self):
368 M = self._run('pass61',filename='test/blackbox/reinstantiate.a4c')
369
370 def testpass62(self):
371 M = self._run('pass62',filename='test/blackbox/reinstantiate.a4c')
372
373 def testpass64(self):
374 M = self._run('pass64',filename='test/blackbox/reinstantiate.a4c')
375
376 def testpass65(self):
377 M = self._run('pass65',filename='test/blackbox/reinstantiate.a4c')
378
379 def testpass66(self):
380 M = self._run('pass66',filename='test/blackbox/reinstantiate.a4c')
381
382 def testpass67(self):
383 M = self._run('pass67',filename='test/blackbox/reinstantiate.a4c')
384
385 class TestExtFn(AscendSelfTester):
386 def testextfntest(self):
387 M = self._run('extfntest',filename='johnpye/extfn/extfntest.a4c')
388 self.assertAlmostEqual(M.y, 2);
389 self.assertAlmostEqual(M.x, 1);
390 self.assertAlmostEqual(M.y, M.x + 1);
391
392 def testextrelfor(self):
393 M = self._run('extrelfor',filename='johnpye/extfn/extrelfor.a4c')
394
395 ## @TODO fix bug with badly-named bbox rel in a loop (Ben, maybe)
396 # def testextrelforbadnaming(self):
397 # self.L.load('johnpye/extfn/extrelforbadnaming.a4c')
398 # T = self.L.findType('extrelfor')
399 # M = T.getSimulation('sim')
400 # M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
401 # print "x[1] = %f" % M.x[1]
402 # print "x[2] = %f" % M.x[2]
403 # print "x[3] = %f" % M.x[3]
404 # print "x[4] = %f" % M.x[4]
405 # print "x[5] = %f" % M.x[5]
406 # M.run(T.getMethod('self_test'))
407
408 def testextrelrepeat(self):
409 M = self._run('extrelrepeat',filename='johnpye/extfn/extrelrepeat.a4c')
410
411 #-------------------------------------------------------------------------------
412 # Testing of a ExtPy - external python methods
413
414 class TestExtPy(AscendSelfTester):
415 def test1(self):
416 self.L.load('johnpye/extpy/extpytest.a4c')
417 T = self.L.findType('extpytest')
418 M = T.getSimulation('sim')
419 M.run(T.getMethod('self_test'))
420
421 def test2(self):
422 self.L.load('johnpye/extpy/extpytest.a4c')
423 T = self.L.findType('extpytest')
424 M = T.getSimulation('sim')
425 M.run(T.getMethod('pythonthing'))
426 M.run(T.getMethod('pythonthing'))
427 M.run(T.getMethod('pythonthing'))
428 M.run(T.getMethod('pythonthing'))
429 # causes crash!
430
431 #-------------------------------------------------------------------------------
432 # Testing of saturated steam properties library (iapwssatprops.a4c)
433
434 class TestSteam(AscendSelfTester):
435 def testiapwssatprops1(self):
436 M = self._run('testiapwssatprops1',filename='steam/iapwssatprops.a4c')
437 def testiapwssatprops2(self):
438 M = self._run('testiapwssatprops2',filename='steam/iapwssatprops.a4c')
439 def testiapwssatprops3(self):
440 M = self._run('testiapwssatprops3',filename='steam/iapwssatprops.a4c')
441 def testsatsteamstream(self):
442 M = self._run('satsteamstream',filename='steam/satsteamstream.a4c')
443
444 def testsatsteamstream(self):
445 M = self._run('satsteamstream',filename='steam/satsteamstream.a4c')
446
447 ## @TODO fix error capture from bounds checking during initialisation
448 # def testiapwssat1(self):
449 # M = self._run('testiapwssat1',filename='steam/iapwssat.a4c')
450
451 # @TODO fix bug with unpivoted node[i].hg_expr eqns.
452 def testdsgsat(self):
453 self.L.load('steam/dsgsat2.a4c')
454 T = self.L.findType('dsgsat2')
455 M = T.getSimulation('sim',False)
456 try:
457 M.run(T.getMethod('on_load'))
458 except:
459 pass
460 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
461 M.run(T.getMethod('fixed_states'))
462 I = ascpy.Integrator(M)
463 I.setEngine('LSODE')
464 I.setReporter(ascpy.IntegratorReporterConsole(I))
465 I.setReporter(ascpy.IntegratorReporterConsole(I))
466 I.setLinearTimesteps(ascpy.Units("s"), 0, 5, 100)
467 I.setMinSubStep(0.01)
468 I.setMaxSubStep(0.02)
469 I.setInitialSubStep(0.1)
470 I.analyse()
471 I.solve()
472 I.solve()
473 #M.checkStructuralSingularity() causes crash!
474
475 #-------------------------------------------------------------------------------
476 # Testing of freesteam external steam properties functions
477
478 with_freesteam = True
479 try:
480 # we assume that if the freesteam python module is installed, the ASCEND
481 # external library will also be.
482 import freesteam
483 have_freesteam = True
484 except ImportError,e:
485 have_freesteam = False
486
487 if with_freesteam and have_freesteam:
488 class TestFreesteam(AscendSelfTester):
489 def testfreesteamtest(self):
490 """run the self-test cases bundled with freesteam"""
491 self._run('testfreesteam',filename='testfreesteam.a4c')
492
493 def testload(self):
494 """check that we can load 'thermalequilibrium2' (IMPORT "freesteam", etc)"""
495 self.L.load('johnpye/thermalequilibrium2.a4c')
496
497 def testinstantiate(self):
498 """load an instantiate 'thermalequilibrium2'"""
499 self.testload()
500 M = self.L.findType('thermalequilibrium2').getSimulation('sim')
501 return M
502
503 def testintegrate(self):
504 """integrate transfer of heat from one mass of water/steam to another
505 according to Newton's law of cooling"""
506 M = self.testinstantiate()
507 M.setSolver(ascpy.Solver("QRSlv"))
508 I = ascpy.Integrator(M)
509 I.setEngine('LSODE')
510 I.setReporter(ascpy.IntegratorReporterConsole(I))
511 I.setLinearTimesteps(ascpy.Units("s"), 0, 3000, 30)
512 I.setMinSubStep(0.01)
513 I.setInitialSubStep(1)
514 I.analyse()
515 print "Number of vars = %d" % I.getNumVars()
516 assert I.getNumVars()==2
517 I.solve()
518 assert I.getNumObservedVars() == 3;
519 print "S[1].T = %f K" % M.S[1].T
520 print "S[2].T = %f K" % M.S[2].T
521 print "Q = %f W" % M.Q
522 self.assertAlmostEqual(float(M.S[1].T),506.77225109,5);
523 self.assertAlmostEqual(float(M.S[2].T),511.605173967,5);
524 self.assertAlmostEqual(float(M.Q),-48.32922877329,3);
525 self.assertAlmostEqual(float(M.t),3000);
526 print "Note that the above values have not been verified analytically"
527
528 #-------------------------------------------------------------------------------
529 # Testing of IDA models using DENSE linear solver
530
531 class TestIDADENSE(Ascend):
532 """IDA DAE integrator, DENSE linear solver"""
533
534 def testnewton(self):
535 sys.stderr.write("STARTING TESTNEWTON\n")
536 self.L.load('johnpye/newton.a4c')
537 T = self.L.findType('newton')
538 M = T.getSimulation('sim')
539 M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
540 I = ascpy.Integrator(M)
541 I.setEngine('IDA')
542 I.setParameter('linsolver','DENSE')
543 I.setParameter('safeeval',True)
544 I.setParameter('rtol',1e-8)
545 I.setMaxSubStep(0.001)
546 I.setMaxSubSteps(10000)
547
548 I.setReporter(ascpy.IntegratorReporterConsole(I))
549 I.setLinearTimesteps(ascpy.Units("s"), 0, 2*float(M.v)/float(M.g), 2)
550 I.analyse()
551 I.solve()
552 print "At end of simulation,"
553 print "x = %f" % M.x
554 print "v = %f" % M.v
555 M.run(T.getMethod('self_test'))
556
557 def testlotka(self):
558 self.L.load('johnpye/lotka.a4c')
559 M = self.L.findType('lotka').getSimulation('sim')
560 M.setSolver(ascpy.Solver("QRSlv"))
561 I = ascpy.Integrator(M)
562 I.setEngine('IDA')
563 I.setReporter(ascpy.IntegratorReporterConsole(I))
564 I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 5);
565 I.setParameter('linsolver','DENSE')
566 I.setParameter('rtol',1e-8);
567 I.analyse()
568 assert I.getNumVars()==2
569 assert abs(M.R - 1000) < 1e-300
570 I.solve()
571 assert I.getNumObservedVars() == 3
572 assert abs(M.R - 832) < 1.0
573 assert abs(M.F - 21.36) < 0.1
574
575 def testdenx(self):
576 print "-----------------------------====="
577 self.L.load('johnpye/idadenx.a4c')
578 M = self.L.findType('idadenx').getSimulation('sim')
579 M.setSolver(ascpy.Solver("QRSlv"))
580 I = ascpy.Integrator(M)
581 I.setEngine('IDA')
582 I.setParameter('calcic','YA_YPD')
583 I.setParameter('linsolver','DENSE')
584 I.setReporter(ascpy.IntegratorReporterConsole(I))
585 I.setLogTimesteps(ascpy.Units("s"), 0.4, 4e10, 11)
586 I.setMaxSubStep(0);
587 I.setInitialSubStep(0)
588 I.setMaxSubSteps(0);
589 I.setParameter('autodiff',True)
590 I.analyse()
591 I.solve()
592 assert abs(float(M.y1) - 5.1091e-08) < 2e-9
593 assert abs(float(M.y2) - 2.0437e-13) < 2e-14
594 assert abs(float(M.y3) - 1.0) < 1e-5
595
596 ## @TODO fails during IDACalcIC (model too big?)
597 # def testkryx(self):
598 # self.L.load('johnpye/idakryx.a4c')
599 # ascpy.getCompiler().setUseRelationSharing(False)
600 # M = self.L.findType('idakryx').getSimulation('sim')
601 # M.setSolver(ascpy.Solver('QRSlv'))
602 # M.build()
603 # I = ascpy.Integrator(M)
604 # I.setEngine('IDA')
605 # I.setReporter(ascpy.IntegratorReporterConsole(I))
606 # I.setParameter('linsolver','DENSE')
607 # I.setParameter('maxl',8)
608 # I.setParameter('gsmodified',False)
609 # I.setParameter('autodiff',True)
610 # I.setParameter('rtol',0)
611 # I.setParameter('atol',1e-3);
612 # I.setParameter('atolvect',False)
613 # I.setParameter('calcic','YA_YDP')
614 # I.analyse()
615 # I.setLogTimesteps(ascpy.Units("s"), 0.01, 10.24, 11)
616 # I.solve()
617 # assert abs(M.u[2][2].getValue()) < 1e-5
618
619 #-------------------------------------------------------------------------------
620 # Testing of IDA models using SPGMR linear solver (Krylov)
621
622 # these tests are disabled until SPGMR preconditioning has been implemented
623 class TestIDASPGMR:#(Ascend):
624 def testlotka(self):
625 self.L.load('johnpye/lotka.a4c')
626 M = self.L.findType('lotka').getSimulation('sim')
627 M.setSolver(ascpy.Solver("QRSlv"))
628 I = ascpy.Integrator(M)
629 I.setEngine('IDA')
630 I.setReporter(ascpy.IntegratorReporterConsole(I))
631 I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 5)
632 I.setParameter('rtol',1e-8)
633 I.analyse()
634 assert I.getNumVars()==2
635 assert abs(M.R - 1000) < 1e-300
636 I.solve()
637 assert I.getNumObservedVars() == 3
638 assert abs(M.R - 832) < 1.0
639 assert abs(M.F - 21.36) < 0.1
640
641
642 def testkryx(self):
643 self.L.load('johnpye/idakryx.a4c')
644 M = self.L.findType('idakryx').getSimulation('sim')
645 M.build()
646 I = ascpy.Integrator(M)
647 I.setEngine('IDA')
648 I.setReporter(ascpy.IntegratorReporterConsole(I))
649 I.setParameter('linsolver','SPGMR')
650 I.setParameter('prec','JACOBI')
651 I.setParameter('maxl',8)
652 I.setParameter('gsmodified',False)
653 I.setParameter('autodiff',True)
654 I.setParameter('gsmodified',True)
655 I.setParameter('rtol',0)
656 I.setParameter('atol',1e-3);
657 I.setParameter('atolvect',False)
658 I.setParameter('calcic','Y')
659 I.analyse()
660 I.setLogTimesteps(ascpy.Units("s"), 0.01, 10.24, 10);
661 print M.udot[1][3]
662 I.solve()
663 assert 0
664
665 def testzill(self):
666 self.L.load('johnpye/zill.a4c')
667 T = self.L.findType('zill')
668 M = T.getSimulation('sim')
669 M.setSolver(ascpy.Solver('QRSlv'))
670 I = ascpy.Integrator(M)
671 I.setEngine('IDA')
672 I.setParameter('safeeval',False)
673 I.setMinSubStep(1e-7)
674 I.setMaxSubStep(0.001)
675 I.setMaxSubSteps(10000)
676 I.setReporter(ascpy.IntegratorReporterConsole(I))
677 I.setLinearTimesteps(ascpy.Units(), 1.0, 1.5, 5)
678 I.analyse()
679 I.solve()
680 M.run(T.getMethod('self_test'))
681
682 def testdenxSPGMR(self):
683 self.L.load('johnpye/idadenx.a4c')
684 M = self.L.findType('idadenx').getSimulation('sim')
685 M.setSolver(ascpy.Solver('QRSlv'))
686 I = ascpy.Integrator(M)
687 I.setEngine('IDA')
688 I.setReporter(ascpy.IntegratorReporterConsole(I))
689 I.setLogTimesteps(ascpy.Units("s"), 0.4, 4e10, 11)
690 I.setMaxSubStep(0);
691 I.setInitialSubStep(0);
692 I.setMaxSubSteps(0);
693 I.setParameter('autodiff',True)
694 I.setParameter('linsolver','SPGMR')
695 I.setParameter('gsmodified',False)
696 I.setParameter('maxncf',10)
697 I.analyse()
698 I.solve()
699 assert abs(float(M.y1) - 5.1091e-08) < 1e-10
700 assert abs(float(M.y2) - 2.0437e-13) < 1e-15
701 assert abs(float(M.y3) - 1.0) < 1e-5
702
703 # move code above down here if you want to temporarily avoid testing it
704 class NotToBeTested:
705 def nothing(self):
706 pass
707
708 if __name__=='__main__':
709 # a whole bag of tricks to make sure we get the necessary dirs in our ascend, python and ld path vars
710 restart = 0
711
712 if platform.system()=="Windows":
713 LD_LIBRARY_PATTH="PATH"
714 SEP = ";"
715 else:
716 LD_LIBRARY_PATH="LD_LIBRARY_PATH"
717 SEP = ":"
718
719 modelsdir = os.path.normpath(os.path.join(sys.path[0],"models"))
720 if not os.environ.get('ASCENDLIBRARY'):
721 os.environ['ASCENDLIBRARY'] = modelsdir
722 restart = 1
723 else:
724 envmodelsdir = [os.path.abspath(i) for i in os.environ['ASCENDLIBRARY'].split(SEP)]
725 if modelsdir not in envmodelsdir:
726 envmodelsdir.insert(0,modelsdir)
727 os.environ['ASCENDLIBRARY']=SEP.join(envmodelsdir)
728 restart = 1
729
730 libdirs = ["pygtk","."]
731 libdirs = [os.path.normpath(os.path.join(sys.path[0],l)) for l in libdirs]
732 if not os.environ.get(LD_LIBRARY_PATH):
733 os.environ[LD_LIBRARY_PATH]=SEP.join(libdirs)
734 restart = 1
735 else:
736 envlibdirs = [os.path.normpath(i) for i in os.environ[LD_LIBRARY_PATH].split(SEP)]
737 for l in libdirs:
738 if l in envlibdirs[len(libdirs):]:
739 envlibdirs.remove(l)
740 restart = 1
741 for l in libdirs:
742 if l not in envlibdirs:
743 envlibdirs.insert(0,l)
744 restart = 1
745 os.environ[LD_LIBRARY_PATH] = SEP.join(envlibdirs)
746
747 pypath = os.path.normpath(os.path.join(sys.path[0],"pygtk"))
748 if not os.environ.get('PYTHONPATH'):
749 os.environ['PYTHONPATH']=pypath
750 else:
751 envpypath = os.environ['PYTHONPATH'].split(SEP)
752 if pypath not in envpypath:
753 envpypath.insert(0,pypath)
754 os.environ['PYTHONPATH']=envpypath
755 restart = 1
756
757 if restart:
758 script = os.path.join(sys.path[0],"test.py")
759 print "Restarting"
760 print "LD_LIBRARY_PATH = %s" % os.environ.get(LD_LIBRARY_PATH)
761 print "PYTHONPATH = %s" % os.environ.get('PYTHONPATH')
762 print "ASCENDLIBRARY = %s" % os.environ.get('ASCENDLIBRARY')
763 os.execvp("python",[script] + sys.argv)
764
765 import ascpy
766
767 try:
768 import cunit
769 except:
770 pass
771
772 atexit.register(ascpy.shutdown)
773 #suite = unittest.TestSuite()
774 #suite = unittest.defaultTestLoader.loadTestsFromName('__main__')
775 #unittest.TextTestRunner(verbosity=2).run(suite)
776 unittest.main()

Properties

Name Value
svn:executable *

john.pye@anu.edu.au
ViewVC Help
Powered by ViewVC 1.1.22