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