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

Contents of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

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