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

Contents of /trunk/test.py

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

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