Package PyFoam :: Package Basics :: Module FoamFileGenerator
[hide private]
[frames] | no frames]

Source Code for Module PyFoam.Basics.FoamFileGenerator

  1  #  ICE Revision: $Id$ 
  2  """Transform a Python data-structure into a OpenFOAM-File-Representation""" 
  3   
  4  from PyFoam.Error import error,PyFoamException 
  5  from PyFoam.Basics.DataStructures import Vector,Field,Dimension,TupleProxy,DictProxy,Tensor,SymmTensor,Unparsed,UnparsedList,Codestream,DictRedirection,BinaryList 
  6   
  7  import string 
  8   
  9  from PyFoam.ThirdParty.six import string_types,integer_types 
 10   
11 -class FoamFileGenerator(object):
12 """Class that generates a OpenFOAM-compatible representation of a 13 data-structure""" 14 15 primitiveTypes=[SymmTensor,Tensor,Vector,Dimension,Field,Unparsed] 16
17 - def __init__(self, 18 data, 19 header=None, 20 longListThreshold=20):
21 """@param data: data structure that will be turned into a 22 Foam-compatible file 23 @param header: header information that is to be prepended 24 @param longListThreshold: Threshold for lists before they are considered 25 long. This means that they are prefixed with the number of elements. If the 26 threshold is 0 or None then no list is considered long 27 """ 28 29 self.data=data 30 self.header=header 31 self.longListThreshold=longListThreshold
32
33 - def __str__(self):
34 return self.makeString()
35
36 - def makeString(self,firstLevel=False):
37 """turns the data into a string""" 38 result="" 39 if self.header: 40 result+="FoamFile\n{\n"+self.strDict(self.header,indent=1)+"}\n\n" 41 42 if type(self.data) in [dict,DictProxy]: 43 result+=self.strDict(self.data,firstLevel=firstLevel) 44 elif type(self.data) in [tuple,TupleProxy]: 45 result+=self.strTuple(self.data) 46 elif type(self.data) in [list,UnparsedList,BinaryList]: 47 result+=self.strList(self.data) 48 elif self.data==None: 49 raise FoamFileGeneratorError("<None> found") 50 else: 51 result+=self.strPrimitive(self.data) 52 53 return result
54
55 - def strPrimitive(self,pri):
56 if type(pri)==bool: 57 if pri: 58 return "yes" 59 else: 60 return "no" 61 elif isinstance(pri,integer_types+(float,)+string_types): 62 return str(pri) 63 elif pri.__class__ in self.primitiveTypes: 64 return str(pri) 65 elif type(pri)==DictRedirection: 66 return str(pri()) 67 else: 68 error("List, Dict or valid primitve expected,",type(pri),"found in",pri)
69
70 - def strDict(self,dic,indent=0,firstLevel=False):
71 s="" 72 if type(dic)==DictProxy: 73 order=dic._order 74 else: 75 order=list(dic.keys()) 76 order.sort() 77 78 for k in order: 79 if type(k)==DictRedirection: 80 v=k 81 else: 82 try: 83 v=dic[k] 84 except KeyError: 85 v=dic.getRegexpValue(k) 86 87 end="\n" 88 if type(dic)==DictProxy: 89 end=dic.getDecoration(k)+"\n" 90 91 if firstLevel: 92 end+="\n" 93 94 # remove trailing spaces 95 end="\n".join([part.rstrip() for part in end.split("\n")]) 96 97 if type(k)==int: 98 s+=v 99 continue 100 101 if str(k).find("anonymValue")==0: 102 k="" 103 104 s+=(" "*indent)+str(k) 105 if isinstance(v,string_types): 106 if type(v)==Codestream: 107 s+="\n" 108 s+=" "*indent 109 s+=str(v) 110 s+=";"+end 111 else: 112 s+=" "+v+";"+end 113 elif type(v) in [dict,DictProxy]: 114 s+="\n"+(" "*indent)+"{\n" 115 s+=self.strDict(v,indent+2) 116 s+=(" "*indent)+"}"+end 117 elif type(v) in [list,UnparsedList]: 118 s+="\n" 119 s+=self.strList(v,indent+2) 120 if s[-1]=="\n": 121 s=s[:-1] 122 s+=";"+end 123 elif type(v) in [tuple,TupleProxy]: 124 s+=" "+self.strTuple(v,indent+2)+";"+end 125 elif type(v)==bool: 126 if v: 127 s+=" yes;\n" 128 else: 129 s+=" no;\n" 130 elif isinstance(v,integer_types+(float,)): 131 s+=" "+str(v)+";"+end 132 elif v.__class__ in self.primitiveTypes: 133 s+=" "+str(v)+";"+end 134 elif v==None: 135 s+=" /* empty */ ;"+end 136 elif type(v)==DictRedirection: 137 s+=";"+end 138 else: 139 error("Unhandled type",type(v)," for",v) 140 return s
141
142 - def strList(self,lst,indent=0):
143 s="" 144 145 if type(lst)==UnparsedList: 146 s+=(" "*indent)+str(len(lst))+" (" 147 s+=lst.data 148 if lst.data[-1]!="\n": 149 s+="\n" 150 s+=(" "*indent)+")\n" 151 return s 152 elif type(lst)==BinaryList: 153 s+=(" "*indent)+str(len(lst))+" (" 154 s+=lst.data 155 s+=")" 156 return s 157 158 theLen=len(lst) 159 160 if len(lst)>2 and len(lst)%2==0: 161 if isinstance(lst[0],string_types) and (type(lst[1]) in [dict,DictProxy]): 162 theLen=len(lst)/2 163 164 isFixedType=False 165 if len(lst)==3 or len(lst)==9 or len(lst)==6: 166 isFixedType=True 167 for l in lst: 168 try: 169 float(l) 170 except (ValueError,TypeError): 171 isFixedType=False 172 173 if isFixedType: 174 s+="("+" ".join(["%g"%v for v in lst])+")" 175 else: 176 if self.longListThreshold: 177 if theLen>self.longListThreshold: 178 s+=(" "*indent)+str(theLen)+"\n" 179 s+=(" "*indent)+"(\n" 180 for v in lst: 181 if isinstance(v,string_types): 182 s+=(" "*(indent+2))+v+"\n" 183 elif type(v) in [dict,DictProxy]: 184 s+="\n"+(" "*(indent+2))+"{\n" 185 s+=self.strDict(v,indent+4) 186 s+="\n"+(" "*(indent+2))+"}\n" 187 elif type(v) in [list,UnparsedList]: 188 s+="\n" 189 s+=self.strList(v,indent+2) 190 elif type(v)==tuple: 191 s+=" "+self.strTuple(v,indent+2)+" " 192 else: 193 s+=(" "*(indent+2))+str(v)+"\n" 194 195 s+=(" "*indent)+")\n" 196 197 return s
198
199 - def strTuple(self,lst,indent=0):
200 s="" 201 202 for v in lst: 203 if isinstance(v,string_types): 204 s+=v+" " 205 elif type(v) in [dict,DictProxy]: 206 s+="{\n" 207 s+=self.strDict(v,indent+4) 208 s+=(" "*(indent+2))+"} " 209 elif type(v) in [list,UnparsedList]: 210 s+=" " 211 s+=self.strList(v,indent+2) 212 else: 213 s+=(" "*(indent+2))+str(v)+" " 214 215 return s
216
217 -def makeString(data):
218 return str(FoamFileGenerator(data))
219
220 -class FoamFileGeneratorError(PyFoamException):
221 - def __init__(self,descr):
222 PyFoamException.__init__(self,descr)
223 224 # Should work with Python3 and Python2 225