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

Annotation of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1679 - (hide annotations) (download) (as text)
Wed Dec 19 06:20:49 2007 UTC (11 years, 11 months ago) by jpye
File MIME type: text/x-python
File size: 45616 byte(s)
Moved 'incidence.c' and 'incidence.h' to base/generic/system.
Change system_write_graph to use GraphViz directly, and create PNG output.
Created 'TestSystem' suite in test.py and added test for PNG graph create (no checking performed though so far).
Updated Simulation::write to use the new system_write_graph syntax (no filters any more).
Fixed WITH_GRAPHVIZ flags for graph.c.
1 johnpye 1008 #!/usr/bin/env python
2 johnpye 1102 # ASCEND modelling environment
3 johnpye 1259 # Copyright (C) 2006, 2007 Carnegie Mellon University
4 johnpye 1102 #
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 johnpye 1288 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 johnpye 1028
40 johnpye 1288 sys.setdlopenflags(_dlflags)
41    
42 johnpye 956 class Ascend(unittest.TestCase):
43 johnpye 669
44 johnpye 933 def setUp(self):
45     import ascpy
46 johnpye 1118 self.L = ascpy.Library()
47 johnpye 933
48     def tearDown(self):
49     self.L.clear()
50     del self.L
51    
52 johnpye 1024 class AscendSelfTester(Ascend):
53    
54 johnpye 1257 def _run(self,modelname,solvername="QRSlv",filename=None,parameters={}):
55 johnpye 1024 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 johnpye 1257 M.setSolver(ascpy.Solver(solvername))
61     for k,v in parameters.iteritems():
62     M.setParameter(k,v)
63 johnpye 1024 M.solve(ascpy.Solver(solvername),ascpy.SolverReporter())
64     M.run(T.getMethod('self_test'))
65     return M
66    
67 johnpye 966 class TestCompiler(Ascend):
68    
69 johnpye 1213 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 johnpye 941 def testloading(self):
85 johnpye 1213 """library startup"""
86 johnpye 941 pass
87    
88     def testsystema4l(self):
89 johnpye 1213 """loading system.a4l?"""
90 johnpye 941 self.L.load('system.a4l')
91    
92     def testatomsa4l(self):
93 johnpye 1213 """loading atoms.a4l?"""
94 johnpye 941 self.L.load('atoms.a4l')
95    
96 johnpye 1213 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 johnpye 1292 def defaultmethodstest(self,modelname):
105     self.L.load("test/defaultmethods.a4c")
106     T = self.L.findType(modelname)
107     M = T.getSimulation('sim')
108     M.run(T.getMethod('on_load'))
109     M.run(T.getMethod('self_test'))
110     return M
111    
112     def testdefault1(self):
113     self.defaultmethodstest('testdefault1')
114    
115     def testdefault2(self):
116     self.defaultmethodstest('testdefault2')
117    
118     def testdefault3(self):
119     self.defaultmethodstest('testdefault3')
120    
121     def testdefault4(self):
122     self.defaultmethodstest('testdefault4')
123    
124     def testdefault5(self):
125     self.defaultmethodstest('testdefault5')
126    
127     def testdefault6(self):
128     self.defaultmethodstest('testdefault6')
129    
130     def testdefault7(self):
131     self.defaultmethodstest('testdefault7')
132    
133     def testdefault8(self):
134     self.defaultmethodstest('testdefault8')
135    
136     def testdefault9(self):
137     self.defaultmethodstest('testdefault9')
138    
139     def testdefault10(self):
140     self.defaultmethodstest('testdefault10')
141    
142     def testdefault11(self):
143     self.defaultmethodstest('testdefault11')
144    
145     def testdefault12(self):
146     self.defaultmethodstest('testdefault12')
147    
148     def testdefault13(self):
149     self.defaultmethodstest('testdefault13')
150    
151     def testdefault14(self):
152     self.defaultmethodstest('testdefault14')
153    
154     def testdefault15(self):
155     self.defaultmethodstest('testdefault15')
156    
157     def testdefault16(self):
158     self.defaultmethodstest('testdefault16')
159    
160 johnpye 1304 def testdefault17(self):
161     self.defaultmethodstest('testdefault17')
162     def testdefault18(self):
163     self.defaultmethodstest('testdefault18')
164    
165 jpye 1372 def testdefault19(self):
166     self.defaultmethodstest('testdefault19')
167    
168 jpye 1406 #def testdefault19fail(self):
169     # self.defaultmethodstest('testdefault19fail')
170 jpye 1372
171     def testdefault20(self):
172     self.defaultmethodstest('testdefault20')
173    
174 jpye 1406 #def testdefault20fail(self):
175     # self.defaultmethodstest('testdefault20fail')
176 jpye 1372
177 jpye 1679 class TestSystem(AscendSelfTester):
178    
179     def testwritegraph(self):
180     M = self._run('testlog10')
181     M.run(self.L.findType('testlog10').getMethod('on_load'))
182     if platform.system!="Windows":
183     f = file('temp.png','wb')
184     M.write(f,"dot")
185     f.close()
186     else:
187     self.fail("not implemented on windows")
188    
189 johnpye 1024 class TestSolver(AscendSelfTester):
190 johnpye 966
191     def testlog10(self):
192 jpye 1349 M = self._run('testlog10')
193 johnpye 966
194 johnpye 1156 def testrootsofpoly(self):
195     self._run('roots_of_poly',filename="roots_of_poly.a4c")
196    
197 johnpye 1152 def testcollapsingcan(self):
198     self._run('collapsingcan',filename="collapsingcan.a4c")
199    
200 johnpye 1165 def testdistancecalc(self):
201     self._run('distance_calc',filename="distance_calc.a4c")
202    
203 johnpye 966 def testconopt(self):
204 jpye 1505 self._run('conopttest',"CONOPT",filename="conopttest.a4c")
205 johnpye 966
206     def testcmslv2(self):
207 johnpye 974 self._run('testcmslv2',"CMSlv")
208 johnpye 966
209     def testsunpos1(self):
210     self._run('example_1_6_1',"QRSlv","johnpye/sunpos.a4c")
211    
212     def testsunpos2(self):
213     self._run('example_1_6_2',"QRSlv","johnpye/sunpos.a4c")
214    
215     def testsunpos3(self):
216     self._run('example_1_7_1',"QRSlv","johnpye/sunpos.a4c")
217    
218     def testsunpos4(self):
219     self._run('example_1_7_2',"QRSlv","johnpye/sunpos.a4c")
220    
221     def testsunpos5(self):
222     self._run('example_1_7_3',"QRSlv","johnpye/sunpos.a4c")
223    
224     def testsunpos6(self):
225     self._run('example_1_8_1',"QRSlv","johnpye/sunpos.a4c")
226    
227 johnpye 1073 def testinstanceas(self):
228     M = self._run('example_1_6_1',"QRSlv","johnpye/sunpos.a4c")
229     self.assertAlmostEqual( float(M.t_solar), M.t_solar.as("s"))
230     self.assertAlmostEqual( float(M.t_solar)/3600, M.t_solar.as("h"))
231    
232 jpye 1363 def testrelinclude(self):
233     self.L.load('test/relinclude.a4c')
234     T = self.L.findType('relinclude')
235     M = T.getSimulation('sim')
236     M.eq1.setIncluded(True)
237     M.eq2.setIncluded(False)
238     M.eq3.setIncluded(False)
239     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
240     self.assertAlmostEqual( float(M.z), 2.0)
241     M.eq1.setIncluded(False)
242     M.eq2.setIncluded(True)
243     M.eq3.setIncluded(False)
244     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
245     self.assertAlmostEqual( float(M.z), 4.0)
246     M.eq1.setIncluded(False)
247     M.eq2.setIncluded(False)
248     M.eq3.setIncluded(True)
249     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
250     self.assertAlmostEqual( float(M.z), 4.61043629206)
251 jpye 1349
252 jpye 1363
253 jpye 1341 class TestLRSlv(AscendSelfTester):
254     def testonerel(self):
255     self._run('onerel',"LRSlv","test/lrslv/onerel.a4c")
256    
257 jpye 1342 # need to migrate to 'FIX boolvar', currently not supported...
258     # def testonerel(self):
259     # self._run('onerel',"LRSlv","test/lrslv/onerel.a4c")
260    
261 jpye 1348 def testsequencecrash(self):
262     try:
263     self._run('onerel',"LRSlv","test/lrslv/sequencecrash.a4c")
264     except:
265     pass
266     # it just has to not crash, that's all
267    
268 jpye 1342 def testsequence(self):
269     self._run('onerel',"LRSlv","test/lrslv/sequence.a4c")
270    
271    
272 johnpye 1257 class TestCMSlv(AscendSelfTester):
273 jpye 1344 def testsonic(self):
274     M = self._run('sonic',"CMSlv","sonic.a4c")
275     assert(M.sonic_flow.getBoolValue())
276    
277     # other side of boundary...
278     M.D.setRealValueWithUnits(4.,"cm")
279     T = self.L.findType('sonic')
280     M.solve(ascpy.Solver('CMSlv'),ascpy.SolverReporter())
281     M.run(T.getMethod('self_test'))
282     assert(not M.sonic_flow.getBoolValue())
283    
284 johnpye 1257 def testheatex(self):
285     self._run('heatex',"CMSlv","heatex.a4c")
286     def testphaseeq(self):
287     self._run('phaseq',"CMSlv","phaseq.a4c")
288     def testpipeline(self):
289     self._run('pipeline',"CMSlv","pipeline.a4c"
290     ,{'infinity':3.2e9}
291     )
292     def testrachford(self):
293     self._run('rachford',"CMSlv","rachford.a4c")
294     def testlinmassbal(self):
295     self._run('linmassbal',"CMSlv","linmassbal.a4c")
296    
297    
298 johnpye 1126 class TestMatrix(AscendSelfTester):
299     def testlog10(self):
300     M = self._run('testlog10')
301 jpye 1380 print "FETCHING MATRIX................."
302     X = M.getMatrix()
303     # this stuff crashes Windows because the FILE* structure used by Python is not the same
304     # as used by MinGW...
305     #print "GOT MATRIX"
306     #sys.stderr.flush()
307     #sys.stdout.flush()
308     #F = os.tmpfile()
309     #X.write(F.fileno,"mmio")
310     #F.seek(0)
311     #print F.read()
312 johnpye 1126
313 johnpye 966 class TestIntegrator(Ascend):
314    
315 johnpye 941 def testListIntegrators(self):
316     I = ascpy.Integrator.getEngines()
317 jpye 1452 s1 = sorted([str(i) for i in I])
318 jpye 1491 assert 'IDA' in s1
319     assert 'LSODE' in s1
320 johnpye 941
321 johnpye 942 # this routine is reused by both testIDA and testLSODE
322 johnpye 941 def _testIntegrator(self,integratorname):
323 johnpye 940 self.L.load('johnpye/shm.a4c')
324     M = self.L.findType('shm').getSimulation('sim')
325 johnpye 972 M.setSolver(ascpy.Solver('QRSlv'))
326 johnpye 1133 P = M.getParameters()
327     M.setParameter('feastol',1e-12)
328 johnpye 979 print M.getChildren()
329     assert float(M.x) == 10.0
330     assert float(M.v) == 0.0
331 johnpye 941 t_end = math.pi
332 johnpye 940
333     I = ascpy.Integrator(M)
334     I.setReporter(ascpy.IntegratorReporterNull(I))
335 johnpye 941 I.setEngine(integratorname);
336 johnpye 940 I.setLinearTimesteps(ascpy.Units("s"), 0.0, t_end, 100);
337 johnpye 1133 I.setMinSubStep(0.0001); # these limits are required by IDA at present (numeric diff)
338     I.setMaxSubStep(0.1);
339 johnpye 941 I.setInitialSubStep(0.001);
340     I.setMaxSubSteps(200);
341 johnpye 944 if(integratorname=='IDA'):
342     I.setParameter('autodiff',False)
343 johnpye 1133 for p in M.getParameters():
344     print p.getName(),"=",p.getValue()
345 johnpye 940 I.analyse();
346     I.solve();
347 johnpye 941 print "At end of simulation,"
348 johnpye 979 print "x = %f" % M.x
349     print "v = %f" % M.v
350     assert abs(float(M.x) + 10) < 1e-2
351     assert abs(float(M.v)) < 1e-2
352 johnpye 940 assert I.getNumObservedVars() == 3
353    
354 johnpye 941 def testInvalidIntegrator(self):
355 johnpye 966 self.L.load('johnpye/shm.a4c')
356 johnpye 941 M = self.L.findType('shm').getSimulation('sim')
357 johnpye 972 M.setSolver(ascpy.Solver('QRSlv'))
358 johnpye 941 I = ascpy.Integrator(M)
359     try:
360     I.setEngine('___NONEXISTENT____')
361 jpye 1452 except IndexError:
362 johnpye 941 return
363     self.fail("setEngine did not raise error!")
364    
365     def testLSODE(self):
366     self._testIntegrator('LSODE')
367    
368 johnpye 972 def testIDA(self):
369     self._testIntegrator('IDA')
370    
371 johnpye 1016 def testparameters(self):
372     self.L.load('johnpye/shm.a4c')
373     M = self.L.findType('shm').getSimulation('sim')
374     M.build()
375     I = ascpy.Integrator(M)
376     I.setEngine('IDA')
377     P = I.getParameters()
378     for p in P:
379     print p.getName(),"=",p.getValue()
380 johnpye 1280 assert len(P)==12
381 johnpye 1016 assert P[0].isStr()
382     assert P[0].getName()=="linsolver"
383 johnpye 1307 assert P[0].getValue()=='DENSE'
384 johnpye 1280 assert P[2].getName()=="maxord"
385     assert P[3].getName()=="autodiff"
386     assert P[3].getValue()==True
387     assert P[8].getName()=="atolvect"
388     assert P[8].getBoolValue() == True
389     P[3].setBoolValue(False)
390     assert P[3].getBoolValue()==False
391 johnpye 1016 I.setParameters(P)
392     assert I.getParameterValue('autodiff')==False
393     I.setParameter('autodiff',True)
394     try:
395     v = I.getParameterValue('nonexist')
396     except KeyError:
397     pass
398     else:
399     self.fail('Failed to trip invalid Integrator parameter')
400    
401 johnpye 972 class TestLSODE(Ascend):
402    
403 johnpye 964 def testzill(self):
404     self.L.load('johnpye/zill.a4c')
405     T = self.L.findType('zill')
406     M = T.getSimulation('sim')
407 johnpye 972 M.setSolver(ascpy.Solver('QRSlv'))
408 johnpye 964 I = ascpy.Integrator(M)
409 johnpye 966 I.setEngine('LSODE')
410     I.setMinSubStep(1e-7)
411     I.setMaxSubStep(0.001)
412     I.setMaxSubSteps(10000)
413 johnpye 964 I.setReporter(ascpy.IntegratorReporterConsole(I))
414 johnpye 1017 I.setLinearTimesteps(ascpy.Units(), 1.0, 1.5, 5)
415 johnpye 964 I.analyse()
416     I.solve()
417     M.run(T.getMethod('self_test'))
418    
419 johnpye 962 def testnewton(self):
420 johnpye 973 sys.stderr.write("STARTING TESTNEWTON\n")
421 johnpye 962 self.L.load('johnpye/newton.a4c')
422     T = self.L.findType('newton')
423     M = T.getSimulation('sim')
424     M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
425     I = ascpy.Integrator(M)
426     I.setEngine('LSODE')
427 johnpye 963 I.setParameter('rtolvect',False)
428     I.setParameter('rtol',1e-7)
429     I.setParameter('atolvect',False)
430     I.setParameter('atol',1e-7)
431     I.setMinSubStep(1e-7)
432     I.setMaxSubStep(0.001)
433     I.setMaxSubSteps(10000)
434    
435 johnpye 962 I.setReporter(ascpy.IntegratorReporterConsole(I))
436 johnpye 1017 I.setLinearTimesteps(ascpy.Units("s"), 0, 2*float(M.v)/float(M.g), 2)
437 johnpye 962 I.analyse()
438     I.solve()
439     print "At end of simulation,"
440 johnpye 979 print "x = %f" % M.x
441     print "v = %f" % M.v
442 johnpye 962 M.run(T.getMethod('self_test'))
443    
444 johnpye 961 def testlotka(self):
445     self.L.load('johnpye/lotka.a4c')
446     M = self.L.findType('lotka').getSimulation('sim')
447 johnpye 980 M.setSolver(ascpy.Solver("QRSlv"))
448 johnpye 961 I = ascpy.Integrator(M)
449     I.setEngine('LSODE')
450     I.setReporter(ascpy.IntegratorReporterConsole(I))
451 johnpye 1017 I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 5)
452 johnpye 961 I.analyse()
453 johnpye 979 print "Number of vars = %d" % I.getNumVars()
454     assert I.getNumVars()==2
455 johnpye 961 I.solve()
456     assert I.getNumObservedVars() == 3;
457 johnpye 979 assert abs(M.R - 832) < 1.0
458     assert abs(M.F - 21.36) < 0.1
459 johnpye 1017
460 jpye 1351 def testwritegraph(self):
461     self.L.load('johnpye/lotka.a4c')
462     M = self.L.findType('lotka').getSimulation('sim')
463     F = file('lotka.dot','w')
464     M.build()
465     M.write(F,"dot")
466    
467    
468 johnpye 1017 #-------------------------------------------------------------------------------
469 johnpye 1032 # Testing of a external blackbox functions
470 johnpye 1021
471 johnpye 1032 class TestBlackBox(AscendSelfTester):
472     def testparsefail0(self):
473     try:
474     self.L.load('test/blackbox/parsefail0.a4c')
475     self.fail("parsefail0 should not have loaded without errors")
476     except:
477     pass
478    
479     def testparsefail1(self):
480     try:
481     self.L.load('test/blackbox/parsefail1.a4c')
482     self.fail("parsefail1 should not have loaded without errors")
483     except:
484     pass
485    
486     def testparsefail2(self):
487     try:
488     self.L.load('test/blackbox/parsefail2.a4c')
489     self.fail("parsefail2 should not have loaded without errors")
490     except:
491     pass
492    
493     def testparsefail3(self):
494     try:
495     self.L.load('test/blackbox/parsefail3.a4c')
496     self.fail("parsefail3 should not have loaded without errors")
497     except:
498     pass
499    
500     def testparsefail4(self):
501     try:
502     self.L.load('test/blackbox/parsefail4.a4c')
503     self.fail("parsefail4 should not have loaded")
504     except:
505     pass
506    
507     def testfail1(self):
508     """Mismatched arg counts check-- tests bbox, not ascend."""
509     self.L.load('test/blackbox/fail1.a4c')
510 johnpye 1034 try:
511 johnpye 1035 M = self.L.findType('fail1').getSimulation('sim')
512 johnpye 1034 self.fail("expected exception was not raised")
513     except RuntimeError,e:
514     print "Caught exception '%s', assumed ok" % e
515 johnpye 1032
516     def testfail2(self):
517     """Incorrect data arg check -- tests bbox, not ascend"""
518     self.L.load('test/blackbox/fail2.a4c')
519 johnpye 1035 try:
520     M = self.L.findType('fail2').getSimulation('sim')
521     self.fail("expected exception was not raised")
522     except RuntimeError,e:
523     print "Caught exception '%s', assumed ok (should mention errors during instantiation)" % e
524 johnpye 1032
525     def testpass1(self):
526     """simple single bbox forward solve"""
527     M = self._run('pass1',filename='test/blackbox/pass.a4c')
528    
529     def testpass2(self):
530     """simple single bbox reverse solve"""
531     M = self._run('pass2',filename='test/blackbox/pass.a4c')
532    
533     def testpass3(self):
534     """simple double bbox solve"""
535     M = self._run('pass3',filename='test/blackbox/pass3.a4c')
536    
537     def testpass4(self):
538     """simple double bbox reverse solve"""
539     M = self._run('pass4',filename='test/blackbox/pass3.a4c')
540    
541     def testpass5(self):
542     M = self._run('pass5',filename='test/blackbox/pass5.a4c')
543    
544     def testpass6(self):
545     M = self._run('pass6',filename='test/blackbox/pass5.a4c')
546    
547     def testpass7(self):
548     M = self._run('pass7',filename='test/blackbox/passmerge.a4c')
549    
550     def testpass8(self):
551     M = self._run('pass8',filename='test/blackbox/passmerge.a4c')
552    
553     def testpass9(self):
554     M = self._run('pass9',filename='test/blackbox/passmerge.a4c')
555    
556     def testpass10(self):
557     M = self._run('pass10',filename='test/blackbox/passmerge.a4c')
558    
559     def testpass11(self):
560     M = self._run('pass11',filename='test/blackbox/passmerge.a4c')
561    
562     def testpass12(self):
563     M = self._run('pass12',filename='test/blackbox/passmerge.a4c')
564    
565 johnpye 1037 # this test doesn't work: 'system is inconsistent' -- and structurally singular
566     # def testpass13(self):
567     # """cross-merged input/output solve"""
568     # M = self._run('pass13',filename='test/blackbox/passmerge.a4c')
569 johnpye 1032
570     def testpass14(self):
571     """cross-merged input/output reverse solve"""
572     M = self._run('pass14',filename='test/blackbox/passmerge.a4c')
573    
574     def testpass20(self):
575     M = self._run('pass20',filename='test/blackbox/passarray.a4c')
576    
577     def testparsefail21(self):
578     """dense array of black boxes wrong syntax"""
579     try:
580     self.L.load('test/blackbox/parsefail21.a4c')
581     self.fail("parsefail21 should not have loaded without errors")
582     except:
583     pass
584    
585     def testpass22(self):
586     M = self._run('pass22',filename='test/blackbox/passarray.a4c')
587    
588     def testpass23(self):
589     M = self._run('pass23',filename='test/blackbox/passarray.a4c')
590    
591     def testpass61(self):
592     M = self._run('pass61',filename='test/blackbox/reinstantiate.a4c')
593    
594     def testpass62(self):
595     M = self._run('pass62',filename='test/blackbox/reinstantiate.a4c')
596    
597     def testpass64(self):
598     M = self._run('pass64',filename='test/blackbox/reinstantiate.a4c')
599    
600     def testpass65(self):
601     M = self._run('pass65',filename='test/blackbox/reinstantiate.a4c')
602    
603     def testpass66(self):
604     M = self._run('pass66',filename='test/blackbox/reinstantiate.a4c')
605    
606     def testpass67(self):
607     M = self._run('pass67',filename='test/blackbox/reinstantiate.a4c')
608    
609 johnpye 1024 class TestExtFn(AscendSelfTester):
610 johnpye 1021 def testextfntest(self):
611 johnpye 1024 M = self._run('extfntest',filename='johnpye/extfn/extfntest.a4c')
612     self.assertAlmostEqual(M.y, 2);
613     self.assertAlmostEqual(M.x, 1);
614 johnpye 1021 self.assertAlmostEqual(M.y, M.x + 1);
615    
616 johnpye 1039 def testextrelfor(self):
617     M = self._run('extrelfor',filename='johnpye/extfn/extrelfor.a4c')
618 johnpye 1024
619 johnpye 1056 ## @TODO fix bug with badly-named bbox rel in a loop (Ben, maybe)
620     # def testextrelforbadnaming(self):
621     # self.L.load('johnpye/extfn/extrelforbadnaming.a4c')
622     # T = self.L.findType('extrelfor')
623     # M = T.getSimulation('sim')
624     # M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
625     # print "x[1] = %f" % M.x[1]
626     # print "x[2] = %f" % M.x[2]
627     # print "x[3] = %f" % M.x[3]
628     # print "x[4] = %f" % M.x[4]
629     # print "x[5] = %f" % M.x[5]
630     # M.run(T.getMethod('self_test'))
631 johnpye 1039
632 johnpye 1024 def testextrelrepeat(self):
633     M = self._run('extrelrepeat',filename='johnpye/extfn/extrelrepeat.a4c')
634    
635 johnpye 1021 #-------------------------------------------------------------------------------
636 johnpye 1162 # Testing of Sensitivity module
637    
638     class TestSensitivity(AscendSelfTester):
639     def test1(self):
640     self.L.load('sensitivity_test.a4c')
641     T = self.L.findType('sensitivity_test')
642     M = T.getSimulation('sim',False)
643     M.run(T.getMethod('on_load'))
644     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
645     M.run(T.getMethod('analyse'))
646 johnpye 1163 M.run(T.getMethod('self_test'))
647 johnpye 1167
648 johnpye 1168 # def testall(self):
649     # self.L.load('sensitivity_test.a4c')
650     # T = self.L.findType('sensitivity_test_all')
651     # M = T.getSimulation('sim',False)
652     # M.run(T.getMethod('on_load'))
653     # M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
654     # M.run(T.getMethod('analyse'))
655     # M.run(T.getMethod('self_test'))
656     # CAUSES CRASH
657 johnpye 1162
658     #-------------------------------------------------------------------------------
659 johnpye 1024 # Testing of a ExtPy - external python methods
660    
661     class TestExtPy(AscendSelfTester):
662 johnpye 1055 def test1(self):
663     self.L.load('johnpye/extpy/extpytest.a4c')
664     T = self.L.findType('extpytest')
665     M = T.getSimulation('sim')
666     M.run(T.getMethod('self_test'))
667    
668     def test2(self):
669     self.L.load('johnpye/extpy/extpytest.a4c')
670     T = self.L.findType('extpytest')
671     M = T.getSimulation('sim')
672     M.run(T.getMethod('pythonthing'))
673     M.run(T.getMethod('pythonthing'))
674     M.run(T.getMethod('pythonthing'))
675     M.run(T.getMethod('pythonthing'))
676 johnpye 1205 M.run(T.getMethod('pythonthing'))
677     M.run(T.getMethod('pythonthing'))
678     M.run(T.getMethod('pythonthing'))
679 johnpye 1055 # causes crash!
680 johnpye 1024
681     #-------------------------------------------------------------------------------
682 johnpye 1042 # Testing of saturated steam properties library (iapwssatprops.a4c)
683    
684     class TestSteam(AscendSelfTester):
685 johnpye 1161
686 johnpye 1042 def testiapwssatprops1(self):
687     M = self._run('testiapwssatprops1',filename='steam/iapwssatprops.a4c')
688     def testiapwssatprops2(self):
689     M = self._run('testiapwssatprops2',filename='steam/iapwssatprops.a4c')
690     def testiapwssatprops3(self):
691     M = self._run('testiapwssatprops3',filename='steam/iapwssatprops.a4c')
692    
693 johnpye 1161 # test the stream model basically works
694 johnpye 1043 def testsatsteamstream(self):
695     M = self._run('satsteamstream',filename='steam/satsteamstream.a4c')
696 johnpye 1042
697 johnpye 1161 # test that we can solve in terms of various (rho,u)
698     def testsatuv(self):
699     self.L.load('steam/iapwssat.a4c')
700     T = self.L.findType('testiapwssatuv')
701     M = T.getSimulation('sim',False)
702     M.run(T.getMethod('on_load'))
703     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
704     print "p = %f bar" % M.p.as('bar');
705     print "T = %f C" % (M.T.as('K') - 273.15);
706     print "x = %f" % M.x;
707     M.run(T.getMethod('self_test'))
708     M.run(T.getMethod('values2'))
709     # M.v.setRealValueWithUnits(1.0/450,"m^3/kg");
710     # M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
711     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
712     print "p = %f bar" % M.p.as('bar');
713     print "T = %f C" % (M.T.as('K') - 273.15);
714     print "x = %f" % M.x;
715     M.run(T.getMethod('self_test2'))
716    
717    
718 johnpye 1056 ## @TODO fix error capture from bounds checking during initialisation
719     # def testiapwssat1(self):
720     # M = self._run('testiapwssat1',filename='steam/iapwssat.a4c')
721 johnpye 1042
722 johnpye 1100 def testdsgsat(self):
723 johnpye 1196 self.L.load('steam/dsgsat3.a4c')
724     T = self.L.findType('dsgsat3')
725 johnpye 1100 M = T.getSimulation('sim',False)
726 johnpye 1127 M.run(T.getMethod('on_load'))
727 johnpye 1100 M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
728 johnpye 1152 self.assertAlmostEqual(M.dTw_dt[2],0.0);
729 johnpye 1127 M.run(T.getMethod('configure_dynamic'))
730     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
731 johnpye 1132 return M
732    
733 johnpye 1270 def testdsgsatrepeat(self):
734     self.L.load('steam/dsgsat3.a4c')
735     T = self.L.findType('dsgsat3')
736     M = T.getSimulation('sim',False)
737     M.run(T.getMethod('on_load'))
738     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
739     M.run(T.getMethod('on_load'))
740     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
741     M.run(T.getMethod('on_load'))
742     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
743    
744 johnpye 1273 def testvary(self):
745     self.L.load('steam/dsgsat3.a4c')
746     T = self.L.findType('dsgsat3')
747     M = T.getSimulation('sim',False)
748     M.run(T.getMethod('on_load'))
749     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
750     print "----- setting qdot_s -----"
751     M.qdot_s.setRealValueWithUnits(1000,"W/m")
752     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
753     print "----- setting qdot_s -----"
754     M.qdot_s.setRealValueWithUnits(2000,"W/m")
755     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
756    
757 johnpye 1265 def teststeadylsode(self):
758     "test that steady conditions are stable with LSODE"
759 johnpye 1132 M = self.testdsgsat()
760 johnpye 1265 #M.qdot_s.setRealValueWithUnits(1000,"W/m")
761     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
762     #M.setParameter('
763     I = ascpy.Integrator(M)
764     I.setEngine('LSODE')
765     I.setReporter(ascpy.IntegratorReporterConsole(I))
766 johnpye 1280 I.setLinearTimesteps(ascpy.Units("s"), 0, 3600, 10)
767 johnpye 1265 I.analyse()
768     I.solve()
769    
770 johnpye 1267 # def testpeturblsode(self):
771     # "test that steady conditions are stable with LSODE"
772     # M = self.testdsgsat()
773     # # here is the peturbation...
774     # M.qdot_s.setRealValueWithUnits(1000,"W/m")
775     # M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
776     # I = ascpy.Integrator(M)
777     # I.setEngine('LSODE')
778     # I.setReporter(ascpy.IntegratorReporterConsole(I))
779     # I.setLinearTimesteps(ascpy.Units("s"), 0, 5, 1)
780     # I.analyse()
781     # I.solve()
782 johnpye 1132
783 johnpye 1265 def teststeadyida(self):
784 johnpye 1137 M = self.testdsgsat()
785 johnpye 1152 self.assertAlmostEqual(M.dTw_dt[2],0.0)
786     Tw1 = float(M.T_w[2])
787 johnpye 1196 T = self.L.findType('dsgsat3')
788 johnpye 1137 M.run(T.getMethod('free_states'))
789 johnpye 1100 I = ascpy.Integrator(M)
790 johnpye 1132 I.setEngine('IDA')
791     I.setParameter('linsolver','DENSE')
792     I.setParameter('safeeval',True)
793 johnpye 1280 I.setParameter('rtol',1e-4)
794     I.setParameter('atolvect',False)
795     I.setParameter('atol',1e-4)
796     I.setParameter('maxord',3)
797     I.setInitialSubStep(0.001)
798 johnpye 1100 I.setReporter(ascpy.IntegratorReporterConsole(I))
799 johnpye 1280 I.setLinearTimesteps(ascpy.Units("s"), 0, 3600, 10)
800 johnpye 1273 I.analyse()
801 johnpye 1100 I.solve()
802 johnpye 1152 self.assertAlmostEqual(float(M.T_w[2]),Tw1)
803 johnpye 1127 M.qdot_s.setRealValueWithUnits(1000,"W/m")
804     self.assertAlmostEqual(M.qdot_s.as("W/m"),1000)
805     M.solve(ascpy.Solver('QRSlv'),ascpy.SolverReporter())
806 johnpye 1266 print "dTw/dt = %f" % M.dTw_dt[2]
807 johnpye 1152 self.assertNotAlmostEqual(M.dTw_dt[2],0.0)
808 jpye 1350 F=file('dsgsat.dot','w')
809     M.write(F,'dot')
810 johnpye 1265
811 johnpye 1266 def testpeturbida(self):
812     M = self.testdsgsat()
813     self.assertAlmostEqual(M.dTw_dt[2],0.0)
814     T = self.L.findType('dsgsat3')
815     M.run(T.getMethod('free_states'))
816     # here is the peturbation...
817 jpye 1383 qdot_s = float(M.qdot_s)
818     print "OLD QDOT_S = %f" % qdot_s
819 jpye 1395 M.qdot_s.setRealValueWithUnits(6000,"W/m")
820 johnpye 1267 # IDA has its own initial conditions solver, so no need to call QRSlv here
821 johnpye 1266 I = ascpy.Integrator(M)
822     I.setEngine('IDA')
823     I.setParameter('linsolver','DENSE')
824     I.setReporter(ascpy.IntegratorReporterConsole(I))
825 jpye 1383 #I.setLinearTimesteps(ascpy.Units("s"), 0,300,300)
826 jpye 1395 I.setLogTimesteps(ascpy.Units("s"), 0.009, 1200, 150)
827 johnpye 1266 I.analyse()
828 jpye 1327 F = file('ga.mm','w')
829 jpye 1339 I.writeMatrix(F,'dg/dz')
830 jpye 1327 F = file('gd.mm','w')
831 jpye 1339 I.writeMatrix(F,'dg/dx')
832 jpye 1327 F = file('fa.mm','w')
833 jpye 1339 I.writeMatrix(F,'df/dz')
834 jpye 1327 F = file('fd.mm','w')
835 jpye 1339 I.writeMatrix(F,'df/dx')
836 jpye 1327 F = file('fdp.mm','w')
837 jpye 1339 I.writeMatrix(F,"df/dx'")
838 johnpye 1266 I.solve()
839    
840 johnpye 1042 #-------------------------------------------------------------------------------
841 johnpye 1017 # Testing of freesteam external steam properties functions
842    
843 johnpye 1032 with_freesteam = True
844 johnpye 1017 try:
845 johnpye 1039 # we assume that if the freesteam python module is installed, the ASCEND
846     # external library will also be.
847 johnpye 1017 import freesteam
848     have_freesteam = True
849 johnpye 1018 except ImportError,e:
850 johnpye 1017 have_freesteam = False
851    
852 johnpye 1024 if with_freesteam and have_freesteam:
853 johnpye 1039 class TestFreesteam(AscendSelfTester):
854 johnpye 1119 # def testfreesteamtest(self):
855     # """run the self-test cases bundled with freesteam"""
856     # self._run('testfreesteam',filename='testfreesteam.a4c')
857 johnpye 1039
858 johnpye 1021 def testload(self):
859 johnpye 1039 """check that we can load 'thermalequilibrium2' (IMPORT "freesteam", etc)"""
860 johnpye 1017 self.L.load('johnpye/thermalequilibrium2.a4c')
861 johnpye 1018
862 johnpye 1021 def testinstantiate(self):
863 johnpye 1039 """load an instantiate 'thermalequilibrium2'"""
864 johnpye 1021 self.testload()
865 johnpye 1018 M = self.L.findType('thermalequilibrium2').getSimulation('sim')
866 johnpye 1039 return M
867 johnpye 1021
868 johnpye 1039 def testintegrate(self):
869     """integrate transfer of heat from one mass of water/steam to another
870     according to Newton's law of cooling"""
871     M = self.testinstantiate()
872 johnpye 1018 M.setSolver(ascpy.Solver("QRSlv"))
873 johnpye 1039 I = ascpy.Integrator(M)
874     I.setEngine('LSODE')
875     I.setReporter(ascpy.IntegratorReporterConsole(I))
876     I.setLinearTimesteps(ascpy.Units("s"), 0, 3000, 30)
877 johnpye 1055 I.setMinSubStep(0.01)
878     I.setInitialSubStep(1)
879 johnpye 1039 I.analyse()
880     print "Number of vars = %d" % I.getNumVars()
881     assert I.getNumVars()==2
882     I.solve()
883     assert I.getNumObservedVars() == 3;
884     print "S[1].T = %f K" % M.S[1].T
885     print "S[2].T = %f K" % M.S[2].T
886     print "Q = %f W" % M.Q
887 johnpye 1119 self.assertAlmostEqual(float(M.S[1].T),506.77225109,4);
888 johnpye 1056 self.assertAlmostEqual(float(M.S[2].T),511.605173967,5);
889     self.assertAlmostEqual(float(M.Q),-48.32922877329,3);
890 johnpye 1039 self.assertAlmostEqual(float(M.t),3000);
891     print "Note that the above values have not been verified analytically"
892 johnpye 1017
893 johnpye 1170 def testcollapsingcan2(self):
894     """ solve the collapsing can model using IAPWS-IF97 steam props """
895     M = self._run("collapsingcan2",filename="collapsingcan2.a4c");
896 johnpye 1121
897 johnpye 1017 #-------------------------------------------------------------------------------
898 jpye 1374 # Testing of the brent-solver EXTERNAL method
899    
900     class TestBrent(AscendSelfTester):
901     def testbrent(self):
902     M = self._run('brent1',filename='test/brent.a4c')
903    
904     #-------------------------------------------------------------------------------
905 johnpye 1199 # Testing of IDA's analysis module
906    
907     class TestIDA(Ascend):
908 johnpye 1200 def _run(self,filen,modeln=""):
909     self.L.load('test/ida/%s.a4c' % filen)
910     T = self.L.findType('%s%s' % (filen,modeln))
911 johnpye 1199 M = T.getSimulation('sim')
912     M.build()
913     I = ascpy.Integrator(M)
914     I.setEngine('IDA')
915     I.analyse()
916 johnpye 1246 return M;
917 johnpye 1199
918 johnpye 1200 def _runfail(self,filen,n,msg="failed"):
919     try:
920     self._run(filen,'fail%d' % n)
921     except Exception,e:
922     print "(EXPECTED) ERROR: %s" % e
923     return
924     self.fail(msg)
925    
926 johnpye 1199 def testsinglederiv(self):
927 johnpye 1200 self._run('singlederiv')
928 johnpye 1199
929     def testsinglederivfail1(self):
930 johnpye 1200 self._runfail('singlederiv',1
931     ,"t.ode_id=-1 did not trigger error")
932    
933 johnpye 1199 def testsinglederivfail2(self):
934 johnpye 1200 self._runfail('singlederiv',2
935     ,"dy_dt.ode_id=2 did not trigger error")
936 johnpye 1199
937     def testsinglederivfail3(self):
938 johnpye 1200 self._runfail('singlederiv',3
939     ,"dy_dt.ode_type=3 did not trigger error")
940 johnpye 1199
941     def testsinglederivfail4(self):
942 johnpye 1200 self._runfail('singlederiv',4
943     ,"duplicate ode_type=1 did not trigger error")
944 johnpye 1199
945     def testsinglederivfail5(self):
946 johnpye 1200 self._runfail('singlederiv',5
947     ,"duplicate ode_type=1 did not trigger error")
948 johnpye 1199
949     def testsinglederivfail6(self):
950 johnpye 1200 self._runfail('singlederiv',6
951     ,"duplicate ode_type=1 did not trigger error")
952 johnpye 1199
953 johnpye 1200 def testtwoderiv(self):
954     self._run('twoderiv')
955    
956     def testtwoderivfail1(self):
957     self._runfail('twoderiv',1)
958    
959     def testtwoderivfail2(self):
960     self._runfail('twoderiv',2)
961    
962     def testtwoderivfail3(self):
963     self._runfail('twoderiv',3)
964     def testtwoderivfail4(self):
965     self._runfail('twoderiv',4)
966     def testtwoderivfail5(self):
967     self._runfail('twoderiv',5)
968    
969 johnpye 1201 def testnoderivs(self):
970     self._runfail('noderivs',1)
971    
972     def testnoindeps(self):
973     self._runfail('indeps',1)
974    
975     def testtwoindeps(self):
976     self._runfail('indeps',2)
977    
978     def testfixedvars(self):
979     self._run('fixedvars')
980    
981     def testfixedvars1(self):
982     self._run('fixedvars',1)
983    
984 jpye 1324 # fails the index check
985     # def testfixedvars2(self):
986     # self._run('fixedvars',2)
987 johnpye 1201
988 jpye 1324 # fails the index check
989     # def testfixedvars3(self):
990     # self._run('fixedvars',3)
991 johnpye 1201
992 johnpye 1213 def testincidence(self):
993     self._run('incidence')
994 johnpye 1201
995 johnpye 1214 def testincidence1(self):
996     self._run('incidence',1)
997     def testincidence2(self):
998     self._run('incidence',2)
999     def testincidence3(self):
1000 johnpye 1246 M = self._run('incidence',3)
1001    
1002 johnpye 1214 def testincidence4(self):
1003     self._run('incidence',4)
1004     def testincidencefail5(self):
1005     self._runfail('incidence',5)
1006    
1007 johnpye 1306 def testwritematrix(self):
1008     self.L.load('test/ida/writematrix.a4c')
1009     T = self.L.findType('writematrix')
1010     M = T.getSimulation('sim')
1011     M.build()
1012     I = ascpy.Integrator(M)
1013     I.setEngine('IDA')
1014     I.analyse()
1015 jpye 1380 # this stuff fails on Windows because FILE structure is different python vs mingw
1016     # F = os.tmpfile()
1017     # I.writeMatrix(F,"dF/dy")
1018     # F.seek(0)
1019     # print F.read()
1020     # F1 = os.tmpfile()
1021     # I.writeMatrix(F1,"dF/dy'")
1022     # F1.seek(0)
1023     # print F1.read()
1024     # F1 = os.tmpfile()
1025     # I.writeMatrix(F1,"dg/dx")
1026     # F1.seek(0)
1027     # print F1.read()
1028     # # for the moment you'll have to check these results manually.
1029 johnpye 1306
1030 johnpye 1309 def testwritematrix2(self):
1031     self.L.load('test/ida/writematrix.a4c')
1032     T = self.L.findType('writematrix2')
1033     M = T.getSimulation('sim')
1034     M.build()
1035     I = ascpy.Integrator(M)
1036     I.setEngine('IDA')
1037     I.analyse()
1038 jpye 1380 # this stuff fails on Windows because FILE structure is different python vs mingw
1039     # F = os.tmpfile()
1040     # I.writeMatrix(F,"dF/dy")
1041     # F.seek(0)
1042     # print F.read()
1043     # F1 = os.tmpfile()
1044     # I.writeMatrix(F1,"dF/dy'")
1045     # F1.seek(0)
1046     # print F1.read()
1047     # F1 = os.tmpfile()
1048     # I.writeMatrix(F1,"dg/dx")
1049     # F1.seek(0)
1050     # print F1.read()
1051 jpye 1327 #F1 = os.tmpfile()
1052     #I.writeMatrix(F1,"dydp/dyd")
1053     #F1.seek(0)
1054     #print F1.read()
1055 johnpye 1309 # for the moment you'll have to check these results manually.
1056    
1057     def testindexproblem(self):
1058     self.L.load('test/ida/indexproblem.a4c')
1059     T = self.L.findType('indexproblem')
1060     M = T.getSimulation('sim')
1061     M.build()
1062     I = ascpy.Integrator(M)
1063     I.setEngine('IDA')
1064     I.analyse()
1065 jpye 1324 pass
1066 johnpye 1309
1067 jpye 1324 def testindexproblem2(self):
1068     self.L.load('test/ida/indexproblem.a4c')
1069     T = self.L.findType('indexproblem2')
1070     M = T.getSimulation('sim')
1071     M.build()
1072     I = ascpy.Integrator(M)
1073     I.setEngine('IDA')
1074     try:
1075     I.analyse()
1076     except Exception,e:
1077     return
1078     self.fail("Index problem not detected")
1079 johnpye 1309
1080 jpye 1337 def testboundaries(self):
1081     self.L.load('test/ida/boundaries.a4c')
1082     T = self.L.findType('boundaries')
1083     M = T.getSimulation('sim')
1084     M.build()
1085     I = ascpy.Integrator(M)
1086     I.setEngine('IDA')
1087     I.analyse()
1088     I.setLogTimesteps(ascpy.Units("s"), 0.1, 20, 20)
1089     I.setParameter('linsolver','DENSE')
1090     I.setParameter('calcic','Y')
1091     I.setParameter('linsolver','DENSE')
1092     I.setParameter('safeeval',False)
1093     I.setReporter(ascpy.IntegratorReporterConsole(I))
1094     I.solve()
1095    
1096 johnpye 1214 # doesn't work yet:
1097     # def testincidence5(self):
1098     # self._run('incidence',5)
1099    
1100    
1101 johnpye 1199 #-------------------------------------------------------------------------------
1102 johnpye 1017 # Testing of IDA models using DENSE linear solver
1103    
1104 johnpye 1016 class TestIDADENSE(Ascend):
1105 johnpye 1017 """IDA DAE integrator, DENSE linear solver"""
1106 johnpye 961
1107 johnpye 1042 def testlotka(self):
1108 johnpye 991 self.L.load('johnpye/lotka.a4c')
1109     M = self.L.findType('lotka').getSimulation('sim')
1110     M.setSolver(ascpy.Solver("QRSlv"))
1111     I = ascpy.Integrator(M)
1112     I.setEngine('IDA')
1113     I.setReporter(ascpy.IntegratorReporterConsole(I))
1114     I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 5);
1115     I.setParameter('linsolver','DENSE')
1116     I.setParameter('rtol',1e-8);
1117     I.analyse()
1118     assert I.getNumVars()==2
1119     assert abs(M.R - 1000) < 1e-300
1120     I.solve()
1121 johnpye 1017 assert I.getNumObservedVars() == 3
1122 johnpye 991 assert abs(M.R - 832) < 1.0
1123     assert abs(M.F - 21.36) < 0.1
1124 johnpye 972
1125 johnpye 975 def testdenx(self):
1126 johnpye 1026 print "-----------------------------====="
1127 johnpye 942 self.L.load('johnpye/idadenx.a4c')
1128     M = self.L.findType('idadenx').getSimulation('sim')
1129 johnpye 1017 M.setSolver(ascpy.Solver("QRSlv"))
1130 johnpye 942 I = ascpy.Integrator(M)
1131     I.setEngine('IDA')
1132 johnpye 1228 I.setParameter('calcic','YA_YDP')
1133 johnpye 972 I.setParameter('linsolver','DENSE')
1134 johnpye 1237 I.setParameter('safeeval',True)
1135 johnpye 944 I.setReporter(ascpy.IntegratorReporterConsole(I))
1136 johnpye 1017 I.setLogTimesteps(ascpy.Units("s"), 0.4, 4e10, 11)
1137 johnpye 950 I.setMaxSubStep(0);
1138 johnpye 1017 I.setInitialSubStep(0)
1139 johnpye 1228 I.setMaxSubSteps(0)
1140 johnpye 944 I.setParameter('autodiff',True)
1141     I.analyse()
1142     I.solve()
1143 johnpye 1022 assert abs(float(M.y1) - 5.1091e-08) < 2e-9
1144     assert abs(float(M.y2) - 2.0437e-13) < 2e-14
1145 johnpye 1017 assert abs(float(M.y3) - 1.0) < 1e-5
1146 johnpye 942
1147 johnpye 1247 def testhires(self):
1148     self.L.load('test/hires.a4c')
1149     T = self.L.findType('hires')
1150     M = T.getSimulation('sim')
1151     M.setSolver(ascpy.Solver('QRSlv'))
1152     I = ascpy.Integrator(M)
1153     I.setEngine('IDA')
1154     I.setParameter('linsolver','DENSE')
1155 johnpye 1251 I.setParameter('rtol',1.1e-15)
1156 johnpye 1247 I.setParameter('atolvect',0)
1157 johnpye 1251 I.setParameter('atol',1.1e-15)
1158 johnpye 1247 I.setReporter(ascpy.IntegratorReporterConsole(I))
1159     I.setLogTimesteps(ascpy.Units(""), 1, 321.8122, 5)
1160 johnpye 1251 I.setInitialSubStep(1e-5)
1161     I.setMaxSubSteps(10000)
1162 johnpye 1247 I.analyse()
1163     I.solve()
1164 johnpye 1251 for i in range(8):
1165     print "y[%d] = %.20g" % (i+1, M.y[i+1])
1166 johnpye 1247 M.run(T.getMethod('self_test'))
1167    
1168 johnpye 1253 def testchemakzo(self):
1169     self.L.load('test/chemakzo.a4c')
1170     T = self.L.findType('chemakzo')
1171 johnpye 1252 M = T.getSimulation('sim')
1172     M.setSolver(ascpy.Solver('QRSlv'))
1173     I = ascpy.Integrator(M)
1174     I.setEngine('IDA')
1175     I.setParameter('linsolver','DENSE')
1176 johnpye 1253 I.setParameter('rtol',1e-15)
1177 johnpye 1252 I.setParameter('atolvect',0)
1178 johnpye 1253 I.setParameter('atol',1e-15)
1179 johnpye 1252 I.setReporter(ascpy.IntegratorReporterConsole(I))
1180 johnpye 1253 I.setLinearTimesteps(ascpy.Units("s"), 1, 180, 5)
1181     I.setInitialSubStep(1e-13)
1182 johnpye 1252 I.setMaxSubSteps(10000)
1183     I.analyse()
1184     I.solve()
1185 johnpye 1255 for i in range(6):
1186 johnpye 1254 print "y[%d] = %.20g" % (i+1, M.y[i+1])
1187     M.run(T.getMethod('self_test'))
1188    
1189     def testtransamp(self):
1190     self.L.load('test/transamp.a4c')
1191     T = self.L.findType('transamp')
1192     M = T.getSimulation('sim')
1193     M.setSolver(ascpy.Solver('QRSlv'))
1194     I = ascpy.Integrator(M)
1195     I.setEngine('IDA')
1196     I.setParameter('linsolver','DENSE')
1197     I.setParameter('rtol',1e-7)
1198     I.setParameter('atolvect',0)
1199     I.setParameter('atol',1e-7)
1200     I.setReporter(ascpy.IntegratorReporterConsole(I))
1201     I.setLinearTimesteps(ascpy.Units("s"), 0.05, 0.2, 20)
1202     I.setInitialSubStep(0.00001)
1203     I.setMaxSubSteps(10000)
1204     I.analyse()
1205     I.solve()
1206 johnpye 1253 for i in range(6):
1207 johnpye 1252 print "y[%d] = %.20g" % (i+1, M.y[i+1])
1208     M.run(T.getMethod('self_test'))
1209    
1210 johnpye 1253 # MODEL FAILS ANALYSIS: we need to add support for non-incident differential vars
1211     # def testpollution(self):
1212     # self.L.load('test/pollution.a4c')
1213     # T = self.L.findType('pollution')
1214     # M = T.getSimulation('sim')
1215     # M.setSolver(ascpy.Solver('QRSlv'))
1216     # I = ascpy.Integrator(M)
1217     # I.setEngine('IDA')
1218     # I.setParameter('linsolver','DENSE')
1219     # I.setParameter('rtol',1.1e-15)
1220     # I.setParameter('atolvect',0)
1221     # I.setParameter('atol',1.1e-15)
1222     # I.setReporter(ascpy.IntegratorReporterConsole(I))
1223     # I.setLogTimesteps(ascpy.Units("s"), 1, 60, 5)
1224     # I.setInitialSubStep(1e-5)
1225     # I.setMaxSubSteps(10000)
1226     # I.analyse()
1227     # I.solve()
1228     # for i in range(20):
1229     # print "y[%d] = %.20g" % (i+1, M.y[i+1])
1230     # M.run(T.getMethod('self_test'))
1231    
1232 johnpye 1058 ## @TODO fails during IDACalcIC (model too big?)
1233     # def testkryx(self):
1234     # self.L.load('johnpye/idakryx.a4c')
1235     # ascpy.getCompiler().setUseRelationSharing(False)
1236     # M = self.L.findType('idakryx').getSimulation('sim')
1237     # M.setSolver(ascpy.Solver('QRSlv'))
1238     # M.build()
1239     # I = ascpy.Integrator(M)
1240     # I.setEngine('IDA')
1241     # I.setReporter(ascpy.IntegratorReporterConsole(I))
1242     # I.setParameter('linsolver','DENSE')
1243     # I.setParameter('maxl',8)
1244     # I.setParameter('gsmodified',False)
1245     # I.setParameter('autodiff',True)
1246     # I.setParameter('rtol',0)
1247     # I.setParameter('atol',1e-3);
1248     # I.setParameter('atolvect',False)
1249     # I.setParameter('calcic','YA_YDP')
1250     # I.analyse()
1251     # I.setLogTimesteps(ascpy.Units("s"), 0.01, 10.24, 11)
1252     # I.solve()
1253     # assert abs(M.u[2][2].getValue()) < 1e-5
1254 johnpye 1017
1255     #-------------------------------------------------------------------------------
1256     # Testing of IDA models using SPGMR linear solver (Krylov)
1257    
1258 johnpye 1016 # these tests are disabled until SPGMR preconditioning has been implemented
1259     class TestIDASPGMR:#(Ascend):
1260     def testlotka(self):
1261     self.L.load('johnpye/lotka.a4c')
1262     M = self.L.findType('lotka').getSimulation('sim')
1263     M.setSolver(ascpy.Solver("QRSlv"))
1264 johnpye 951 I = ascpy.Integrator(M)
1265     I.setEngine('IDA')
1266     I.setReporter(ascpy.IntegratorReporterConsole(I))
1267 johnpye 1017 I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 5)
1268     I.setParameter('rtol',1e-8)
1269 johnpye 951 I.analyse()
1270 johnpye 1016 assert I.getNumVars()==2
1271     assert abs(M.R - 1000) < 1e-300
1272 johnpye 951 I.solve()
1273 johnpye 1017 assert I.getNumObservedVars() == 3
1274 johnpye 1016 assert abs(M.R - 832) < 1.0
1275     assert abs(M.F - 21.36) < 0.1
1276 johnpye 951
1277 johnpye 1016
1278 johnpye 991 def testkryx(self):
1279 johnpye 951 self.L.load('johnpye/idakryx.a4c')
1280     M = self.L.findType('idakryx').getSimulation('sim')
1281 johnpye 952 M.build()
1282 johnpye 951 I = ascpy.Integrator(M)
1283     I.setEngine('IDA')
1284     I.setReporter(ascpy.IntegratorReporterConsole(I))
1285 johnpye 992 I.setParameter('linsolver','SPGMR')
1286 johnpye 993 I.setParameter('prec','JACOBI')
1287 johnpye 970 I.setParameter('maxl',8)
1288 johnpye 952 I.setParameter('gsmodified',False)
1289     I.setParameter('autodiff',True)
1290 johnpye 993 I.setParameter('gsmodified',True)
1291 johnpye 952 I.setParameter('rtol',0)
1292     I.setParameter('atol',1e-3);
1293     I.setParameter('atolvect',False)
1294 johnpye 993 I.setParameter('calcic','Y')
1295 johnpye 952 I.analyse()
1296     I.setLogTimesteps(ascpy.Units("s"), 0.01, 10.24, 10);
1297 johnpye 1017 print M.udot[1][3]
1298 johnpye 952 I.solve()
1299     assert 0
1300 johnpye 967
1301 johnpye 1016 def testzill(self):
1302     self.L.load('johnpye/zill.a4c')
1303     T = self.L.findType('zill')
1304     M = T.getSimulation('sim')
1305     M.setSolver(ascpy.Solver('QRSlv'))
1306     I = ascpy.Integrator(M)
1307     I.setEngine('IDA')
1308     I.setParameter('safeeval',False)
1309     I.setMinSubStep(1e-7)
1310     I.setMaxSubStep(0.001)
1311     I.setMaxSubSteps(10000)
1312     I.setReporter(ascpy.IntegratorReporterConsole(I))
1313 johnpye 1017 I.setLinearTimesteps(ascpy.Units(), 1.0, 1.5, 5)
1314 johnpye 1016 I.analyse()
1315     I.solve()
1316     M.run(T.getMethod('self_test'))
1317    
1318     def testdenxSPGMR(self):
1319     self.L.load('johnpye/idadenx.a4c')
1320     M = self.L.findType('idadenx').getSimulation('sim')
1321     M.setSolver(ascpy.Solver('QRSlv'))
1322     I = ascpy.Integrator(M)
1323     I.setEngine('IDA')
1324     I.setReporter(ascpy.IntegratorReporterConsole(I))
1325 johnpye 1017 I.setLogTimesteps(ascpy.Units("s"), 0.4, 4e10, 11)
1326 johnpye 1016 I.setMaxSubStep(0);
1327     I.setInitialSubStep(0);
1328     I.setMaxSubSteps(0);
1329     I.setParameter('autodiff',True)
1330     I.setParameter('linsolver','SPGMR')
1331     I.setParameter('gsmodified',False)
1332     I.setParameter('maxncf',10)
1333     I.analyse()
1334     I.solve()
1335 johnpye 1017 assert abs(float(M.y1) - 5.1091e-08) < 1e-10
1336     assert abs(float(M.y2) - 2.0437e-13) < 1e-15
1337     assert abs(float(M.y3) - 1.0) < 1e-5
1338 johnpye 1016
1339 jpye 1459 class TestDOPRI5(Ascend):
1340     def testlotka(self):
1341     self.L.load('johnpye/dopri5/dopri5test.a4c')
1342     M = self.L.findType('dopri5test').getSimulation('sim')
1343     M.setSolver(ascpy.Solver("QRSlv"))
1344     M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
1345     I = ascpy.Integrator(M)
1346     I.setEngine('DOPRI5')
1347     I.setReporter(ascpy.IntegratorReporterConsole(I))
1348     I.setLinearTimesteps(ascpy.Units("s"), 0, 200, 20)
1349     I.setParameter('rtol',1e-8)
1350     I.analyse()
1351     assert I.getNumVars()==1
1352     I.solve()
1353 jpye 1477 def testaren(self):
1354     self.L.load('johnpye/dopri5/aren.a4c')
1355     M = self.L.findType('aren').getSimulation('sim')
1356     M.setSolver(ascpy.Solver("QRSlv"))
1357 jpye 1507 M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
1358 jpye 1477 I = ascpy.Integrator(M)
1359     I.setEngine('DOPRI5')
1360     I.setReporter(ascpy.IntegratorReporterConsole(I))
1361 jpye 1478 #xend = 17.0652165601579625588917206249
1362 jpye 1480 I.setLinearTimesteps(ascpy.Units("s"), 0, 17.0652165601579625588917206249, 10)
1363 jpye 1477 I.setParameter('rtol',1e-7)
1364     I.setParameter('atol',1e-7)
1365     I.setParameter('tolvect',False)
1366 jpye 1507 I.setMinSubStep(0);
1367 jpye 1480 I.setMaxSubStep(0);
1368     I.setInitialSubStep(0);
1369 jpye 1477 I.analyse()
1370 jpye 1480 I.solve()
1371     assert abs(float(M.y[0]) - 0.994) < 1e-5
1372     assert abs(float(M.y[1]) - 0.0) < 1e-5
1373 jpye 1459
1374 jpye 1553 class TestIPOPT(Ascend):
1375     def test1(self):
1376     self.L.load('test/ipopt/test1.a4c')
1377     M = self.L.findType('test1').getSimulation('sim')
1378     M.solve(ascpy.Solver("IPOPT"),ascpy.SolverReporter())
1379    
1380 jpye 1562 # test some stuff for beam calculations
1381     class TestSection(Ascend):
1382     def test_compound3(self):
1383     self.L.load('johnpye/section.a4c')
1384     T = self.L.findType('compound_section_test3')
1385     M = T.getSimulation('sim')
1386     M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
1387     M.run(T.getMethod('self_test'))
1388 jpye 1564 def test_compound4(self):
1389     self.L.load('johnpye/section.a4c')
1390     T = self.L.findType('compound_section_test4')
1391     M = T.getSimulation('sim')
1392     M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
1393     M.run(T.getMethod('self_test'))
1394 jpye 1562 def test_compound2(self):
1395     self.L.load('johnpye/section.a4c')
1396     T = self.L.findType('compound_section_test2')
1397     M = T.getSimulation('sim')
1398     M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
1399     M.run(T.getMethod('self_test'))
1400    
1401 johnpye 943 # move code above down here if you want to temporarily avoid testing it
1402 johnpye 932 class NotToBeTested:
1403     def nothing(self):
1404     pass
1405 johnpye 1016
1406 johnpye 1251 def testnewton(self):
1407     sys.stderr.write("STARTING TESTNEWTON\n")
1408     self.L.load('johnpye/newton.a4c')
1409     T = self.L.findType('newton')
1410     M = T.getSimulation('sim')
1411     M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())
1412     I = ascpy.Integrator(M)
1413     I.setEngine('IDA')
1414     I.setParameter('linsolver','DENSE')
1415     I.setParameter('safeeval',True)
1416     I.setParameter('rtol',1e-8)
1417     I.setMaxSubStep(0.001)
1418     I.setMaxSubSteps(10000)
1419    
1420     I.setReporter(ascpy.IntegratorReporterConsole(I))
1421     I.setLinearTimesteps(ascpy.Units("s"), 0, 2*float(M.v)/float(M.g), 2)
1422     I.analyse()
1423     I.solve()
1424     print "At end of simulation,"
1425     print "x = %f" % M.x
1426     print "v = %f" % M.v
1427     M.run(T.getMethod('self_test'))
1428    
1429 jpye 1520 def patchpath(VAR,SEP,addvals):
1430     restart = 0
1431     envpath = [os.path.abspath(i) for i in os.environ[VAR].split(SEP)]
1432     for l in addvals:
1433     if l in envpath[len(addvals):]:
1434     envpath.remove(l)
1435     restart = 1
1436     for l in addvals:
1437     if l not in envpath:
1438     envpath.insert(0,l)
1439     restart = 1
1440     os.environ[VAR] = SEP.join(envpath)
1441     return restart
1442    
1443 johnpye 669 if __name__=='__main__':
1444 johnpye 1118 # a whole bag of tricks to make sure we get the necessary dirs in our ascend, python and ld path vars
1445 johnpye 1098 restart = 0
1446    
1447     if platform.system()=="Windows":
1448 johnpye 1120 LD_LIBRARY_PATH="PATH"
1449 johnpye 1098 SEP = ";"
1450     else:
1451     LD_LIBRARY_PATH="LD_LIBRARY_PATH"
1452     SEP = ":"
1453    
1454 jpye 1520 solverdir = os.path.abspath(os.path.join(sys.path[0],"solvers"))
1455 jpye 1553 solverdirs = [os.path.join(solverdir,s) for s in "qrslv","cmslv","lrslv","conopt","ida","lsode","ipopt"]
1456 jpye 1520
1457     if not os.environ.get('ASCENDSOLVERS'):
1458     os.environ['ASCENDSOLVERS'] = SEP.join(solverdirs)
1459     restart = 1
1460     else:
1461     if patchpath('ASCENDSOLVERS',SEP,solverdirs):
1462     restart = 1
1463    
1464 johnpye 1119 freesteamdir = os.path.expanduser("~/freesteam/ascend")
1465     modeldirs = [os.path.abspath(os.path.join(sys.path[0],"models")),os.path.abspath(freesteamdir)]
1466 jpye 1520
1467 johnpye 1118 if not os.environ.get('ASCENDLIBRARY'):
1468 jpye 1520 os.environ['ASCENDLIBRARY'] = SEP.join(modeldirs)
1469 johnpye 1118 restart = 1
1470     else:
1471 jpye 1520 if patchpath('ASCENDLIBRARY',SEP,modeldirs):
1472     restart = 1
1473 johnpye 1118
1474 johnpye 1102 libdirs = ["pygtk","."]
1475 johnpye 1098 libdirs = [os.path.normpath(os.path.join(sys.path[0],l)) for l in libdirs]
1476     if not os.environ.get(LD_LIBRARY_PATH):
1477 johnpye 1105 os.environ[LD_LIBRARY_PATH]=SEP.join(libdirs)
1478 johnpye 1106 restart = 1
1479 johnpye 1098 else:
1480     envlibdirs = [os.path.normpath(i) for i in os.environ[LD_LIBRARY_PATH].split(SEP)]
1481     for l in libdirs:
1482 johnpye 1106 if l in envlibdirs[len(libdirs):]:
1483     envlibdirs.remove(l)
1484     restart = 1
1485     for l in libdirs:
1486 johnpye 1098 if l not in envlibdirs:
1487     envlibdirs.insert(0,l)
1488 johnpye 1106 restart = 1
1489 johnpye 1098 os.environ[LD_LIBRARY_PATH] = SEP.join(envlibdirs)
1490    
1491 johnpye 1102 pypath = os.path.normpath(os.path.join(sys.path[0],"pygtk"))
1492     if not os.environ.get('PYTHONPATH'):
1493     os.environ['PYTHONPATH']=pypath
1494     else:
1495     envpypath = os.environ['PYTHONPATH'].split(SEP)
1496     if pypath not in envpypath:
1497     envpypath.insert(0,pypath)
1498 johnpye 1137 os.environ['PYTHONPATH']=SEP.join(envpypath)
1499 johnpye 1102 restart = 1
1500    
1501 jpye 1645 if restart and platform.system()!="Windows":
1502 jpye 1520 script = os.path.join(sys.path[0],"test.py")
1503     sys.stderr.write("Restarting with...\n")
1504     sys.stderr.write(" export LD_LIBRARY_PATH=%s\n" % os.environ.get(LD_LIBRARY_PATH))
1505     sys.stderr.write(" export PYTHONPATH=%s\n" % os.environ.get('PYTHONPATH'))
1506     sys.stderr.write(" export ASCENDLIBRARY=%s\n" % os.environ.get('ASCENDLIBRARY'))
1507     sys.stderr.write(" export ASCENDSOLVERS=%s\n" % os.environ.get('ASCENDSOLVERS'))
1508     sys.stderr.flush()
1509     os.execvp("python",[script] + sys.argv)
1510     exit(1)
1511     else:
1512     sys.stderr.write("Got...\n")
1513     sys.stderr.write(" LD_LIBRARY_PATH=%s\n" % os.environ.get(LD_LIBRARY_PATH))
1514     sys.stderr.write(" PYTHONPATH=%s\n" % os.environ.get('PYTHONPATH'))
1515     sys.stderr.write(" ASCENDLIBRARY=%s\n" % os.environ.get('ASCENDLIBRARY'))
1516     sys.stderr.write(" ASCENDSOLVERS=%s\n" % os.environ.get('ASCENDSOLVERS'))
1517     sys.stderr.flush()
1518 johnpye 1098
1519     import ascpy
1520    
1521     try:
1522     import cunit
1523     except:
1524     pass
1525    
1526 johnpye 966 atexit.register(ascpy.shutdown)
1527 johnpye 1008 #suite = unittest.TestSuite()
1528 johnpye 1003 #suite = unittest.defaultTestLoader.loadTestsFromName('__main__')
1529 johnpye 1008 #unittest.TextTestRunner(verbosity=2).run(suite)
1530     unittest.main()

Properties

Name Value
svn:executable *

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