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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 4938 - (show annotations)
Wed May 14 01:13:23 2014 UTC (5 years, 3 months ago) by jfenwick
File MIME type: text/x-python
File size: 16550 byte(s)
Modify unit tests to read their classes from
esys.escriptcore.utestselect

Change the line in that file to switch between unittest and unittest2


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