/[escript]/trunk/escript/test/python/run_xml.py
ViewVC logotype

Contents of /trunk/escript/test/python/run_xml.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2471 - (show annotations)
Thu Jun 11 23:33:06 2009 UTC (11 years ago) by jfenwick
File MIME type: text/x-python
File size: 16373 byte(s)
Fixed extract of ndarray from xml to properly return booleans.
Modified some strings which had numarray:: in them
1
2 ########################################################
3 #
4 # Copyright (c) 2003-2008 by University of Queensland
5 # Earth Systems Science Computational Center (ESSCC)
6 # http://www.uq.edu.au/esscc
7 #
8 # Primary Business: Queensland, Australia
9 # Licensed under the Open Software License version 3.0
10 # http://www.opensource.org/licenses/osl-3.0.php
11 #
12 ########################################################
13
14 __copyright__="""Copyright (c) 2003-2008 by University of Queensland
15 Earth Systems Science Computational Center (ESSCC)
16 http://www.uq.edu.au/esscc
17 Primary Business: Queensland, Australia"""
18 __license__="""Licensed under the Open Software License version 3.0
19 http://www.opensource.org/licenses/osl-3.0.php"""
20 __url__="https://launchpad.net/escript-finley"
21
22 import unittest
23 from esys.escript.modelframe import Model,Link,Simulation,ParameterSet,ESySXMLParser,DataSource
24 import math
25 from cStringIO import StringIO
26 from xml.dom import minidom
27 import numpy
28 import sys
29
30 class XMLDocumentTestCase(unittest.TestCase):
31
32 def setUp(self):
33
34 o1=ODETEST(debug=False)
35 o1.u=10
36 o2=ODETEST(debug=False)
37 o2.u=-10.
38 o1.f=Link(o2,"u")
39 o2.f=Link(o1,"u")
40 m=Messenger()
41 o1.dt=0.01
42 m.message=Link(o1)
43 s=Simulation([o1,o2,m],debug=False)
44 s.run()
45 output = StringIO()
46 s.writeXML(output)
47 output.reset()
48 outputList = output.readlines()
49 self.xmlList = outputList
50
51 def testFirstLine(self):
52 firstLine = self.xmlList[0]
53 self.assertEqual('<?xml version="1.0" ?>\n', firstLine)
54
55 def testEsysHeader(self):
56 header = self.xmlList[1]
57 self.assertEqual('<ESys>\n', header)
58
59 def testEsysFooter(self):
60 footer = self.xmlList[-1]
61 self.assertEqual('</ESys>\n', footer)
62
63 def testSimulationHeader(self):
64 pass
65
66 def testSimulationFooter(self):
67 pass
68
69 class SimulationTestCase(unittest.TestCase):
70 def setUp(self):
71 o1=ODETEST(debug=False)
72 o1.u=10
73 o2=ODETEST(debug=False)
74 o2.u=-10.
75 o1.f=Link(o2,"u")
76 o2.f=Link(o1,"u")
77 m=Messenger()
78 o1.dt=0.01
79 m.message=Link(o1)
80 self.s=Simulation([o1,o2,m],debug=False)
81 self.s.run()
82 output = StringIO()
83 self.s.writeXML(output)
84 output.reset()
85 self.xml = output.read()
86
87 def testSimulation(self):
88 assert "<Simulation" in self.xml, "I should see a Simulation"
89
90 def testParseAndInstanceOfSimulation(self):
91
92 xml = ESySXMLParser(self.xml)
93 newSim = xml.parse()[0]
94 assert isinstance(newSim, Simulation)
95 newout = StringIO()
96 newSim.writeXML(newout)
97 newout.reset()
98 xml = newout.read()
99 assert '<Simulation' in xml, "Missing a Simulation! It should be in this!"
100
101
102
103
104 class LinkTestCase(unittest.TestCase):
105
106
107 def setUp(self):
108
109 self.o1=ODETEST(debug=False)
110 #self.o1.u=10
111 self.o2=ODETEST(debug=False)
112 self.o2.u=-10.
113 self.o1.f=Link(self.o2,"u")
114 self.o2.f=Link(self.o1,"u")
115 self.o2.declareParameter(child=self.o1)
116
117 def testLinkCreation(self):
118 self.o1.f=Link(self.o2,"u")
119 assert self.o1.f
120
121
122 def testLinkValue(self):
123 self.assertEqual(self.o1.f, -10)
124
125 def testLinkTarget(self):
126 pass
127
128 def testLinkDefaultAttribute(self):
129 Link(self.o2)
130
131 def testLinkXML(self):
132 s = StringIO()
133 self.o2.writeXML(s)
134 s.reset()
135 xmlout = s.read()
136 assert '<Link' in xmlout
137
138 def testLinkTargetXML(self):
139 pass
140
141 class ParamaterSetTestCase(unittest.TestCase):
142
143
144 def setUp(self):
145 self.p = ParameterSet()
146 self.p.declareParameter(gamma1=1.,gamma2=2.,gamma3=3.)
147
148 def testParameterSetCreation(self):
149 self.assertEqual(self.p.gamma1, 1.)
150
151 def testParameterSetXMLCreation(self):
152 s = StringIO()
153 self.p.writeXML(s)
154 s.reset()
155 xmlout = s.read()
156 assert ("gamma1" in xmlout)
157 assert ("gamma2" in xmlout)
158 assert ("gamma3" in xmlout)
159 esysxml=ESySXMLParser(xmlout)
160 parsable = esysxml.parse()[0]
161 assert (isinstance (parsable, ParameterSet))
162 assert (self._dom(self.p).getElementsByTagName("ParameterSet"))
163
164 def testParameterSetFromXML(self):
165 s = StringIO()
166 self.p.writeXML(s)
167 s.reset()
168 xmlout = s.read()
169 esysxml=ESySXMLParser(xmlout)
170 doc = self._class(self.p)
171 pset = ParameterSet.fromDom(esysxml, self._dom(self.p).getElementsByTagName("ParameterSet")[0])
172 assert (isinstance(pset, ParameterSet))
173 assert (isinstance(doc, ParameterSet))
174 self.assertEqual(self.p.gamma1,doc.gamma1)
175
176
177 def testParameterSetWithChildrenFromXML(self):
178 p2 = ParameterSet()
179 p2.declareParameter(s="abc", f=3.)
180 self.p.declareParameter(child=p2)
181 doc = self._class(self.p)
182 #pset = ParameterSet.fromDom(doc.getElementsByTagName("ParameterSet")[0])
183 self.assertEqual(self.p.child.f, doc.child.f)
184
185 def testParameterSetChild(self):
186 p2 = ParameterSet()
187 p2.declareParameter(s="abc", f=3.)
188 self.p.declareParameter(child=p2)
189 self.assertEqual(self.p.child.s, "abc")
190 self.assertEqual(self.p.child.f, 3.)
191
192 def _dom(self, input):
193 s = StringIO()
194 input.writeXML(s)
195 s.reset()
196 xmlout = s.read()
197 doc = minidom.parseString(xmlout)
198 return doc
199
200 def _class(self, input):
201 s = StringIO()
202 input.writeXML(s)
203 s.reset()
204 xmlout = s.read()
205 esysxml=ESySXMLParser(xmlout)
206 doc =esysxml.parse()[0]
207 return doc
208
209 def testFromDomInt(self):
210 p3 = ParameterSet()
211 p3.declareParameter(inttest=1)
212 doc = self._class(p3)
213 assert type(doc.inttest)==int
214
215 def testFromDomNumarrayVector(self):
216 p3 = ParameterSet()
217 mynumpy = numpy.array([3., 4., 5.], dtype=numpy.float64)
218 p3.declareParameter(numtest=mynumpy)
219 doc = self._class(p3)
220 assert doc.numtest.dtype == numpy.float64
221 assert type(doc.numtest) == numpy.ndarray
222
223 def testFromDomNumarrayMulti(self):
224 p3 = ParameterSet()
225 mynumpy = numpy.array([[1., 2., 3.], [3., 4., 5.]], dtype=numpy.float64)
226 p3.declareParameter(numtest=mynumpy)
227 doc = self._class(p3)
228 assert doc.numtest.dtype == numpy.float64
229 assert type(doc.numtest) == numpy.ndarray
230
231 def testBoolLists(self):
232 p4 = ParameterSet()
233 mylist = [True, False, False, True]
234 p4.declareParameter(listest=mylist)
235 doc = self._class(p4)
236 assert type(doc.listest) == numpy.ndarray
237 assert doc.listest.dtype == numpy.bool_
238 assert len(doc.listest) == len(mylist)
239 assert min([ mylist[i] == doc.listest[i] for i in range(len( doc.listest)) ])
240
241 def testIntLists(self):
242 p4 = ParameterSet()
243 mylist = [1,2,4]
244 p4.declareParameter(listest=mylist)
245 doc = self._class(p4)
246 assert type(doc.listest) == numpy.ndarray
247 assert doc.listest.dtype == numpy.int_
248 assert len(doc.listest) == len(mylist)
249 assert min([ mylist[i] == doc.listest[i] for i in range(len( doc.listest)) ])
250
251 def testFloatLists(self):
252 p4 = ParameterSet()
253 mylist = [1.,2.,4.]
254 p4.declareParameter(listest=mylist)
255 doc = self._class(p4)
256 assert type(doc.listest) == numpy.ndarray
257 assert doc.listest.dtype == numpy.float_
258 assert len(doc.listest) == len(mylist)
259 assert min([ mylist[i] == doc.listest[i] for i in range(len( doc.listest)) ])
260
261 def testStringLists(self):
262 p4 = ParameterSet()
263 mylist = ["a", "b", "c"]
264 p4.declareParameter(listest=mylist)
265 doc = self._class(p4)
266 assert type(doc.listest) == list
267 assert len(doc.listest) == len(mylist)
268 assert min([ mylist[i] == doc.listest[i] for i in range(len( doc.listest)) ])
269
270 def testDatasource(self):
271 p5 = ParameterSet()
272 myURI = DataSource("somelocalfile.txt", "text")
273 p5.declareParameter(uritest=myURI)
274 doc = self._class(p5)
275 self.assertEquals(myURI.uri, doc.uritest.uri)
276 self.assertEquals(myURI.fileformat, doc.uritest.fileformat)
277 assert type(doc.uritest) == DataSource
278
279
280
281 class ModeltoDomTestCase(unittest.TestCase):
282
283 def _class(self):
284 # returns a modelframe class, generated from the xml
285 s = StringIO()
286 self.o1.writeXML(s)
287 s.reset()
288 self.xmlout = s.read()
289 esysxml=ESySXMLParser(xmlout)
290 doc =esysxml.parse()[0]
291 return doc
292
293 def _dom(self):
294 # returns a minidom dom element, generated from the xml
295 s = StringIO()
296 self.o1.writeXML(s)
297 s.reset()
298 self.xmlout = s.read()
299 doc = minidom.parseString(self.xmlout)
300 return doc
301
302 def setUp(self):
303 self.o1=ODETEST(debug=False)
304 self.o1.message='blah'
305
306 def testModelExists(self):
307 modeldoc = self._class()
308 assert isinstance(modeldoc, Model)
309 assert self._dom().getElementsByTagName("Model")
310
311 def testModelhasID(self):
312 assert int(self._dom().getElementsByTagName("Model")[0].getAttribute("id"))>99
313
314 class ModeltoDomTestCase(unittest.TestCase):
315 def _xml(self, modulename, modelname):
316 # returns a modelframe class, generated from the xml
317 return '''<?xml version="1.0" ?>
318 <ESys> <Simulation type="Simulation"> <Component rank="0">
319
320 <Model id="127" module="%s" type="%s">
321
322 <Parameter type="float"> <Name> a </Name> <Value> 0.9 </Value> </Parameter>
323 <Parameter type="Link"> <Name> f </Name> <Value> <Link> <Target> 128 </Target>
324 <Attribute> u </Attribute> </Link> </Value> </Parameter> <Parameter
325 type="float"> <Name> tend </Name> <Value>
326 1.0 </Value> </Parameter> <Parameter type="int"> <Name> u </Name> <Value> 10
327 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name> <Value>
328 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt </Name>
329 <Value>
330 0.01 </Value> </Parameter> <Parameter type="str"> <Name> message </Name>
331 <Value> current error = 9.516258e-01 </Value> </Parameter> </Model>
332 </Component> <Component rank="1"> <Model id="128" type="ODETEST"> <Parameter
333 type="float"> <Name> a </Name> <Value>
334 0.9 </Value> </Parameter> <Parameter type="Link"> <Name> f </Name> <Value>
335 <Link> <Target> 127 </Target> <Attribute> u </Attribute> </Link> </Value>
336 </Parameter> <Parameter type="float"> <Name> tend </Name> <Value>
337 1.0 </Value> </Parameter> <Parameter type="float"> <Name> u </Name> <Value>
338 -10.0 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name>
339 <Value> 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt
340 </Name> <Value>
341 0.1 </Value> </Parameter> <Parameter type="str"> <Name> message </Name> <Value>
342 current error = 1.904837e+01 </Value> </Parameter> </Model> </Component>
343 <Component rank="2"> <Model id="129" type="Messenger"> <Parameter
344 type="Link"> <Name> message </Name> <Value> <Link> <Target> 127 </Target>
345 <Attribute> message </Attribute> </Link> </Value> </Parameter> </Model>
346 </Component> </Simulation> <Model id="150" type="ODETEST"> <Parameter
347 type="float"> <Name> a </Name> <Value>
348 0.9 </Value> </Parameter> <Parameter type="Link"> <Name> f </Name> <Value>
349 <Link> <Target> 127 </Target> <Attribute> u </Attribute> </Link> </Value>
350 </Parameter> <Parameter type="float"> <Name> tend </Name> <Value>
351 1.0 </Value> </Parameter> <Parameter type="float"> <Name> u </Name> <Value>
352 -10.0 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name>
353 <Value> 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt
354 </Name> <Value>
355 0.1 </Value> </Parameter> <Parameter type="str"> <Name> message </Name> <Value>
356 current error = 1.904837e+01 </Value> </Parameter> </Model> <Model id="130"
357 type="ODETEST"> <Parameter type="float"> <Name> a </Name> <Value>
358 0.9 </Value> </Parameter> <Parameter type="Link"> <Name> f </Name> <Value>
359 <Link> <Target> 128 </Target> <Attribute> u </Attribute> </Link> </Value>
360 </Parameter> <Parameter type="float"> <Name> tend </Name> <Value>
361 1.0 </Value> </Parameter> <Parameter type="int"> <Name> u </Name> <Value> 10
362 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name> <Value>
363 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt </Name>
364 <Value>
365 0.01 </Value> </Parameter> <Parameter type="str"> <Name> message </Name>
366 <Value> current error = 9.516258e-01 </Value> </Parameter> </Model> <Model
367 id="170" type="ODETEST"> <Parameter type="float"> <Name> a </Name> <Value>
368 0.9 </Value> </Parameter> <Parameter type="Link"> <Name> f </Name> <Value>
369 <Link> <Target> 128 </Target> <Attribute> u </Attribute> </Link> </Value>
370 </Parameter> <Parameter type="float"> <Name> tend </Name> <Value>
371 1.0 </Value> </Parameter> <Parameter type="int"> <Name> u </Name> <Value> 10
372 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name> <Value>
373 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt </Name>
374 <Value>
375 0.01 </Value> </Parameter> <Parameter type="str"> <Name> message </Name>
376 <Value> current error = 9.516258e-01 </Value> </Parameter> </Model> </ESys>
377 ''' % (modulename, modelname)
378
379 def testModuleAttribute(self):
380 esysxml=ESySXMLParser(self._xml('run_xml', 'ODETEST'))
381 modeldoc=esysxml.parse()[0]
382
383 def testModuleAttributeFails(self):
384 try:
385 esysxml=ESySXMLParser(self._xml('a', 'b'))
386 modeldoc=esysxml.parse()[0]
387 except ImportError:
388 return # correct
389
390 assert False, "This test should have resulted in an ImportError"
391
392 class Messenger(Model):
393 def __init__(self, *args, **kwargs):
394 Model.__init__(self, *args, **kwargs)
395 self.declareParameter(message="none")
396
397 def doInitialization(self):
398 self.__t=0
399 #print "I start talking now!"
400
401 def doStepPostprocessing(self,dt):
402 self.__t+=dt
403 #print "Message (time %e) : %s "%(self.__t,self.message)
404
405 def doFinalization(self):
406 #print "I have no more to say!"
407 pass
408
409
410
411 class ODETEST(Model):
412 """ implements a solver for the ODE
413
414 du/dt=a*u+f(t)
415
416 we use a implicit euler scheme :
417
418 u_n-u_{n-1}= dt*a u_n + st*f(t_n)
419
420 to get u_n we run an iterative process
421
422 u_{n.k}=u_{n-1}+dt*(a u_{n.i-1} + f(t_n))
423
424
425 input for this model are step size dt, end time tend and a value for
426 a, f and initial value for u. we need also a tolerance tol for a
427 stopping criterion.
428
429 """
430
431 def __init__(self, *args, **kwargs):
432 Model.__init__(self, *args, **kwargs)
433 self.declareParameter(tend=1.,dt=0.1,a=0.9,u=10.,f=0.,message="",tol=1.e-8)
434
435 def doInitialization(self):
436 self.__tn=0
437 self.__iter=0
438
439 def doStepPreprocessing(self,dt):
440 self.__iter=0
441 self.__u_last=self.u
442
443 def doStep(self,dt):
444 self.__iter+=1
445 self.__u_old=self.u
446 self.u=self.__u_last+dt*(self.a*self.__u_old+self.f)
447
448 def terminate(self):
449 if self.__iter<1:
450 return False
451 else:
452 return abs(self.__u_old-self.u)<self.tol*abs(self.u)
453
454 def doStepPostprocessing(self,dt):
455 self.__tn+=dt
456 self.message="current error = %e"%abs(self.u-10.*math.exp((self.a-1.)*self.__tn))
457
458 def getSafeTimeStepSize(self,dt):
459 return min(self.dt,1./(abs(self.a)+1.))
460
461 def finalize(self):
462 return self.__tn>=self.tend
463
464
465
466 if __name__ == "__main__":
467 suite = unittest.TestSuite()
468 suite.addTest(unittest.makeSuite(XMLDocumentTestCase))
469 suite.addTest(unittest.makeSuite(SimulationTestCase))
470 suite.addTest(unittest.makeSuite(LinkTestCase))
471 suite.addTest(unittest.makeSuite(ParamaterSetTestCase))
472 suite.addTest(unittest.makeSuite(ModeltoDomTestCase))
473 suite.addTest(unittest.makeSuite(ModeltoDomTestCase))
474 suite.addTest(unittest.makeSuite(Messenger))
475 suite.addTest(unittest.makeSuite(ODETEST))
476 s=unittest.TextTestRunner(verbosity=2).run(suite)
477 if not s.wasSuccessful(): sys.exit(1)

Properties

Name Value
svn:eol-style native
svn:keywords Author Date Id Revision

  ViewVC Help
Powered by ViewVC 1.1.26