/[ascend]/branches/fprops2/test.py
ViewVC logotype

Annotation of /branches/fprops2/test.py

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

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