/[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 2720 - (show annotations)
Wed Oct 14 23:43:21 2009 UTC (10 years, 11 months ago) by gross
File MIME type: text/x-python
File size: 13193 byte(s)
missing modules 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 import tempfile, os
39
40 class TagMap(object):
41 """
42 A class that allows to map tags to names.
43
44 Example::
45
46 tm=TagMap({5 : x })
47 tm.setMap(a=1,x=4)
48 assert tm.getTags("a") == [ 1 ]
49 assert tm.getTags("x") == [ 5, 4 ]
50 assert tm.map(x=10., a=20.) == { 5 : 10, 4: 10, 1 : 20 }
51
52 """
53 def __init__(self, mapping={}):
54 """
55 Initializes the mapping. ``mapping`` defines an initial mapping from tag
56 to a name.
57 """
58 self.__mapping={}
59 for tag, name in mapping.items():
60 if not isinstance(tag, int):
61 raise TypeError("tag needs to be an int")
62 if not isinstance(name, str):
63 raise TypeError("name needs to be a str.")
64 self.__mapping[tag]=name
65
66 def setMap(self,**kwargs):
67 """
68 Sets a new map where <name>=<tag> assigns the tag <tag> to name <name>.
69 <tag> has to be an integer. If <tag> has been assigned to a name before
70 the mapping will be overwritten. Otherwise a new mapping <tag> -> <name>
71 is set. Notice that a single name can be assigned to different tags.
72 """
73 for name, tag in kwargs.items():
74 if not isinstance(tag, int):
75 raise TypeError("tag needs to be an int")
76 self.__mapping[tag]=name
77
78 def getTags(self,name=None):
79 """
80 Returns a list of the tags assigned to ``name``. If name is not present
81 a list of all tags is returned.
82 """
83 if name == None:
84 out=self.__mapping.keys()
85 else:
86 out=[]
87 for tag, arg in self.__mapping.items():
88 if arg == name: out.append(tag)
89 return out
90
91 def getName(self,tag=None):
92 """
93 Returns the name of a tag. If ``tag`` is not present a list of all names
94 is returned.
95 """
96 if tag == None:
97 return list(set(self.__mapping.values()))
98 else:
99 return self.__mapping[tag]
100
101 def getMapping(self):
102 """
103 Returns a dictionary where the tags define the keys and the values the
104 corresponding names.
105 """
106 return self.__mapping
107
108 def map(self,default=0,**kwargs):
109 """
110 Returns a dictionary where the tags define the keys and the values give
111 the values assigned to the tag via name and kwargs::
112
113 tm=TagMap(x=5)
114 tm.setMap(a=1,x=4)
115 print tm.map(x=10., a=20.)
116 { 5 : 10, 4: 10, 1 : 20 }
117
118 The default is used for tags which map onto name with unspecified
119 values.
120 """
121 out={}
122 for tag in self.__mapping:
123 if kwargs.has_key(self.__mapping[tag]):
124 out[tag]=kwargs[self.__mapping[tag]]
125 else:
126 out[tag]=default
127 return out
128
129 def insert(self,data,default=0,**kwargs):
130 """
131 Inserts values into the `esys.escript.Data` object according to the
132 given values assigned to the keywords. The default is used for tags
133 which map onto name with unspecified values.
134 """
135 d=self.map(default=default,**kwargs)
136 for t,v in d.items():
137 data.setTaggedValue(t,v)
138
139 def passToDomain(self,domain):
140 """
141 Passes the tag map to the `esys.escript.Domain` ``domain``.
142 """
143 for tag, name in self.__mapping.items():
144 print "Tag",name, "is mapped to id ", tag
145 domain.setTagMap(name,tag)
146
147 def toDOM(self,dom):
148 """
149 Adds object to ``dom``.
150 """
151 tm=dom.createElement("TagMap")
152 dom.appendChild(tm)
153 for tag,name in self.getMapping().items():
154 item_dom=dom.createElement("map")
155 tag_dom=dom.createElement("tag")
156 name_dom=dom.createElement("name")
157 tag_dom.appendChild(dom.createTextNode(str(tag)))
158 name_dom.appendChild(dom.createTextNode(str(name)))
159 item_dom.appendChild(tag_dom)
160 item_dom.appendChild(name_dom)
161 tm.appendChild(item_dom)
162 return tm
163
164 def fromDom(self,node):
165 """
166 Fills names and tags from dom ``node``.
167 """
168 for node in node.childNodes:
169 if isinstance(node, minidom.Element):
170 if node.tagName == 'map':
171 tag=int(node.getElementsByTagName("tag")[0].firstChild.nodeValue.strip())
172 name=str(node.getElementsByTagName("name")[0].firstChild.nodeValue.strip())
173 self.setMap(**{ name : tag })
174 return
175
176 def fillFromXML(self,iostream):
177 """
178 Uses the XML file or string to set the mapping.
179 """
180 if isinstance(iostream,str):
181 dom=minidom.parseString(iostream)
182 else:
183 dom=minidom.parse(iostream)
184 root=dom.getElementsByTagName('ESys')[0]
185 for node in root.childNodes:
186 if isinstance(node, minidom.Element):
187 if node.tagName == 'TagMap':
188 self.fromDom(node)
189 return
190
191 def writeXML(self,iostream=None):
192 """
193 Serializes self as XML into ``iostream`` or if not present returns the
194 XML as string.
195 """
196 dom=minidom.Document()
197 esys=dom.createElement('ESys')
198 esys.appendChild(self.toDOM(dom))
199 dom.appendChild(esys)
200 if iostream == None:
201 return dom.toprettyxml()
202 else:
203 iostream.write(dom.toprettyxml())
204
205 class Design(object):
206 """
207 Template for a design which defines the input for a mesh generator.
208
209 :cvar GMSH: U{gmsh<http://www.geuz.org/gmsh/>} file formatt
210 :cvar IDEAS: U{I_DEAS<http://www.plm.automation.siemens.com/en_us/products/nx/>} universal file format
211 :cvar VRML: U{VRML<http://www.w3.org/MarkUp/VRML/>} file format
212 :cvar STL: U{STL<http://en.wikipedia.org/wiki/STL_(file_format)>} file format
213 :cvar NASTRAN: U{Nastran<http://simcompanion.mscsoftware.com/infocenter/index?page=content&channel=DOCUMENTATION>} bulk data format
214 :cvar MEDIT: U{Medit<http://www-rocq.inria.fr/OpenFEM/Doc/>} file format
215 :cvar CGNS: U{CGNS<http://cgns.sourceforge.net/>} file format
216 :cvar PLOT3D: U{Plot3D<http://www.plot3d.net/>} file format
217 :cvar DIFFPACK: U{Diffpack<http://www.diffpack.com/>} file format
218 """
219 GMSH="msh"
220 IDEAS="unv"
221 VRML="vrml"
222 STL="stl"
223 NASTRAN="bdf"
224 MEDIT="mesh"
225 CGNS="cgns"
226 PLOT3D="p3d"
227 DIFFPACK="diff"
228 def __init__(self,dim=3,element_size=1.,order=1,keep_files=False):
229 """
230 Initializes a design.
231
232 :param dim: spatial dimension
233 :param element_size: global element size
234 :param order: element order
235 :param keep_files: flag to keep work files
236 """
237 self.clearItems()
238 self.setElementSize(element_size)
239 self.setDim(dim)
240 self.setElementOrder(order)
241 self.setFileFormat()
242 self.setMeshFileName()
243 if keep_files:
244 self.setKeepFilesOn()
245 else:
246 self.setKeepFilesOff()
247
248 def setDim(self,dim=3):
249 """
250 Sets the spatial dimension.
251 """
252 if not dim in [1,2,3]:
253 raise ValueError("only dimension 1, 2, 3 are supported.")
254 self.__dim=dim
255
256 def getDim(self,dim=3):
257 """
258 Returns the spatial dimension.
259 """
260 return self.__dim
261
262 def setElementOrder(self,order=1):
263 """
264 Sets the element order.
265 """
266 if not order in [1,2]:
267 raise ValueError("only element order 1 or 2 is supported.")
268 self.__order=order
269
270 def getElementOrder(self):
271 """
272 Returns the element order.
273 """
274 return self.__order
275
276 def setElementSize(self,element_size=1.):
277 """
278 Sets the global element size.
279 """
280 if element_size<=0.:
281 raise ValueError("element size needs to be positive.")
282 self.__element_size=element_size
283
284 def getElementSize(self):
285 """
286 Returns the global element size.
287 """
288 return self.__element_size
289
290 def setKeepFilesOn(self):
291 """
292 Work files are kept at the end of the generation.
293 """
294 self.__keep_files=True
295
296 def setKeepFilesOff(self):
297 """
298 Work files are deleted at the end of the generation
299 """
300 self.__keep_files=False
301
302 def keepFiles(self):
303 """
304 Returns True if work files are kept, False otherwise.
305 """
306 return self.__keep_files
307
308 def addItems(self,*items):
309 """
310 Adds items to the design.
311 """
312 new_items=[]
313 for i in range(len(items)):
314 if not isinstance(items[i],(Primitive, ReversePrimitive)):
315 raise TypeError("%s-th argument is not a Primitive object"%i)
316 if isinstance(items[i],PropertySet):
317 q=items[i]
318 else:
319 q=PropertySet("__%s__"%(items[i].getID()), items[i])
320 for p in self.getAllPrimitives():
321 if isinstance(p, PropertySet):
322 if q.getName() == p.getName():
323 raise ValueError("Property set name %s is allready in use."%q.getName())
324 new_items.append(q)
325 for q in new_items: self.__items.append(q)
326
327 def getItems(self):
328 """
329 Returns a list of the items used in the design.
330 """
331 return self.__items
332
333 def clearItems(self):
334 """
335 Removes all items from the design.
336 """
337 self.__items=[]
338
339 def getAllPrimitives(self):
340 """
341 Returns a list of all primitives used to create the design.
342 Each primitive appears once. The primitives are ordered by their
343 order of generation.
344 """
345 prims=[]
346 for i in self.getItems():
347 for p in i.getPrimitives():
348 if not p in prims: prims.append(p)
349 prims.sort()
350 return prims
351
352 def setOptions(self,**kwargs):
353 """
354 Sets options of the mesh generator.
355
356 :note: this method is typically overwritten by a particular design
357 implementation.
358 """
359 pass
360 def generate(self):
361 """
362 generate output file
363
364 :note: this method may be overwritten by a particular design
365 implementation.
366 """
367 self.getMeshHandler()
368
369 def getMeshHandler(self):
370 """
371 Returns a handle to a mesh meshing the design.
372
373 :note: this method has to be overwritten by a particular design
374 implementation.
375 """
376 raise NotImplementedError()
377
378 def getTagMap(self):
379 """
380 Returns a `TagMap` to map the names of `PropertySet` s to tags.
381 """
382 m={}
383 for p in self.getAllPrimitives():
384 if isinstance(p, PropertySet): m[ p.getTag() ] = p.getName()
385 return TagMap(m)
386
387 def setFileFormat(self,format='msh'):
388 """
389 Sets the file format to be used.
390
391 :param format: format to be used. needs to be one of
392
393 """
394 if not format in [ self.GMSH, self.IDEAS, self.VRML, self.STL, self.NASTRAN, self.MEDIT, self.CGNS, self.PLOT3D, self.DIFFPACK] :
395 raise ValueError,"unknown file format %s."%format
396 self.__fileformat=format
397
398 def getFileFormat(self):
399 """
400 Returns the file format
401 """
402 return self.__fileformat
403
404 def setMeshFileName(self, name=None):
405 """
406 Sets the name for the mesh file. If no name is given a name is generated.
407 """
408 if name == None:
409 tmp_f_id=tempfile.mkstemp(suffix="."+self.getFileFormat())
410 self.__mshname=tmp_f_id[1]
411 os.close(tmp_f_id[0])
412 else:
413 self.__mshname=name
414 self.setKeepFilesOn()
415
416 def getMeshFileName(self):
417 """
418 Returns the name of the mesh file.
419 """
420 return self.__mshname
421
422
423

  ViewVC Help
Powered by ViewVC 1.1.26