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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2179 by ksteube, Thu Sep 25 06:43:44 2008 UTC revision 2180 by caltinay, Thu Dec 18 00:30:25 2008 UTC
# Line 20  http://www.opensource.org/licenses/osl-3 Line 20  http://www.opensource.org/licenses/osl-3
20  __url__="http://www.uq.edu.au/esscc/escript-finley"  __url__="http://www.uq.edu.au/esscc/escript-finley"
21    
22  """  """
23  template for the Design which defines a regions and features  Template for the Design which defines regions and features
24  for a mesh generator.  for a mesh generator.
25    
26  @var __author__: name of author  @var __author__: name of author
# Line 38  from xml.dom import minidom Line 38  from xml.dom import minidom
38    
39  class TagMap(object):  class TagMap(object):
40      """      """
41      a class that allows to map tags to names      A class that allows to map tags to names.
42      
43      tm=TagMap({5 : x })      Example::
44      tm.setMap(a=1,x=4)  
45      assert tm.getTags("a") == [ 1 ]          tm=TagMap({5 : x })
46      assert tm.getTags("x") == [ 5, 4 ]          tm.setMap(a=1,x=4)
47      assert tm.map(x=10., a=20.) == { 5 : 10, 4: 10, 1 : 20 }          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={}):      def __init__(self, mapping={}):
53        """        """
54        initizlizes the mapping. map defines an initial mapping from tag to a name.        Initializes the mapping. C{mapping} defines an initial mapping from tag
55          to a name.
56        """        """
57        self.__mapping={}        self.__mapping={}
58        for tag, name in mapping.items():        for tag, name in mapping.items():
59            if not isinstance(tag, int):            if not isinstance(tag, int):
60                raise TypeError("tag needs to be int")                raise TypeError("tag needs to be an int")
61            if not isinstance(name, str):            if not isinstance(name, str):
62                raise TypeError("name needs to be a str.")                raise TypeError("name needs to be a str.")
63            self.__mapping[tag]=name            self.__mapping[tag]=name
64    
65      def setMap(self,**kwargs):      def setMap(self,**kwargs):
66        """        """
67        set a new map where <name>=<tag> assigns the tag <tag> to name <name>. <tag> has to be integer.        Sets a new map where <name>=<tag> assigns the tag <tag> to name <name>.
68        If <tag> has been assigned to a name before the mapping will be overwritten. Otherwise a new        <tag> has to be an integer. If <tag> has been assigned to a name before
69        mapping <tag> -> <name> is set. Notice that a single name can be assigned to different tags.        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():        for name, tag in kwargs.items():
73            if not isinstance(tag, int):            if not isinstance(tag, int):
74               raise TypeError("tag needs to be int")               raise TypeError("tag needs to be an int")
75            self.__mapping[tag]=name            self.__mapping[tag]=name
76    
77      def getTags(self,name=None):      def getTags(self,name=None):
78          """          """
79          returns a list of the tags assigned to name. If name is not present a list of tags is returned.          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:          if name == None:
83             out=self.__mapping.keys()             out=self.__mapping.keys()
# Line 79  class TagMap(object): Line 86  class TagMap(object):
86             for tag, arg in self.__mapping.items():             for tag, arg in self.__mapping.items():
87               if arg == name: out.append(tag)               if arg == name: out.append(tag)
88          return out          return out
89    
90      def getName(self,tag=None):      def getName(self,tag=None):
91          """          """
92          returns the name of a tag. If tag is not present a list of names is returned.          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:          if tag == None:
96             return list(set(self.__mapping.values()))             return list(set(self.__mapping.values()))
# Line 90  class TagMap(object): Line 99  class TagMap(object):
99    
100      def getMapping(self):      def getMapping(self):
101          """          """
102          returns a dictionary where the tags define the keys and the values the corresposnding names.          Returns a dictionary where the tags define the keys and the values the
103            corresponding names.
104          """          """
105          return self.__mapping          return self.__mapping
106    
107      def map(self,default=0,**kwargs):      def map(self,default=0,**kwargs):
108          """          """
109          returns a dictionary where the tags define the keys and the values give the values assigned to the tag via name          Returns a dictionary where the tags define the keys and the values give
110          and kwargs:          the values assigned to the tag via name and kwargs::
111    
112          tm=TagMap(x=5)              tm=TagMap(x=5)
113          tm.setMap(a=1,x=4)              tm.setMap(a=1,x=4)
114          print tm.map(x=10., a=20.)              print tm.map(x=10., a=20.)
115          { 5 : 10, 4: 10, 1 : 20 }              { 5 : 10, 4: 10, 1 : 20 }
116      
117          the default is used for tags which map onto name with unspecified values          The default is used for tags which map onto name with unspecified
118            values.
119          """          """
120          out={}          out={}
121          for tag in self.__mapping:          for tag in self.__mapping:
# Line 116  class TagMap(object): Line 127  class TagMap(object):
127    
128      def insert(self,data,default=0,**kwargs):      def insert(self,data,default=0,**kwargs):
129          """          """
130          inserts values into the L{esys.escript.Data} object according to the given values assigned to the keywords.          Inserts values into the L{esys.escript.Data} object according to the
131          the default is used for tags which map onto name with unspecified values          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)          d=self.map(default=default,**kwargs)
135          for t,v in d.items():          for t,v in d.items():
136               data.setTaggedValue(t,v)               data.setTaggedValue(t,v)
137    
138      def passToDomain(self,domain):      def passToDomain(self,domain):
139          """          """
140          passes the tag map to  L{esys.escript.Domain} domain.          Passes the tag map to the L{esys.escript.Domain} C{domain}.
141          """          """
142          for tag, name in self.__mapping.items():          for tag, name in self.__mapping.items():
143            domain.setTagMap(name,tag)            domain.setTagMap(name,tag)
144            
145      def toDOM(self,dom):      def toDOM(self,dom):
146           """           """
147           adds object to dom           Adds object to C{dom}.
148           """           """
149           tm=dom.createElement("TagMap")           tm=dom.createElement("TagMap")
150           dom.appendChild(tm)           dom.appendChild(tm)
# Line 145  class TagMap(object): Line 158  class TagMap(object):
158               item_dom.appendChild(name_dom)               item_dom.appendChild(name_dom)
159               tm.appendChild(item_dom)               tm.appendChild(item_dom)
160           return tm           return tm
161    
162      def fromDom(self,node):      def fromDom(self,node):
163          """          """
164          fills from dom node          Fills names and tags from dom C{node}.
165          """          """
166          for node in node.childNodes:          for node in node.childNodes:
167             if isinstance(node, minidom.Element):             if isinstance(node, minidom.Element):
# Line 159  class TagMap(object): Line 173  class TagMap(object):
173    
174      def fillFromXML(self,iostream):      def fillFromXML(self,iostream):
175         """         """
176         uses the xml file or string to set the mapping         Uses the XML file or string to set the mapping.
177         """         """
178         if isinstance(iostream,str):         if isinstance(iostream,str):
179               dom=minidom.parseString(iostream)               dom=minidom.parseString(iostream)
# Line 171  class TagMap(object): Line 185  class TagMap(object):
185                if node.tagName == 'TagMap':                if node.tagName == 'TagMap':
186                   self.fromDom(node)                   self.fromDom(node)
187                   return                   return
               
             
188    
189      def writeXML(self,iostream=None):      def writeXML(self,iostream=None):
190           """           """
191           writes XML serialization into the iostream or if not present returns the XML as string           Serializes self as XML into C{iostream} or if not present returns the
192             XML as string.
193           """           """
194           dom=minidom.Document()           dom=minidom.Document()
195           esys=dom.createElement('ESys')           esys=dom.createElement('ESys')
# Line 186  class TagMap(object): Line 199  class TagMap(object):
199              return dom.toprettyxml()              return dom.toprettyxml()
200           else:           else:
201              iostream.write(dom.toprettyxml())              iostream.write(dom.toprettyxml())
202            
203  class Design(object):  class Design(object):
204      """      """
205      template for a design which defines the input for a mesh generator      Template for a design which defines the input for a mesh generator.
206      """      """
207      def __init__(self,dim=3,element_size=1.,order=1,keep_files=False):      def __init__(self,dim=3,element_size=1.,order=1,keep_files=False):
208         """         """
209         initializes a design         Initializes a design.
210    
211         @param dim: patial dimension         @param dim: spatial dimension
212         @param element_size: global element size         @param element_size: global element size
213         @param order: element order         @param order: element order
214         @param keep_files: flag to keep work files.         @param keep_files: flag to keep work files
215         """         """
216         self.clearItems()         self.clearItems()
217         self.setElementSize(element_size)         self.setElementSize(element_size)
218         self.setDim(dim)         self.setDim(dim)
# Line 208  class Design(object): Line 221  class Design(object):
221            self.setKeepFilesOn()            self.setKeepFilesOn()
222         else:         else:
223            self.setKeepFilesOff()            self.setKeepFilesOff()
224    
225      def setDim(self,dim=3):      def setDim(self,dim=3):
226          """          """
227          sets the spatial dimension          Sets the spatial dimension.
228          """          """
229          if not dim  in [1,2,3]:          if not dim  in [1,2,3]:
230             raise ValueError("only dimension 1, 2, 3 are supported.")             raise ValueError("only dimension 1, 2, 3 are supported.")
231          self.__dim=dim          self.__dim=dim
232    
233      def getDim(self,dim=3):      def getDim(self,dim=3):
234          """          """
235          returns the spatial dimension          Returns the spatial dimension.
236          """          """
237          return self.__dim          return self.__dim
238    
239      def setElementOrder(self,order=1):      def setElementOrder(self,order=1):
240          """          """
241          sets the element order          Sets the element order.
242          """          """
243          if not order in [1,2]:          if not order in [1,2]:
244             raise ValueError("only element orser 1 or 2 is supported.")             raise ValueError("only element order 1 or 2 is supported.")
245          self.__order=order          self.__order=order
246            
247      def getElementOrder(self):      def getElementOrder(self):
248          """          """
249          returns the element order          Returns the element order.
250          """          """
251          return self.__order          return self.__order
252            
253      def setElementSize(self,element_size=1.):      def setElementSize(self,element_size=1.):
254          """          """
255          set the global element size.          Sets the global element size.
256          """          """
257          if element_size<=0.:          if element_size<=0.:
258             raise ValueError("element size needs to be positive.")             raise ValueError("element size needs to be positive.")
259          self.__element_size=element_size          self.__element_size=element_size
260            
261      def getElementSize(self):      def getElementSize(self):
262          """          """
263          returns the global element size.          Returns the global element size.
264          """          """
265          return self.__element_size          return self.__element_size
266            
267      def setKeepFilesOn(self):      def setKeepFilesOn(self):
268          """          """
269          work files are kept at the end of the generation          Work files are kept at the end of the generation.
270          """          """
271          self.__keep_files=True          self.__keep_files=True
272    
273      def setKeepFilesOff(self):      def setKeepFilesOff(self):
274          """          """
275          work files are deleted at the end of the generation          Work files are deleted at the end of the generation
276          """          """
277          self.__keep_files=False          self.__keep_files=False
278    
279      def keepFiles(self):      def keepFiles(self):
280          """          """
281          returns True if work files are kept          Returns True if work files are kept, False otherwise.
282          """          """
283          return self.__keep_files          return self.__keep_files
284    
285      def addItems(self,*items):      def addItems(self,*items):
286         """         """
287         adds items to the design         Adds items to the design.
288         """         """
289         for i in range(len(items)):         for i in range(len(items)):
290            if not isinstance(items[i],(Primitive, ReversePrimitive)):            if not isinstance(items[i],(Primitive, ReversePrimitive)):
291               raise TypeError("%s-th argument is not a Primitive object"%i)               raise TypeError("%s-th argument is not a Primitive object"%i)
292         for i in items:         for i in items:
293            self.__items.append(i)            self.__items.append(i)
294    
295      def getItems(self):      def getItems(self):
296          """          """
297          returns a list of the items used in the design          Returns a list of the items used in the design.
298          """          """
299          return self.__items          return self.__items
300    
301      def clearItems(self):      def clearItems(self):
302          """          """
303          resets the items in design          Removes all items from the design.
304          """          """
305          self.__items=[]          self.__items=[]
306    
307      def getAllPrimitives(self):      def getAllPrimitives(self):
308          """          """
309          returns a list of all primitives used to create the design.          Returns a list of all primitives used to create the design.
310          each primitve appears once. The primitives are ordered by their          Each primitive appears once. The primitives are ordered by their
311          order of generation          order of generation.
312          """          """
313          prims=[]          prims=[]
314          for i in self.getItems():          for i in self.getItems():
315              for p in i.getPrimitives():              for p in i.getPrimitives():
316                  if not p in prims: prims.append(p)                  if not p in prims: prims.append(p)
317          prims.sort()          prims.sort()
# Line 297  class Design(object): Line 319  class Design(object):
319    
320      def setOptions(self,**kwargs):      def setOptions(self,**kwargs):
321          """          """
322          sets options of the mesh generator          Sets options of the mesh generator.
323    
324          @note: this method is typically overwritten by a particular Design implementation          @note: this method is typically overwritten by a particular design
325                   implementation.
326          """          """
327          pass          pass
328    
329      def getMeshHandler(self):      def getMeshHandler(self):
330          """          """
331          returns a handle to a mesh meshing the design          Returns a handle to a mesh meshing the design.
332    
333          @note: this method has to be overwritten by a particular Design implementation          @note: this method has to be overwritten by a particular design
334                   implementation.
335          """          """
336          raise NotImplementedError()          raise NotImplementedError()
337    
338      def getTagMap(self):      def getTagMap(self):
339          """          """
340          returns a L{TagMap} to map the names of L{PropertySet}s to tags          Returns a L{TagMap} to map the names of L{PropertySet}s to tags.
341          """          """
342          m={}          m={}
343          for p in self.getAllPrimitives():          for p in self.getAllPrimitives():
344             if isinstance(p, PropertySet): m[ p.getTag() ] = p.getName()             if isinstance(p, PropertySet): m[ p.getTag() ] = p.getName()
345          return TagMap(m)          return TagMap(m)
346    

Legend:
Removed from v.2179  
changed lines
  Added in v.2180

  ViewVC Help
Powered by ViewVC 1.1.26