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

Contents of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1288 - (show annotations) (download) (as text)
Sun Feb 18 12:05:53 2007 UTC (15 years, 4 months ago) by johnpye
File MIME type: text/x-python
File size: 35689 byte(s)
Fixed test.py for lack of module 'dl' on AMD64
1 #!/usr/bin/env python
2 # ASCEND modelling environment
3 # Copyright (C) 2006, 2007 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 try:
32 import dl
33 _dlflags = dl.RTLD_GLOBAL|dl.RTLD_NOW
34 except:
35 # On platforms that unilaterally refuse to provide the 'dl' module
36 # we'll just set the value and see if it works.
37 print "Note: python 'dl' module not available on this system, guessing value of RTLD_* flags"
38 _dlflags = 258
39
40 sys.setdlopenflags(_dlflags)
41
42 class Ascend(unittest.TestCase):
43
44 def setUp(self):
45 import ascpy
46 self.L = ascpy.Library()
47
48 def tearDown(self):
49 self.L.clear()
50 del self.L
51
52 class AscendSelfTester(Ascend):
53
54 def _run(self,modelname,solvername="QRSlv",filename=None,parameters={}):
55 if filename==None:
56 filename = 'johnpye/%s.a4c' % modelname
57 self.L.load(filename)
58 T = self.L.findType(modelname)
59 M = T.getSimulation('sim')
60 M.setSolver(ascpy.Solver(solvername))
61 for k,v in parameters.iteritems():
62 M.setParameter(k,v)
63 M.solve(ascpy.Solver(solvername),ascpy.SolverReporter())
64 M.run(T.getMethod('self_test'))
65 return M
66
67 class TestCompiler(Ascend):
68
69 def _run(self,filen,modeln=""):
70 self.L.load('test/compiler/%s.a4c' % filen)
71 T = self.L.findType('%s%s' % (filen,modeln))
72 M = T.getSimulation('sim')
73 M.build()
74
75 def _runfail(self,filen,n,msg="failed"):
76 try:
77 self._run(filen,'fail%d' % n)
78 except Exception,e:
79 print "(EXPECTED) ERROR: %s" % e
80 return
81 self.fail(msg)
82
83
84 def testloading(self):
85 """library startup"""
86 pass
87
88 def testsystema4l(self):
89 """loading system.a4l?"""
90 self.L.load('system.a4l')
91
92 def testatomsa4l(self):
93 """loading atoms.a4l?"""
94 self.L.load('atoms.a4l')
95
96 def testmissingreq(self):
97 """flagging a missing REQUIRE"""
98 self._runfail('missingreq',1)
99
100 def testmissingsubreq(self):
101 """flagging a subsidiary missing REQUIRE"""
102 self._runfail('missingreq',1)
103
104 class TestSolver(AscendSelfTester):
105
106 def testlog10(self):
107 self._run('testlog10')
108
109 def testrootsofpoly(self):
110 self._run('roots_of_poly',filename="roots_of_poly.a4c")
111
112 def testcollapsingcan(self):
113 self._run('collapsingcan',filename="collapsingcan.a4c")
114
115 def testdistancecalc(self):
116 self._run('distance_calc',filename="distance_calc.a4c")
117
118 def testconopt(self):
119 self._run('testconopt',"CONOPT")
120
121 def testcmslv2(self):
122 self._run('testcmslv2',"CMSlv")
123
124 def testsunpos1(self):
125 self._run('example_1_6_1',"QRSlv","johnpye/sunpos.a4c")
126
127 def testsunpos2(self):
128 self._run('example_1_6_2',"QRSlv","johnpye/sunpos.a4c")
129
130 def testsunpos3(self):
131 self._run('example_1_7_1',"QRSlv","johnpye/sunpos.a4c")
132
133 def testsunpos4(self):
134 self._run('example_1_7_2',"QRSlv","johnpye/sunpos.a4c")
135
136 def testsunpos5(self):
137 self._run('example_1_7_3',"QRSlv","johnpye/sunpos.a4c")
138
139 def testsunpos6(self):
140 self._run('example_1_8_1',"QRSlv","johnpye/sunpos.a4c")
141
142 def testinstanceas(self):
143 M = self._run('example_1_6_1',"QRSlv","johnpye/sunpos.a4c")
144 self.assertAlmostEqual( float(M.t_solar), M.t_solar.as("s"))
145 self.assertAlmostEqual( float(M.t_solar)/3600, M.t_solar.as("h"))
146
147
148 class TestCMSlv(AscendSelfTester):
149 def testheatex(self):
150 self._run('heatex',"CMSlv","heatex.a4c")
151 def testphaseeq(self):
152 self._run('phaseq',"CMSlv","phaseq.a4c")
153 def testpipeline(self):
154 self._run('pipeline',"CMSlv","pipeline.a4c"
155 ,{'infinity':3.2e9}
156 )
157 def testrachford(self):
158 self._run('rachford',"CMSlv","rachford.a4c")
159 def testlinmassbal(self):
160 self._run('linmassbal',"CMSlv","linmassbal.a4c")
161
162
163 class TestMatrix(AscendSelfTester):
164 def testlog10(self):
165 M = self._run('testlog10')
166 print M.getMatrix().write(sys.stderr,"mmio")
167
168
169 class TestIntegrator(Ascend):
170
171 def testListIntegrators(self):
172 I = ascpy.Integrator.getEngines()
173 s1 = sorted([str(i) for i in I.values()])
174 s2 = sorted(['IDA','LSODE','AWW'])
175 assert s1==s2
176
177 # this routine is reused by both testIDA and testLSODE
178 def _testIntegrator(self,integratorname):
179 self.L.load('johnpye/shm.a4c')
180 M = self.L.findType('shm').getSimulation('sim')
181 M.setSolver(ascpy.Solver('QRSlv'))
182 P = M.getParameters()
183 M.setParameter('feastol',1e-12)
184 print M.getChildren()
185 assert float(M.x) == 10.0
186 assert float(M.v) == 0.0
187 t_end = math.pi
188
189 I = ascpy.Integrator(M)
190 I.setReporter(ascpy.IntegratorReporterNull(I))
191 I.setEngine(integratorname);
192 I.setLinearTimesteps(ascpy.Units("s"), 0.0, t_end, 100);
193 I.setMinSubStep(0.0001); # these limits are required by IDA at present (numeric diff)
194 I.setMaxSubStep(0.1);
195 I.setInitialSubStep(0.001);
196 I.setMaxSubSteps(200);
197 if(integratorname=='IDA'):
198 I.setParameter('autodiff',False)
199 for p in M.getParameters():
200 print p.getName(),"=",p.getValue()
201 I.analyse();
202 I.solve();
203 print "At end of simulation,"
204 print "x = %f" % M.x
205 print "v = %f" % M.v
206 assert abs(float(M.x) + 10) < 1e-2
207 assert abs(float(M.v)) < 1e-2
208 assert I.getNumObservedVars() == 3
209
210 def testInvalidIntegrator(self):
211 self.L.load('johnpye/shm.a4c')
212 M = self.L.findType('shm').getSimulation('sim')
213 M.setSolver(ascpy.Solver('QRSlv'))
214 I = ascpy.Integrator(M)
215 try:
216 I.setEngine('___NONEXISTENT____')
217 except RuntimeError:
218 return
219 self.fail("setEngine did not raise error!")
220
221 def testLSODE(self):
222 self._testIntegrator('LSODE')
223
224 def testIDA(self):
225 self._testIntegrator('IDA')
226
227 def testparameters(self):
228 self.L.load('johnpye/shm.a4c')
229 M = self.L.findType('shm').getSimulation('sim')
230 M.build()
231 I = ascpy.Integrator(M)
232 I.setEngine('IDA')
233 P = I.getParameters()
234 for p in P:
235 print p.getName(),"=",p.getValue()
236 assert len(P)==12
237 assert P[0].isStr()
238 assert P[0].getName()=="linsolver"
239 assert P[0].getValue()=='SPGMR'
240 assert P[2].getName()=="maxord"
241 assert P[3].getName()=="autodiff"
242 assert P[3].getValue()==True
243 assert P[8].getName()=="atolvect"
244 assert P[8].getBoolValue() == True
245 P[3].setBoolValue(False)
246 assert P[3].getBoolValue()==False
247 I.setParameters(P)
248 assert I.getParameterValue('autodiff')==False
249 I.setParameter('autodiff',True)
250 try:
251 v = I.getParameterValue('nonexist')
252 except KeyError:
253 pass
254 else:
255 self.fail('Failed to trip invalid Integrator parameter')
256
257 class TestLSODE(Ascend):
258
259 def testzill(self):
260 self.L.load('johnpye/zill.a4c')
261 T = self.L.findType('zill')
262 M = T.getSimulation('sim')
263 M.setSolver(ascpy.Solver('QRSlv'))
264 I = ascpy.Integrator(M)
265 I.setEngine('LSODE')
266 I.setMinSubStep(1e-7)
267 I.setMaxSubStep(0.001)
268 I.setMaxSubSteps(10000)
269 I.setReporter(ascpy.IntegratorReporterConsole(I))
270 I.setLinearTimesteps(ascpy.Units(), 1.0, 1.5, 5)
271 I.analyse()
272 I.solve()
273 M.run(T.getMethod('self_test'))
274
275 def testnewton(self):
276 sys.stderr.write("STARTING TESTNEWTON\n")
277 self.L.load('johnpye/newton.a4c')
278 T = self.L.findType('newton')
279 M = T.getSimulation('sim')
280 M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
281 I = ascpy.Integrator(M)
282 I.setEngine('LSODE')
283 I.setParameter('rtolvect',False)
284 I.setParameter('rtol',1e-7)
285 I.setParameter('atolvect',False)
286 I.setParameter('atol',1e-7)
287 I.setMinSubStep(1e-7)
288 I.setMaxSubStep(0.001)
289 I.setMaxSubSteps(10000)
290
291 I.setReporter(ascpy.IntegratorReporterConsole(I))
292 I.setLinearTimesteps(ascpy.Units("s"), 0, 2*float(M.v)/float(M.g), 2)
293 I.analyse()
294 I.solve()
295 print "At end of simulation,"
296 print "x = %f" % M.x
297 print "v = %f" % M.v
298 M.run(T.getMethod('self_test'))
299
300 def testlotka(self):
301 self.L.load('johnpye/lotka.a4c')
302 M = self.L.findType('lotka').getSimulation('sim')
303 M.setSolver(ascpy.Solver("QRSlv"))
304 I = ascpy.Integrator(M)
305 I.setEngine('LSODE')
306 I.setReporter(ascpy.IntegratorReporterConsole(I))
307 I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 5)
308 I.analyse()
309 print "Number of vars = %d" % I.getNumVars()
310 assert I.getNumVars()==2
311 I.solve()
312 assert I.getNumObservedVars() == 3;
313 assert abs(M.R - 832) < 1.0
314 assert abs(M.F - 21.36) < 0.1
315
316 #-------------------------------------------------------------------------------
317 # Testing of a external blackbox functions
318
319 class TestBlackBox(AscendSelfTester):
320 def testparsefail0(self):
321 try:
322 self.L.load('test/blackbox/parsefail0.a4c')
323 self.fail("parsefail0 should not have loaded without errors")
324 except:
325 pass
326
327 def testparsefail1(self):
328 try:
329 self.L.load('test/blackbox/parsefail1.a4c')
330 self.fail("parsefail1 should not have loaded without errors")
331 except:
332 pass
333
334 def testparsefail2(self):
335 try:
336 self.L.load('test/blackbox/parsefail2.a4c')
337 self.fail("parsefail2 should not have loaded without errors")
338 except:
339 pass
340
341 def testparsefail3(self):
342 try:
343 self.L.load('test/blackbox/parsefail3.a4c')
344 self.fail("parsefail3 should not have loaded without errors")
345 except:
346 pass
347
348 def testparsefail4(self):
349 try:
350 self.L.load('test/blackbox/parsefail4.a4c')
351 self.fail("parsefail4 should not have loaded")
352 except:
353 pass
354
355 def testfail1(self):
356 """Mismatched arg counts check-- tests bbox, not ascend."""
357 self.L.load('test/blackbox/fail1.a4c')
358 try:
359 M = self.L.findType('fail1').getSimulation('sim')
360 self.fail("expected exception was not raised")
361 except RuntimeError,e:
362 print "Caught exception '%s', assumed ok" % e
363
364 def testfail2(self):
365 """Incorrect data arg check -- tests bbox, not ascend"""
366 self.L.load('test/blackbox/fail2.a4c')
367 try:
368 M = self.L.findType('fail2').getSimulation('sim')
369 self.fail("expected exception was not raised")
370 except RuntimeError,e:
371 print "Caught exception '%s', assumed ok (should mention errors during instantiation)" % e
372
373 def testpass1(self):
374 """simple single bbox forward solve"""
375 M = self._run('pass1',filename='test/blackbox/pass.a4c')
376
377 def testpass2(self):
378 """simple single bbox reverse solve"""
379 M = self._run('pass2',filename='test/blackbox/pass.a4c')
380
381 def testpass3(self):
382 """simple double bbox solve"""
383 M = self._run('pass3',filename='test/blackbox/pass3.a4c')
384
385 def testpass4(self):
386 """simple double bbox reverse solve"""
387 M = self._run('pass4',filename='test/blackbox/pass3.a4c')
388
389 def testpass5(self):
390 M = self._run('pass5',filename='test/blackbox/pass5.a4c')
391
392 def testpass6(self):
393 M = self._run('pass6',filename='test/blackbox/pass5.a4c')
394
395 def testpass7(self):
396 M = self._run('pass7',filename='test/blackbox/passmerge.a4c')
397
398 def testpass8(self):
399 M = self._run('pass8',filename='test/blackbox/passmerge.a4c')
400
401 def testpass9(self):
402 M = self._run('pass9',filename='test/blackbox/passmerge.a4c')
403
404 def testpass10(self):
405 M = self._run('pass10',filename='test/blackbox/passmerge.a4c')
406
407 def testpass11(self):
408 M = self._run('pass11',filename='test/blackbox/passmerge.a4c')
409
410 def testpass12(self):
411 M = self._run('pass12',filename='test/blackbox/passmerge.a4c')
412
413 # this test doesn't work: 'system is inconsistent' -- and structurally singular
414 # def testpass13(self):
415 # """cross-merged input/output solve"""
416 # M = self._run('pass13',filename='test/blackbox/passmerge.a4c')
417
418 def testpass14(self):
419 """cross-merged input/output reverse solve"""
420 M = self._run('pass14',filename='test/blackbox/passmerge.a4c')
421
422 def testpass20(self):
423 M = self._run('pass20',filename='test/blackbox/passarray.a4c')
424
425 def testparsefail21(self):
426 """dense array of black boxes wrong syntax"""
427 try:
428 self.L.load('test/blackbox/parsefail21.a4c')
429 self.fail("parsefail21 should not have loaded without errors")
430 except:
431 pass
432
433 def testpass22(self):
434 M = self._run('pass22',filename='test/blackbox/passarray.a4c')
435
436 def testpass23(self):
437 M = self._run('pass23',filename='test/blackbox/passarray.a4c')
438
439 def testpass61(self):
440 M = self._run('pass61',filename='test/blackbox/reinstantiate.a4c')
441
442 def testpass62(self):
443 M = self._run('pass62',filename='test/blackbox/reinstantiate.a4c')
444
445 def testpass64(self):
446 M = self._run('pass64',filename='test/blackbox/reinstantiate.a4c')
447
448 def testpass65(self):
449 M = self._run('pass65',filename='test/blackbox/reinstantiate.a4c')
450
451 def testpass66(self):
452 M = self._run('pass66',filename='test/blackbox/reinstantiate.a4c')
453
454 def testpass67(self):
455 M = self._run('pass67',filename='test/blackbox/reinstantiate.a4c')
456
457 class TestExtFn(AscendSelfTester):
458 def testextfntest(self):
459 M = self._run('extfntest',filename='johnpye/extfn/extfntest.a4c')
460 self.assertAlmostEqual(M.y, 2);
461 self.assertAlmostEqual(M.x, 1);
462 self.assertAlmostEqual(M.y, M.x + 1);
463
464 def testextrelfor(self):
465 M = self._run('extrelfor',filename='johnpye/extfn/extrelfor.a4c')
466
467 ## @TODO fix bug with badly-named bbox rel in a loop (Ben, maybe)
468 # def testextrelforbadnaming(self):
469 # self.L.load('johnpye/extfn/extrelforbadnaming.a4c')
470 # T = self.L.findType('extrelfor')
471 # M = T.getSimulation('sim')
472 # M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
473 # print "x[1] = %f" % M.x[1]
474 # print "x[2] = %f" % M.x[2]
475 # print "x[3] = %f" % M.x[3]
476 # print "x[4] = %f" % M.x[4]
477 # print "x[5] = %f" % M.x[5]
478 # M.run(T.getMethod('self_test'))
479
480 def testextrelrepeat(self):
481 M = self._run('extrelrepeat',filename='johnpye/extfn/extrelrepeat.a4c')
482
483 #-------------------------------------------------------------------------------
484 # Testing of Sensitivity module
485
486 class TestSensitivity(AscendSelfTester):
487 def test1(self):
488 self.L.load('sensitivity_test.a4c')
489 T = self.L.findType('sensitivity_test')
490 M = T.getSimulation('sim',False)
491 M.run(T.getMethod('on_load'))
492 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
493 M.run(T.getMethod('analyse'))
494 M.run(T.getMethod('self_test'))
495
496 # def testall(self):
497 # self.L.load('sensitivity_test.a4c')
498 # T = self.L.findType('sensitivity_test_all')
499 # M = T.getSimulation('sim',False)
500 # M.run(T.getMethod('on_load'))
501 # M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
502 # M.run(T.getMethod('analyse'))
503 # M.run(T.getMethod('self_test'))
504 # CAUSES CRASH
505
506 #-------------------------------------------------------------------------------
507 # Testing of a ExtPy - external python methods
508
509 class TestExtPy(AscendSelfTester):
510 def test1(self):
511 self.L.load('johnpye/extpy/extpytest.a4c')
512 T = self.L.findType('extpytest')
513 M = T.getSimulation('sim')
514 M.run(T.getMethod('self_test'))
515
516 def test2(self):
517 self.L.load('johnpye/extpy/extpytest.a4c')
518 T = self.L.findType('extpytest')
519 M = T.getSimulation('sim')
520 M.run(T.getMethod('pythonthing'))
521 M.run(T.getMethod('pythonthing'))
522 M.run(T.getMethod('pythonthing'))
523 M.run(T.getMethod('pythonthing'))
524 M.run(T.getMethod('pythonthing'))
525 M.run(T.getMethod('pythonthing'))
526 M.run(T.getMethod('pythonthing'))
527 # causes crash!
528
529 #-------------------------------------------------------------------------------
530 # Testing of saturated steam properties library (iapwssatprops.a4c)
531
532 class TestSteam(AscendSelfTester):
533
534 def testiapwssatprops1(self):
535 M = self._run('testiapwssatprops1',filename='steam/iapwssatprops.a4c')
536 def testiapwssatprops2(self):
537 M = self._run('testiapwssatprops2',filename='steam/iapwssatprops.a4c')
538 def testiapwssatprops3(self):
539 M = self._run('testiapwssatprops3',filename='steam/iapwssatprops.a4c')
540
541 # test the stream model basically works
542 def testsatsteamstream(self):
543 M = self._run('satsteamstream',filename='steam/satsteamstream.a4c')
544
545 # test that we can solve in terms of various (rho,u)
546 def testsatuv(self):
547 self.L.load('steam/iapwssat.a4c')
548 T = self.L.findType('testiapwssatuv')
549 M = T.getSimulation('sim',False)
550 M.run(T.getMethod('on_load'))
551 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
552 print "p = %f bar" % M.p.as('bar');
553 print "T = %f C" % (M.T.as('K') - 273.15);
554 print "x = %f" % M.x;
555 M.run(T.getMethod('self_test'))
556 M.run(T.getMethod('values2'))
557 # M.v.setRealValueWithUnits(1.0/450,"m^3/kg");
558 # M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
559 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
560 print "p = %f bar" % M.p.as('bar');
561 print "T = %f C" % (M.T.as('K') - 273.15);
562 print "x = %f" % M.x;
563 M.run(T.getMethod('self_test2'))
564
565
566 ## @TODO fix error capture from bounds checking during initialisation
567 # def testiapwssat1(self):
568 # M = self._run('testiapwssat1',filename='steam/iapwssat.a4c')
569
570 def testdsgsat(self):
571 self.L.load('steam/dsgsat3.a4c')
572 T = self.L.findType('dsgsat3')
573 M = T.getSimulation('sim',False)
574 M.run(T.getMethod('on_load'))
575 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
576 self.assertAlmostEqual(M.dTw_dt[2],0.0);
577 M.run(T.getMethod('configure_dynamic'))
578 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
579 return M
580
581 def testdsgsatrepeat(self):
582 self.L.load('steam/dsgsat3.a4c')
583 T = self.L.findType('dsgsat3')
584 M = T.getSimulation('sim',False)
585 M.run(T.getMethod('on_load'))
586 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
587 M.run(T.getMethod('on_load'))
588 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
589 M.run(T.getMethod('on_load'))
590 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
591
592 def testvary(self):
593 self.L.load('steam/dsgsat3.a4c')
594 T = self.L.findType('dsgsat3')
595 M = T.getSimulation('sim',False)
596 M.run(T.getMethod('on_load'))
597 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
598 print "----- setting qdot_s -----"
599 M.qdot_s.setRealValueWithUnits(1000,"W/m")
600 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
601 print "----- setting qdot_s -----"
602 M.qdot_s.setRealValueWithUnits(2000,"W/m")
603 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
604
605 def teststeadylsode(self):
606 "test that steady conditions are stable with LSODE"
607 M = self.testdsgsat()
608 #M.qdot_s.setRealValueWithUnits(1000,"W/m")
609 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
610 #M.setParameter('
611 I = ascpy.Integrator(M)
612 I.setEngine('LSODE')
613 I.setReporter(ascpy.IntegratorReporterConsole(I))
614 I.setLinearTimesteps(ascpy.Units("s"), 0, 3600, 10)
615 I.analyse()
616 I.solve()
617
618 # DOESN'T CONVERGE
619 # def testpeturblsode(self):
620 # "test that steady conditions are stable with LSODE"
621 # M = self.testdsgsat()
622 # # here is the peturbation...
623 # M.qdot_s.setRealValueWithUnits(1000,"W/m")
624 # M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
625 # I = ascpy.Integrator(M)
626 # I.setEngine('LSODE')
627 # I.setReporter(ascpy.IntegratorReporterConsole(I))
628 # I.setLinearTimesteps(ascpy.Units("s"), 0, 5, 1)
629 # I.analyse()
630 # I.solve()
631
632 def teststeadyida(self):
633 M = self.testdsgsat()
634 self.assertAlmostEqual(M.dTw_dt[2],0.0)
635 Tw1 = float(M.T_w[2])
636 T = self.L.findType('dsgsat3')
637 M.run(T.getMethod('free_states'))
638 I = ascpy.Integrator(M)
639 I.setEngine('IDA')
640 I.setParameter('linsolver','DENSE')
641 I.setParameter('safeeval',True)
642 I.setParameter('rtol',1e-4)
643 I.setParameter('atolvect',False)
644 I.setParameter('atol',1e-4)
645 I.setParameter('maxord',3)
646 I.setInitialSubStep(0.001)
647 I.setReporter(ascpy.IntegratorReporterConsole(I))
648 I.setLinearTimesteps(ascpy.Units("s"), 0, 3600, 10)
649 I.analyse()
650 I.solve()
651 self.assertAlmostEqual(float(M.T_w[2]),Tw1)
652 M.qdot_s.setRealValueWithUnits(1000,"W/m")
653 self.assertAlmostEqual(M.qdot_s.as("W/m"),1000)
654 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
655 print "dTw/dt = %f" % M.dTw_dt[2]
656 self.assertNotAlmostEqual(M.dTw_dt[2],0.0)
657
658 def testpeturbida(self):
659 M = self.testdsgsat()
660 self.assertAlmostEqual(M.dTw_dt[2],0.0)
661 T = self.L.findType('dsgsat3')
662 M.run(T.getMethod('free_states'))
663 # here is the peturbation...
664 M.qdot_s.setRealValueWithUnits(6000,"W/m")
665 # IDA has its own initial conditions solver, so no need to call QRSlv here
666 I = ascpy.Integrator(M)
667 I.setEngine('IDA')
668 I.setParameter('linsolver','DENSE')
669 I.setParameter('safeeval',True)
670 I.setParameter('rtol',1e-4)
671 I.setParameter('atolvect',False)
672 I.setParameter('atol',1e-4)
673 I.setParameter('maxord',3)
674 I.setInitialSubStep(0.001)
675 I.setReporter(ascpy.IntegratorReporterConsole(I))
676 I.setLogTimesteps(ascpy.Units("s"), 0.001, 3600, 40)
677 I.analyse()
678 I.solve()
679
680 #-------------------------------------------------------------------------------
681 # Testing of freesteam external steam properties functions
682
683 with_freesteam = True
684 try:
685 # we assume that if the freesteam python module is installed, the ASCEND
686 # external library will also be.
687 import freesteam
688 have_freesteam = True
689 except ImportError,e:
690 have_freesteam = False
691
692 if with_freesteam and have_freesteam:
693 class TestFreesteam(AscendSelfTester):
694 # def testfreesteamtest(self):
695 # """run the self-test cases bundled with freesteam"""
696 # self._run('testfreesteam',filename='testfreesteam.a4c')
697
698 def testload(self):
699 """check that we can load 'thermalequilibrium2' (IMPORT "freesteam", etc)"""
700 self.L.load('johnpye/thermalequilibrium2.a4c')
701
702 def testinstantiate(self):
703 """load an instantiate 'thermalequilibrium2'"""
704 self.testload()
705 M = self.L.findType('thermalequilibrium2').getSimulation('sim')
706 return M
707
708 def testintegrate(self):
709 """integrate transfer of heat from one mass of water/steam to another
710 according to Newton's law of cooling"""
711 M = self.testinstantiate()
712 M.setSolver(ascpy.Solver("QRSlv"))
713 I = ascpy.Integrator(M)
714 I.setEngine('LSODE')
715 I.setReporter(ascpy.IntegratorReporterConsole(I))
716 I.setLinearTimesteps(ascpy.Units("s"), 0, 3000, 30)
717 I.setMinSubStep(0.01)
718 I.setInitialSubStep(1)
719 I.analyse()
720 print "Number of vars = %d" % I.getNumVars()
721 assert I.getNumVars()==2
722 I.solve()
723 assert I.getNumObservedVars() == 3;
724 print "S[1].T = %f K" % M.S[1].T
725 print "S[2].T = %f K" % M.S[2].T
726 print "Q = %f W" % M.Q
727 self.assertAlmostEqual(float(M.S[1].T),506.77225109,4);
728 self.assertAlmostEqual(float(M.S[2].T),511.605173967,5);
729 self.assertAlmostEqual(float(M.Q),-48.32922877329,3);
730 self.assertAlmostEqual(float(M.t),3000);
731 print "Note that the above values have not been verified analytically"
732
733 def testcollapsingcan2(self):
734 """ solve the collapsing can model using IAPWS-IF97 steam props """
735 M = self._run("collapsingcan2",filename="collapsingcan2.a4c");
736
737 #-------------------------------------------------------------------------------
738 # Testing of IDA's analysis module
739
740 class TestIDA(Ascend):
741 def _run(self,filen,modeln=""):
742 self.L.load('test/ida/%s.a4c' % filen)
743 T = self.L.findType('%s%s' % (filen,modeln))
744 M = T.getSimulation('sim')
745 M.build()
746 I = ascpy.Integrator(M)
747 I.setEngine('IDA')
748 I.analyse()
749 return M;
750
751 def _runfail(self,filen,n,msg="failed"):
752 try:
753 self._run(filen,'fail%d' % n)
754 except Exception,e:
755 print "(EXPECTED) ERROR: %s" % e
756 return
757 self.fail(msg)
758
759 def testsinglederiv(self):
760 self._run('singlederiv')
761
762 def testsinglederivfail1(self):
763 self._runfail('singlederiv',1
764 ,"t.ode_id=-1 did not trigger error")
765
766 def testsinglederivfail2(self):
767 self._runfail('singlederiv',2
768 ,"dy_dt.ode_id=2 did not trigger error")
769
770 def testsinglederivfail3(self):
771 self._runfail('singlederiv',3
772 ,"dy_dt.ode_type=3 did not trigger error")
773
774 def testsinglederivfail4(self):
775 self._runfail('singlederiv',4
776 ,"duplicate ode_type=1 did not trigger error")
777
778 def testsinglederivfail5(self):
779 self._runfail('singlederiv',5
780 ,"duplicate ode_type=1 did not trigger error")
781
782 def testsinglederivfail6(self):
783 self._runfail('singlederiv',6
784 ,"duplicate ode_type=1 did not trigger error")
785
786 def testtwoderiv(self):
787 self._run('twoderiv')
788
789 def testtwoderivfail1(self):
790 self._runfail('twoderiv',1)
791
792 def testtwoderivfail2(self):
793 self._runfail('twoderiv',2)
794
795 def testtwoderivfail3(self):
796 self._runfail('twoderiv',3)
797 def testtwoderivfail4(self):
798 self._runfail('twoderiv',4)
799 def testtwoderivfail5(self):
800 self._runfail('twoderiv',5)
801
802 def testnoderivs(self):
803 self._runfail('noderivs',1)
804
805 def testnoindeps(self):
806 self._runfail('indeps',1)
807
808 def testtwoindeps(self):
809 self._runfail('indeps',2)
810
811 def testfixedvars(self):
812 self._run('fixedvars')
813
814 def testfixedvars1(self):
815 self._run('fixedvars',1)
816
817 def testfixedvars2(self):
818 self._run('fixedvars',2)
819
820 def testfixedvars3(self):
821 self._run('fixedvars',3)
822
823 def testincidence(self):
824 self._run('incidence')
825
826 def testincidence1(self):
827 self._run('incidence',1)
828 def testincidence2(self):
829 self._run('incidence',2)
830 def testincidence3(self):
831 M = self._run('incidence',3)
832
833 def testincidence4(self):
834 self._run('incidence',4)
835 def testincidencefail5(self):
836 self._runfail('incidence',5)
837
838 # doesn't work yet:
839 # def testincidence5(self):
840 # self._run('incidence',5)
841
842
843 #-------------------------------------------------------------------------------
844 # Testing of IDA models using DENSE linear solver
845
846 class TestIDADENSE(Ascend):
847 """IDA DAE integrator, DENSE linear solver"""
848
849 def testlotka(self):
850 self.L.load('johnpye/lotka.a4c')
851 M = self.L.findType('lotka').getSimulation('sim')
852 M.setSolver(ascpy.Solver("QRSlv"))
853 I = ascpy.Integrator(M)
854 I.setEngine('IDA')
855 I.setReporter(ascpy.IntegratorReporterConsole(I))
856 I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 5);
857 I.setParameter('linsolver','DENSE')
858 I.setParameter('rtol',1e-8);
859 I.analyse()
860 assert I.getNumVars()==2
861 assert abs(M.R - 1000) < 1e-300
862 I.solve()
863 assert I.getNumObservedVars() == 3
864 assert abs(M.R - 832) < 1.0
865 assert abs(M.F - 21.36) < 0.1
866
867 def testdenx(self):
868 print "-----------------------------====="
869 self.L.load('johnpye/idadenx.a4c')
870 M = self.L.findType('idadenx').getSimulation('sim')
871 M.setSolver(ascpy.Solver("QRSlv"))
872 I = ascpy.Integrator(M)
873 I.setEngine('IDA')
874 I.setParameter('calcic','YA_YDP')
875 I.setParameter('linsolver','DENSE')
876 I.setParameter('safeeval',True)
877 I.setReporter(ascpy.IntegratorReporterConsole(I))
878 I.setLogTimesteps(ascpy.Units("s"), 0.4, 4e10, 11)
879 I.setMaxSubStep(0);
880 I.setInitialSubStep(0)
881 I.setMaxSubSteps(0)
882 I.setParameter('autodiff',True)
883 I.analyse()
884 I.solve()
885 assert abs(float(M.y1) - 5.1091e-08) < 2e-9
886 assert abs(float(M.y2) - 2.0437e-13) < 2e-14
887 assert abs(float(M.y3) - 1.0) < 1e-5
888
889 def testhires(self):
890 self.L.load('test/hires.a4c')
891 T = self.L.findType('hires')
892 M = T.getSimulation('sim')
893 M.setSolver(ascpy.Solver('QRSlv'))
894 I = ascpy.Integrator(M)
895 I.setEngine('IDA')
896 I.setParameter('linsolver','DENSE')
897 I.setParameter('rtol',1.1e-15)
898 I.setParameter('atolvect',0)
899 I.setParameter('atol',1.1e-15)
900 I.setReporter(ascpy.IntegratorReporterConsole(I))
901 I.setLogTimesteps(ascpy.Units(""), 1, 321.8122, 5)
902 I.setInitialSubStep(1e-5)
903 I.setMaxSubSteps(10000)
904 I.analyse()
905 I.solve()
906 for i in range(8):
907 print "y[%d] = %.20g" % (i+1, M.y[i+1])
908 M.run(T.getMethod('self_test'))
909
910 def testchemakzo(self):
911 self.L.load('test/chemakzo.a4c')
912 T = self.L.findType('chemakzo')
913 M = T.getSimulation('sim')
914 M.setSolver(ascpy.Solver('QRSlv'))
915 I = ascpy.Integrator(M)
916 I.setEngine('IDA')
917 I.setParameter('linsolver','DENSE')
918 I.setParameter('rtol',1e-15)
919 I.setParameter('atolvect',0)
920 I.setParameter('atol',1e-15)
921 I.setReporter(ascpy.IntegratorReporterConsole(I))
922 I.setLinearTimesteps(ascpy.Units("s"), 1, 180, 5)
923 I.setInitialSubStep(1e-13)
924 I.setMaxSubSteps(10000)
925 I.analyse()
926 I.solve()
927 for i in range(6):
928 print "y[%d] = %.20g" % (i+1, M.y[i+1])
929 M.run(T.getMethod('self_test'))
930
931 def testtransamp(self):
932 self.L.load('test/transamp.a4c')
933 T = self.L.findType('transamp')
934 M = T.getSimulation('sim')
935 M.setSolver(ascpy.Solver('QRSlv'))
936 I = ascpy.Integrator(M)
937 I.setEngine('IDA')
938 I.setParameter('linsolver','DENSE')
939 I.setParameter('rtol',1e-7)
940 I.setParameter('atolvect',0)
941 I.setParameter('atol',1e-7)
942 I.setReporter(ascpy.IntegratorReporterConsole(I))
943 I.setLinearTimesteps(ascpy.Units("s"), 0.05, 0.2, 20)
944 I.setInitialSubStep(0.00001)
945 I.setMaxSubSteps(10000)
946 I.analyse()
947 I.solve()
948 for i in range(6):
949 print "y[%d] = %.20g" % (i+1, M.y[i+1])
950 M.run(T.getMethod('self_test'))
951
952 # MODEL FAILS ANALYSIS: we need to add support for non-incident differential vars
953 # def testpollution(self):
954 # self.L.load('test/pollution.a4c')
955 # T = self.L.findType('pollution')
956 # M = T.getSimulation('sim')
957 # M.setSolver(ascpy.Solver('QRSlv'))
958 # I = ascpy.Integrator(M)
959 # I.setEngine('IDA')
960 # I.setParameter('linsolver','DENSE')
961 # I.setParameter('rtol',1.1e-15)
962 # I.setParameter('atolvect',0)
963 # I.setParameter('atol',1.1e-15)
964 # I.setReporter(ascpy.IntegratorReporterConsole(I))
965 # I.setLogTimesteps(ascpy.Units("s"), 1, 60, 5)
966 # I.setInitialSubStep(1e-5)
967 # I.setMaxSubSteps(10000)
968 # I.analyse()
969 # I.solve()
970 # for i in range(20):
971 # print "y[%d] = %.20g" % (i+1, M.y[i+1])
972 # M.run(T.getMethod('self_test'))
973
974 ## @TODO fails during IDACalcIC (model too big?)
975 # def testkryx(self):
976 # self.L.load('johnpye/idakryx.a4c')
977 # ascpy.getCompiler().setUseRelationSharing(False)
978 # M = self.L.findType('idakryx').getSimulation('sim')
979 # M.setSolver(ascpy.Solver('QRSlv'))
980 # M.build()
981 # I = ascpy.Integrator(M)
982 # I.setEngine('IDA')
983 # I.setReporter(ascpy.IntegratorReporterConsole(I))
984 # I.setParameter('linsolver','DENSE')
985 # I.setParameter('maxl',8)
986 # I.setParameter('gsmodified',False)
987 # I.setParameter('autodiff',True)
988 # I.setParameter('rtol',0)
989 # I.setParameter('atol',1e-3);
990 # I.setParameter('atolvect',False)
991 # I.setParameter('calcic','YA_YDP')
992 # I.analyse()
993 # I.setLogTimesteps(ascpy.Units("s"), 0.01, 10.24, 11)
994 # I.solve()
995 # assert abs(M.u[2][2].getValue()) < 1e-5
996
997 #-------------------------------------------------------------------------------
998 # Testing of IDA models using SPGMR linear solver (Krylov)
999
1000 # these tests are disabled until SPGMR preconditioning has been implemented
1001 class TestIDASPGMR:#(Ascend):
1002 def testlotka(self):
1003 self.L.load('johnpye/lotka.a4c')
1004 M = self.L.findType('lotka').getSimulation('sim')
1005 M.setSolver(ascpy.Solver("QRSlv"))
1006 I = ascpy.Integrator(M)
1007 I.setEngine('IDA')
1008 I.setReporter(ascpy.IntegratorReporterConsole(I))
1009 I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 5)
1010 I.setParameter('rtol',1e-8)
1011 I.analyse()
1012 assert I.getNumVars()==2
1013 assert abs(M.R - 1000) < 1e-300
1014 I.solve()
1015 assert I.getNumObservedVars() == 3
1016 assert abs(M.R - 832) < 1.0
1017 assert abs(M.F - 21.36) < 0.1
1018
1019
1020 def testkryx(self):
1021 self.L.load('johnpye/idakryx.a4c')
1022 M = self.L.findType('idakryx').getSimulation('sim')
1023 M.build()
1024 I = ascpy.Integrator(M)
1025 I.setEngine('IDA')
1026 I.setReporter(ascpy.IntegratorReporterConsole(I))
1027 I.setParameter('linsolver','SPGMR')
1028 I.setParameter('prec','JACOBI')
1029 I.setParameter('maxl',8)
1030 I.setParameter('gsmodified',False)
1031 I.setParameter('autodiff',True)
1032 I.setParameter('gsmodified',True)
1033 I.setParameter('rtol',0)
1034 I.setParameter('atol',1e-3);
1035 I.setParameter('atolvect',False)
1036 I.setParameter('calcic','Y')
1037 I.analyse()
1038 I.setLogTimesteps(ascpy.Units("s"), 0.01, 10.24, 10);
1039 print M.udot[1][3]
1040 I.solve()
1041 assert 0
1042
1043 def testzill(self):
1044 self.L.load('johnpye/zill.a4c')
1045 T = self.L.findType('zill')
1046 M = T.getSimulation('sim')
1047 M.setSolver(ascpy.Solver('QRSlv'))
1048 I = ascpy.Integrator(M)
1049 I.setEngine('IDA')
1050 I.setParameter('safeeval',False)
1051 I.setMinSubStep(1e-7)
1052 I.setMaxSubStep(0.001)
1053 I.setMaxSubSteps(10000)
1054 I.setReporter(ascpy.IntegratorReporterConsole(I))
1055 I.setLinearTimesteps(ascpy.Units(), 1.0, 1.5, 5)
1056 I.analyse()
1057 I.solve()
1058 M.run(T.getMethod('self_test'))
1059
1060 def testdenxSPGMR(self):
1061 self.L.load('johnpye/idadenx.a4c')
1062 M = self.L.findType('idadenx').getSimulation('sim')
1063 M.setSolver(ascpy.Solver('QRSlv'))
1064 I = ascpy.Integrator(M)
1065 I.setEngine('IDA')
1066 I.setReporter(ascpy.IntegratorReporterConsole(I))
1067 I.setLogTimesteps(ascpy.Units("s"), 0.4, 4e10, 11)
1068 I.setMaxSubStep(0);
1069 I.setInitialSubStep(0);
1070 I.setMaxSubSteps(0);
1071 I.setParameter('autodiff',True)
1072 I.setParameter('linsolver','SPGMR')
1073 I.setParameter('gsmodified',False)
1074 I.setParameter('maxncf',10)
1075 I.analyse()
1076 I.solve()
1077 assert abs(float(M.y1) - 5.1091e-08) < 1e-10
1078 assert abs(float(M.y2) - 2.0437e-13) < 1e-15
1079 assert abs(float(M.y3) - 1.0) < 1e-5
1080
1081 # move code above down here if you want to temporarily avoid testing it
1082 class NotToBeTested:
1083 def nothing(self):
1084 pass
1085
1086 def testnewton(self):
1087 sys.stderr.write("STARTING TESTNEWTON\n")
1088 self.L.load('johnpye/newton.a4c')
1089 T = self.L.findType('newton')
1090 M = T.getSimulation('sim')
1091 M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
1092 I = ascpy.Integrator(M)
1093 I.setEngine('IDA')
1094 I.setParameter('linsolver','DENSE')
1095 I.setParameter('safeeval',True)
1096 I.setParameter('rtol',1e-8)
1097 I.setMaxSubStep(0.001)
1098 I.setMaxSubSteps(10000)
1099
1100 I.setReporter(ascpy.IntegratorReporterConsole(I))
1101 I.setLinearTimesteps(ascpy.Units("s"), 0, 2*float(M.v)/float(M.g), 2)
1102 I.analyse()
1103 I.solve()
1104 print "At end of simulation,"
1105 print "x = %f" % M.x
1106 print "v = %f" % M.v
1107 M.run(T.getMethod('self_test'))
1108
1109 if __name__=='__main__':
1110 # a whole bag of tricks to make sure we get the necessary dirs in our ascend, python and ld path vars
1111 restart = 0
1112
1113 if platform.system()=="Windows":
1114 LD_LIBRARY_PATH="PATH"
1115 SEP = ";"
1116 else:
1117 LD_LIBRARY_PATH="LD_LIBRARY_PATH"
1118 SEP = ":"
1119
1120 freesteamdir = os.path.expanduser("~/freesteam/ascend")
1121 modeldirs = [os.path.abspath(os.path.join(sys.path[0],"models")),os.path.abspath(freesteamdir)]
1122 if not os.environ.get('ASCENDLIBRARY'):
1123 os.environ['ASCENDLIBRARY'] = SEP.join(modeldirs)
1124 restart = 1
1125 else:
1126 envmodelsdir = [os.path.abspath(i) for i in os.environ['ASCENDLIBRARY'].split(SEP)]
1127 for l in modeldirs:
1128 if l in envmodelsdir[len(modeldirs):]:
1129 envmodelsdir.remove(l)
1130 restart = 1
1131 for l in modeldirs:
1132 if l not in envmodelsdir:
1133 envmodelsdir.insert(0,l)
1134 restart = 1
1135 os.environ['ASCENDLIBRARY'] = SEP.join(envmodelsdir)
1136
1137 libdirs = ["pygtk","."]
1138 libdirs = [os.path.normpath(os.path.join(sys.path[0],l)) for l in libdirs]
1139 if not os.environ.get(LD_LIBRARY_PATH):
1140 os.environ[LD_LIBRARY_PATH]=SEP.join(libdirs)
1141 restart = 1
1142 else:
1143 envlibdirs = [os.path.normpath(i) for i in os.environ[LD_LIBRARY_PATH].split(SEP)]
1144 for l in libdirs:
1145 if l in envlibdirs[len(libdirs):]:
1146 envlibdirs.remove(l)
1147 restart = 1
1148 for l in libdirs:
1149 if l not in envlibdirs:
1150 envlibdirs.insert(0,l)
1151 restart = 1
1152 os.environ[LD_LIBRARY_PATH] = SEP.join(envlibdirs)
1153
1154 pypath = os.path.normpath(os.path.join(sys.path[0],"pygtk"))
1155 if not os.environ.get('PYTHONPATH'):
1156 os.environ['PYTHONPATH']=pypath
1157 else:
1158 envpypath = os.environ['PYTHONPATH'].split(SEP)
1159 if pypath not in envpypath:
1160 envpypath.insert(0,pypath)
1161 os.environ['PYTHONPATH']=SEP.join(envpypath)
1162 restart = 1
1163
1164 if restart:
1165 script = os.path.join(sys.path[0],"test.py")
1166 print "Restarting with..."
1167 print " export LD_LIBRARY_PATH=%s" % os.environ.get(LD_LIBRARY_PATH)
1168 print " export PYTHONPATH=%s" % os.environ.get('PYTHONPATH')
1169 print " export ASCENDLIBRARY=%s" % os.environ.get('ASCENDLIBRARY')
1170
1171 os.execvp("python",[script] + sys.argv)
1172
1173 import ascpy
1174
1175 try:
1176 import cunit
1177 except:
1178 pass
1179
1180 atexit.register(ascpy.shutdown)
1181 #suite = unittest.TestSuite()
1182 #suite = unittest.defaultTestLoader.loadTestsFromName('__main__')
1183 #unittest.TextTestRunner(verbosity=2).run(suite)
1184 unittest.main()

Properties

Name Value
svn:executable *

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