/[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 2468 - (show annotations)
Thu Jun 11 02:55:51 2009 UTC (10 years, 5 months ago) by gross
File MIME type: text/x-python
File size: 16526 byte(s)
some more work toward numpy
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 # This method is disabled until the correct behaviour for lists of bools is decided
232 #numarray converts them into ints whereas numpy leaves them as bools
233 def testBoolLists(self):
234 p4 = ParameterSet()
235 mylist = [True, False, False, True]
236 p4.declareParameter(listest=mylist)
237 doc = self._class(p4)
238 assert type(doc.listest) == numpy.ndarray
239 assert doc.listest.dtype == numpy.bool_
240 assert len(doc.listest) == len(mylist)
241 assert min([ mylist[i] == doc.listest[i] for i in range(len( doc.listest)) ])
242
243 def testIntLists(self):
244 p4 = ParameterSet()
245 mylist = [1,2,4]
246 p4.declareParameter(listest=mylist)
247 doc = self._class(p4)
248 assert type(doc.listest) == numpy.ndarray
249 assert doc.listest.dtype == numpy.int_
250 assert len(doc.listest) == len(mylist)
251 assert min([ mylist[i] == doc.listest[i] for i in range(len( doc.listest)) ])
252
253 def testFloatLists(self):
254 p4 = ParameterSet()
255 mylist = [1.,2.,4.]
256 p4.declareParameter(listest=mylist)
257 doc = self._class(p4)
258 assert type(doc.listest) == numpy.ndarray
259 assert doc.listest.dtype == numpy.float_
260 assert len(doc.listest) == len(mylist)
261 assert min([ mylist[i] == doc.listest[i] for i in range(len( doc.listest)) ])
262
263 def testStringLists(self):
264 p4 = ParameterSet()
265 mylist = ["a", "b", "c"]
266 p4.declareParameter(listest=mylist)
267 doc = self._class(p4)
268 assert type(doc.listest) == list
269 assert len(doc.listest) == len(mylist)
270 assert min([ mylist[i] == doc.listest[i] for i in range(len( doc.listest)) ])
271
272 def testDatasource(self):
273 p5 = ParameterSet()
274 myURI = DataSource("somelocalfile.txt", "text")
275 p5.declareParameter(uritest=myURI)
276 doc = self._class(p5)
277 self.assertEquals(myURI.uri, doc.uritest.uri)
278 self.assertEquals(myURI.fileformat, doc.uritest.fileformat)
279 assert type(doc.uritest) == DataSource
280
281
282
283 class ModeltoDomTestCase(unittest.TestCase):
284
285 def _class(self):
286 # returns a modelframe class, generated from the xml
287 s = StringIO()
288 self.o1.writeXML(s)
289 s.reset()
290 self.xmlout = s.read()
291 esysxml=ESySXMLParser(xmlout)
292 doc =esysxml.parse()[0]
293 return doc
294
295 def _dom(self):
296 # returns a minidom dom element, generated from the xml
297 s = StringIO()
298 self.o1.writeXML(s)
299 s.reset()
300 self.xmlout = s.read()
301 doc = minidom.parseString(self.xmlout)
302 return doc
303
304 def setUp(self):
305 self.o1=ODETEST(debug=False)
306 self.o1.message='blah'
307
308 def testModelExists(self):
309 modeldoc = self._class()
310 assert isinstance(modeldoc, Model)
311 assert self._dom().getElementsByTagName("Model")
312
313 def testModelhasID(self):
314 assert int(self._dom().getElementsByTagName("Model")[0].getAttribute("id"))>99
315
316 class ModeltoDomTestCase(unittest.TestCase):
317 def _xml(self, modulename, modelname):
318 # returns a modelframe class, generated from the xml
319 return '''<?xml version="1.0" ?>
320 <ESys> <Simulation type="Simulation"> <Component rank="0">
321
322 <Model id="127" module="%s" type="%s">
323
324 <Parameter type="float"> <Name> a </Name> <Value> 0.9 </Value> </Parameter>
325 <Parameter type="Link"> <Name> f </Name> <Value> <Link> <Target> 128 </Target>
326 <Attribute> u </Attribute> </Link> </Value> </Parameter> <Parameter
327 type="float"> <Name> tend </Name> <Value>
328 1.0 </Value> </Parameter> <Parameter type="int"> <Name> u </Name> <Value> 10
329 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name> <Value>
330 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt </Name>
331 <Value>
332 0.01 </Value> </Parameter> <Parameter type="str"> <Name> message </Name>
333 <Value> current error = 9.516258e-01 </Value> </Parameter> </Model>
334 </Component> <Component rank="1"> <Model id="128" type="ODETEST"> <Parameter
335 type="float"> <Name> a </Name> <Value>
336 0.9 </Value> </Parameter> <Parameter type="Link"> <Name> f </Name> <Value>
337 <Link> <Target> 127 </Target> <Attribute> u </Attribute> </Link> </Value>
338 </Parameter> <Parameter type="float"> <Name> tend </Name> <Value>
339 1.0 </Value> </Parameter> <Parameter type="float"> <Name> u </Name> <Value>
340 -10.0 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name>
341 <Value> 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt
342 </Name> <Value>
343 0.1 </Value> </Parameter> <Parameter type="str"> <Name> message </Name> <Value>
344 current error = 1.904837e+01 </Value> </Parameter> </Model> </Component>
345 <Component rank="2"> <Model id="129" type="Messenger"> <Parameter
346 type="Link"> <Name> message </Name> <Value> <Link> <Target> 127 </Target>
347 <Attribute> message </Attribute> </Link> </Value> </Parameter> </Model>
348 </Component> </Simulation> <Model id="150" type="ODETEST"> <Parameter
349 type="float"> <Name> a </Name> <Value>
350 0.9 </Value> </Parameter> <Parameter type="Link"> <Name> f </Name> <Value>
351 <Link> <Target> 127 </Target> <Attribute> u </Attribute> </Link> </Value>
352 </Parameter> <Parameter type="float"> <Name> tend </Name> <Value>
353 1.0 </Value> </Parameter> <Parameter type="float"> <Name> u </Name> <Value>
354 -10.0 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name>
355 <Value> 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt
356 </Name> <Value>
357 0.1 </Value> </Parameter> <Parameter type="str"> <Name> message </Name> <Value>
358 current error = 1.904837e+01 </Value> </Parameter> </Model> <Model id="130"
359 type="ODETEST"> <Parameter type="float"> <Name> a </Name> <Value>
360 0.9 </Value> </Parameter> <Parameter type="Link"> <Name> f </Name> <Value>
361 <Link> <Target> 128 </Target> <Attribute> u </Attribute> </Link> </Value>
362 </Parameter> <Parameter type="float"> <Name> tend </Name> <Value>
363 1.0 </Value> </Parameter> <Parameter type="int"> <Name> u </Name> <Value> 10
364 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name> <Value>
365 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt </Name>
366 <Value>
367 0.01 </Value> </Parameter> <Parameter type="str"> <Name> message </Name>
368 <Value> current error = 9.516258e-01 </Value> </Parameter> </Model> <Model
369 id="170" type="ODETEST"> <Parameter type="float"> <Name> a </Name> <Value>
370 0.9 </Value> </Parameter> <Parameter type="Link"> <Name> f </Name> <Value>
371 <Link> <Target> 128 </Target> <Attribute> u </Attribute> </Link> </Value>
372 </Parameter> <Parameter type="float"> <Name> tend </Name> <Value>
373 1.0 </Value> </Parameter> <Parameter type="int"> <Name> u </Name> <Value> 10
374 </Value> </Parameter> <Parameter type="float"> <Name> tol </Name> <Value>
375 1e-08 </Value> </Parameter> <Parameter type="float"> <Name> dt </Name>
376 <Value>
377 0.01 </Value> </Parameter> <Parameter type="str"> <Name> message </Name>
378 <Value> current error = 9.516258e-01 </Value> </Parameter> </Model> </ESys>
379 ''' % (modulename, modelname)
380
381 def testModuleAttribute(self):
382 esysxml=ESySXMLParser(self._xml('run_xml', 'ODETEST'))
383 modeldoc=esysxml.parse()[0]
384
385 def testModuleAttributeFails(self):
386 try:
387 esysxml=ESySXMLParser(self._xml('a', 'b'))
388 modeldoc=esysxml.parse()[0]
389 except ImportError:
390 return # correct
391
392 assert False, "This test should have resulted in an ImportError"
393
394 class Messenger(Model):
395 def __init__(self, *args, **kwargs):
396 Model.__init__(self, *args, **kwargs)
397 self.declareParameter(message="none")
398
399 def doInitialization(self):
400 self.__t=0
401 #print "I start talking now!"
402
403 def doStepPostprocessing(self,dt):
404 self.__t+=dt
405 #print "Message (time %e) : %s "%(self.__t,self.message)
406
407 def doFinalization(self):
408 #print "I have no more to say!"
409 pass
410
411
412
413 class ODETEST(Model):
414 """ implements a solver for the ODE
415
416 du/dt=a*u+f(t)
417
418 we use a implicit euler scheme :
419
420 u_n-u_{n-1}= dt*a u_n + st*f(t_n)
421
422 to get u_n we run an iterative process
423
424 u_{n.k}=u_{n-1}+dt*(a u_{n.i-1} + f(t_n))
425
426
427 input for this model are step size dt, end time tend and a value for
428 a, f and initial value for u. we need also a tolerance tol for a
429 stopping criterion.
430
431 """
432
433 def __init__(self, *args, **kwargs):
434 Model.__init__(self, *args, **kwargs)
435 self.declareParameter(tend=1.,dt=0.1,a=0.9,u=10.,f=0.,message="",tol=1.e-8)
436
437 def doInitialization(self):
438 self.__tn=0
439 self.__iter=0
440
441 def doStepPreprocessing(self,dt):
442 self.__iter=0
443 self.__u_last=self.u
444
445 def doStep(self,dt):
446 self.__iter+=1
447 self.__u_old=self.u
448 self.u=self.__u_last+dt*(self.a*self.__u_old+self.f)
449
450 def terminate(self):
451 if self.__iter<1:
452 return False
453 else:
454 return abs(self.__u_old-self.u)<self.tol*abs(self.u)
455
456 def doStepPostprocessing(self,dt):
457 self.__tn+=dt
458 self.message="current error = %e"%abs(self.u-10.*math.exp((self.a-1.)*self.__tn))
459
460 def getSafeTimeStepSize(self,dt):
461 return min(self.dt,1./(abs(self.a)+1.))
462
463 def finalize(self):
464 return self.__tn>=self.tend
465
466
467
468 if __name__ == "__main__":
469 suite = unittest.TestSuite()
470 suite.addTest(unittest.makeSuite(XMLDocumentTestCase))
471 suite.addTest(unittest.makeSuite(SimulationTestCase))
472 suite.addTest(unittest.makeSuite(LinkTestCase))
473 suite.addTest(unittest.makeSuite(ParamaterSetTestCase))
474 suite.addTest(unittest.makeSuite(ModeltoDomTestCase))
475 suite.addTest(unittest.makeSuite(ModeltoDomTestCase))
476 suite.addTest(unittest.makeSuite(Messenger))
477 suite.addTest(unittest.makeSuite(ODETEST))
478 s=unittest.TextTestRunner(verbosity=2).run(suite)
479 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