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

Annotation of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

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