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

Contents of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

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