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

Contents of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

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