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

Contents of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

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