/[escript]/trunk/pycad/py_src/design.py
ViewVC logotype

Contents of /trunk/pycad/py_src/design.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2560 - (show annotations)
Mon Jul 27 07:38:00 2009 UTC (10 years, 1 month ago) by gross
File MIME type: text/x-python
File size: 10826 byte(s)
a test for unique PropertySet name added.
1
2 ########################################################
3 #
4 # Copyright (c) 2003-2009 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-2009 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 """
23 Template for the Design which defines regions and features
24 for a mesh generator.
25
26 @var __author__: name of author
27 @var __copyright__: copyrights
28 @var __license__: licence agreement
29 @var __url__: url entry point on documentation
30 @var __version__: version
31 @var __date__: date of the version
32 """
33
34 __author__="Lutz Gross, l.gross@uq.edu.au"
35
36 from primitives import Primitive, ReversePrimitive, PropertySet, Point, Manifold1D, Manifold2D, Manifold3D
37 from xml.dom import minidom
38
39 class TagMap(object):
40 """
41 A class that allows to map tags to names.
42
43 Example::
44
45 tm=TagMap({5 : x })
46 tm.setMap(a=1,x=4)
47 assert tm.getTags("a") == [ 1 ]
48 assert tm.getTags("x") == [ 5, 4 ]
49 assert tm.map(x=10., a=20.) == { 5 : 10, 4: 10, 1 : 20 }
50
51 """
52 def __init__(self, mapping={}):
53 """
54 Initializes the mapping. C{mapping} defines an initial mapping from tag
55 to a name.
56 """
57 self.__mapping={}
58 for tag, name in mapping.items():
59 if not isinstance(tag, int):
60 raise TypeError("tag needs to be an int")
61 if not isinstance(name, str):
62 raise TypeError("name needs to be a str.")
63 self.__mapping[tag]=name
64
65 def setMap(self,**kwargs):
66 """
67 Sets a new map where <name>=<tag> assigns the tag <tag> to name <name>.
68 <tag> has to be an integer. If <tag> has been assigned to a name before
69 the mapping will be overwritten. Otherwise a new mapping <tag> -> <name>
70 is set. Notice that a single name can be assigned to different tags.
71 """
72 for name, tag in kwargs.items():
73 if not isinstance(tag, int):
74 raise TypeError("tag needs to be an int")
75 self.__mapping[tag]=name
76
77 def getTags(self,name=None):
78 """
79 Returns a list of the tags assigned to C{name}. If name is not present
80 a list of all tags is returned.
81 """
82 if name == None:
83 out=self.__mapping.keys()
84 else:
85 out=[]
86 for tag, arg in self.__mapping.items():
87 if arg == name: out.append(tag)
88 return out
89
90 def getName(self,tag=None):
91 """
92 Returns the name of a tag. If C{tag} is not present a list of all names
93 is returned.
94 """
95 if tag == None:
96 return list(set(self.__mapping.values()))
97 else:
98 return self.__mapping[tag]
99
100 def getMapping(self):
101 """
102 Returns a dictionary where the tags define the keys and the values the
103 corresponding names.
104 """
105 return self.__mapping
106
107 def map(self,default=0,**kwargs):
108 """
109 Returns a dictionary where the tags define the keys and the values give
110 the values assigned to the tag via name and kwargs::
111
112 tm=TagMap(x=5)
113 tm.setMap(a=1,x=4)
114 print tm.map(x=10., a=20.)
115 { 5 : 10, 4: 10, 1 : 20 }
116
117 The default is used for tags which map onto name with unspecified
118 values.
119 """
120 out={}
121 for tag in self.__mapping:
122 if kwargs.has_key(self.__mapping[tag]):
123 out[tag]=kwargs[self.__mapping[tag]]
124 else:
125 out[tag]=default
126 return out
127
128 def insert(self,data,default=0,**kwargs):
129 """
130 Inserts values into the L{esys.escript.Data} object according to the
131 given values assigned to the keywords. The default is used for tags
132 which map onto name with unspecified values.
133 """
134 d=self.map(default=default,**kwargs)
135 for t,v in d.items():
136 data.setTaggedValue(t,v)
137
138 def passToDomain(self,domain):
139 """
140 Passes the tag map to the L{esys.escript.Domain} C{domain}.
141 """
142 for tag, name in self.__mapping.items():
143 print name, ">>", tag
144 domain.setTagMap(name,tag)
145
146 def toDOM(self,dom):
147 """
148 Adds object to C{dom}.
149 """
150 tm=dom.createElement("TagMap")
151 dom.appendChild(tm)
152 for tag,name in self.getMapping().items():
153 item_dom=dom.createElement("map")
154 tag_dom=dom.createElement("tag")
155 name_dom=dom.createElement("name")
156 tag_dom.appendChild(dom.createTextNode(str(tag)))
157 name_dom.appendChild(dom.createTextNode(str(name)))
158 item_dom.appendChild(tag_dom)
159 item_dom.appendChild(name_dom)
160 tm.appendChild(item_dom)
161 return tm
162
163 def fromDom(self,node):
164 """
165 Fills names and tags from dom C{node}.
166 """
167 for node in node.childNodes:
168 if isinstance(node, minidom.Element):
169 if node.tagName == 'map':
170 tag=int(node.getElementsByTagName("tag")[0].firstChild.nodeValue.strip())
171 name=str(node.getElementsByTagName("name")[0].firstChild.nodeValue.strip())
172 self.setMap(**{ name : tag })
173 return
174
175 def fillFromXML(self,iostream):
176 """
177 Uses the XML file or string to set the mapping.
178 """
179 if isinstance(iostream,str):
180 dom=minidom.parseString(iostream)
181 else:
182 dom=minidom.parse(iostream)
183 root=dom.getElementsByTagName('ESys')[0]
184 for node in root.childNodes:
185 if isinstance(node, minidom.Element):
186 if node.tagName == 'TagMap':
187 self.fromDom(node)
188 return
189
190 def writeXML(self,iostream=None):
191 """
192 Serializes self as XML into C{iostream} or if not present returns the
193 XML as string.
194 """
195 dom=minidom.Document()
196 esys=dom.createElement('ESys')
197 esys.appendChild(self.toDOM(dom))
198 dom.appendChild(esys)
199 if iostream == None:
200 return dom.toprettyxml()
201 else:
202 iostream.write(dom.toprettyxml())
203
204 class Design(object):
205 """
206 Template for a design which defines the input for a mesh generator.
207 """
208 def __init__(self,dim=3,element_size=1.,order=1,keep_files=False):
209 """
210 Initializes a design.
211
212 @param dim: spatial dimension
213 @param element_size: global element size
214 @param order: element order
215 @param keep_files: flag to keep work files
216 """
217 self.clearItems()
218 self.setElementSize(element_size)
219 self.setDim(dim)
220 self.setElementOrder(order)
221 if keep_files:
222 self.setKeepFilesOn()
223 else:
224 self.setKeepFilesOff()
225
226 def setDim(self,dim=3):
227 """
228 Sets the spatial dimension.
229 """
230 if not dim in [1,2,3]:
231 raise ValueError("only dimension 1, 2, 3 are supported.")
232 self.__dim=dim
233
234 def getDim(self,dim=3):
235 """
236 Returns the spatial dimension.
237 """
238 return self.__dim
239
240 def setElementOrder(self,order=1):
241 """
242 Sets the element order.
243 """
244 if not order in [1,2]:
245 raise ValueError("only element order 1 or 2 is supported.")
246 self.__order=order
247
248 def getElementOrder(self):
249 """
250 Returns the element order.
251 """
252 return self.__order
253
254 def setElementSize(self,element_size=1.):
255 """
256 Sets the global element size.
257 """
258 if element_size<=0.:
259 raise ValueError("element size needs to be positive.")
260 self.__element_size=element_size
261
262 def getElementSize(self):
263 """
264 Returns the global element size.
265 """
266 return self.__element_size
267
268 def setKeepFilesOn(self):
269 """
270 Work files are kept at the end of the generation.
271 """
272 self.__keep_files=True
273
274 def setKeepFilesOff(self):
275 """
276 Work files are deleted at the end of the generation
277 """
278 self.__keep_files=False
279
280 def keepFiles(self):
281 """
282 Returns True if work files are kept, False otherwise.
283 """
284 return self.__keep_files
285
286 def addItems(self,*items):
287 """
288 Adds items to the design.
289 """
290 for i in range(len(items)):
291 if not isinstance(items[i],(Primitive, ReversePrimitive)):
292 raise TypeError("%s-th argument is not a Primitive object"%i)
293 if isinstance(items[i],PropertySet):
294 for p in self.getAllPrimitives():
295 if isinstance(p, PropertySet):
296 if items[i].getName() == p.getName():
297 raise ValueError("Property set name %s is allready in use."%items[i].getName())
298 for i in items:
299 self.__items.append(i)
300
301 def getItems(self):
302 """
303 Returns a list of the items used in the design.
304 """
305 return self.__items
306
307 def clearItems(self):
308 """
309 Removes all items from the design.
310 """
311 self.__items=[]
312
313 def getAllPrimitives(self):
314 """
315 Returns a list of all primitives used to create the design.
316 Each primitive appears once. The primitives are ordered by their
317 order of generation.
318 """
319 prims=[]
320 for i in self.getItems():
321 for p in i.getPrimitives():
322 if not p in prims: prims.append(p)
323 prims.sort()
324 return prims
325
326 def setOptions(self,**kwargs):
327 """
328 Sets options of the mesh generator.
329
330 @note: this method is typically overwritten by a particular design
331 implementation.
332 """
333 pass
334
335 def getMeshHandler(self):
336 """
337 Returns a handle to a mesh meshing the design.
338
339 @note: this method has to be overwritten by a particular design
340 implementation.
341 """
342 raise NotImplementedError()
343
344 def getTagMap(self):
345 """
346 Returns a L{TagMap} to map the names of L{PropertySet}s to tags.
347 """
348 m={}
349 for p in self.getAllPrimitives():
350 if isinstance(p, PropertySet): m[ p.getTag() ] = p.getName()
351 return TagMap(m)
352

  ViewVC Help
Powered by ViewVC 1.1.26