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

Annotation of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

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