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

Contents of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

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