Package PyFoam :: Package RunDictionary :: Module ParsedParameterFile
[hide private]
[frames] | no frames]

Source Code for Module PyFoam.RunDictionary.ParsedParameterFile

  1  #  ICE Revision: $Id: ParsedParameterFile.py 8209 2007-11-22 14:22:40Z bgschaid $  
  2  """Parameter file is read into memory and modified there""" 
  3   
  4  from FileBasis import FileBasisBackup 
  5  from PyFoam.Basics.PlyParser import PlyParser 
  6  from PyFoam.Basics.FoamFileGenerator import FoamFileGenerator 
  7   
  8  from PyFoam.Basics.DataStructures import Vector,Field,Dimension,DictProxy,Tensor,SymmTensor 
  9   
10 -class ParsedParameterFile(FileBasisBackup):
11 """ Parameterfile whose complete representation is read into 12 memory, can be manipulated and afterwards written to disk""" 13
14 - def __init__(self,name,backup=False,debug=False,boundaryDict=False):
15 """@param name: The name of the parameter file 16 @param backup: create a backup-copy of the file 17 @param boundaryDict: the file to parse is a boundary file""" 18 19 FileBasisBackup.__init__(self,name,backup=backup) 20 self.debug=debug 21 self.boundaryDict=boundaryDict 22 23 self.header=None 24 self.content=None 25 26 self.readFile()
27
28 - def parse(self,content):
29 """Constructs a representation of the file""" 30 parser=FoamFileParser(content,debug=self.debug,boundaryDict=self.boundaryDict) 31 self.content=parser.getData() 32 self.header=parser.getHeader() 33 return self.content
34
35 - def __getitem__(self,key):
36 return self.content[key]
37
38 - def __setitem__(self,key,value):
39 self.content[key]=value
40
41 - def __str__(self):
42 """Generates a string from the contents in memory 43 Used to be called makeString""" 44 45 string="// File generated by PyFoam - sorry for the ugliness\n\n" 46 47 generator=FoamFileGenerator(self.content,header=self.header) 48 string+=str(generator) 49 50 return string
51
52 -class FoamFileParser(PlyParser):
53 """Class that parses a string that contains the contents of an 54 OpenFOAM-file and builds a nested structure of directories and 55 lists from it""" 56
57 - def __init__(self,content,debug=False,noHeader=False,boundaryDict=False):
58 """@param content: the string to be parsed 59 @param debug: output debug information during parsing 60 @param noHeader: switch that turns off the parsing of the header""" 61 62 self.data=None 63 self.header=None 64 self.debug=debug 65 66 if noHeader: 67 self.start='noHeader' 68 69 if boundaryDict: 70 self.start='boundaryDict' 71 72 PlyParser.__init__(self,debug=debug) 73 74 #sys.setrecursionlimit(50000) 75 #print sys.getrecursionlimit() 76 77 self.header,self.data=self.parse(content)
78
79 - def __getitem__(self,key):
80 return self.data[key]
81
82 - def __setitem__(self,key,value):
83 self.data[key]=value
84
85 - def getData(self):
86 """ Get the data structure""" 87 return self.data
88
89 - def getHeader(self):
90 """ Get the OpenFOAM-header""" 91 return self.header
92
93 - def printContext(self,c,ind):
94 """Prints the context of the current index""" 95 print "------" 96 print c[max(0,ind-100):max(0,ind-1)] 97 print "------" 98 print ">",c[ind-1],"<" 99 print "------" 100 print c[min(len(c),ind):min(len(c),ind+100)] 101 print "------"
102
103 - def parserError(self,text,c,ind):
104 """Prints the error message of the parser and exit""" 105 print "PARSER ERROR:",text 106 print "On index",ind 107 self.printContext(c,ind) 108 raise ParseError
109 110 tokens = ( 111 'NAME', 112 'ICONST', 113 'FCONST', 114 'SCONST', 115 'FOAMFILE', 116 'UNIFORM', 117 'NONUNIFORM', 118 ) 119 120 reserved = { 121 'FoamFile' : 'FOAMFILE', 122 'uniform' : 'UNIFORM', 123 'nonuniform' : 'NONUNIFORM', 124 } 125
126 - def t_NAME(self,t):
127 r'[a-zA-Z_][<>(),.\*|a-zA-Z_0-9+]*' 128 t.type=self.reserved.get(t.value,'NAME') 129 return t
130 131 t_ICONST = r'(-|)\d+([uU]|[lL]|[uU][lL]|[lL][uU])?' 132 133 t_FCONST = r'(-|)((\d+)(\.\d*)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?' 134 135 t_SCONST = r'\"([^\\\n]|(\\.))*?\"' 136 137 literals = "(){};[]" 138 139 t_ignore=" \t" 140 141 # Define a rule so we can track line numbers
142 - def t_newline(self,t):
143 r'\n+' 144 t.lexer.lineno += len(t.value)
145 146 # C or C++ comment (ignore)
147 - def t_ccode_comment(self,t):
148 r'(/\*(.|\n)*?\*/)|(//.*)' 149 t.lexer.lineno += t.value.count('\n') 150 pass
151 152 # Error handling rule
153 - def t_error(self,t):
154 print "Illegal character '%s'" % t.value[0] 155 t.lexer.skip(1)
156
157 - def p_global(self,p):
158 'global : header dictbody' 159 p[0] = ( p[1] , p[2] )
160
161 - def p_noHeader(self,p):
162 'noHeader : dictbody' 163 p[0] = ( None , p[1] )
164
165 - def p_boundaryDict(self,p):
166 '''boundaryDict : header list 167 | header prelist ''' 168 # p[0] = ( p[1] , dict(zip(p[2][::2],p[2][1::2])) ) 169 p[0] = ( p[1] , p[2] )
170
171 - def p_header(self,p):
172 'header : FOAMFILE dictionary' 173 p[0] = p[2]
174
175 - def p_integer(self,p):
176 '''integer : ICONST''' 177 p[0] = int(p[1])
178
179 - def p_float(self,p):
180 '''integer : FCONST''' 181 p[0] = float(p[1])
182
183 - def p_dictionary(self,p):
184 '''dictionary : '{' dictbody '}' 185 | '{' '}' ''' 186 if len(p)==4: 187 p[0] = p[2] 188 else: 189 p[0] = DictProxy()
190
191 - def p_dictbody(self,p):
192 '''dictbody : dictbody dictline 193 | dictline 194 | empty''' 195 196 if len(p)==3: 197 p[0]=p[1] 198 p[0][p[2][0]]=p[2][1] 199 else: 200 if p[1]: 201 p[0]=DictProxy() 202 p[0][p[1][0]]=p[1][1] 203 else: 204 p[0]=DictProxy()
205
206 - def p_list(self,p):
207 '''list : '(' itemlist ')' ''' 208 p[0] = p[2] 209 if len(p[2])==3 or len(p[2])==9 or len(p[2])==6: 210 isVector=True 211 for i in p[2]: 212 try: 213 float(i) 214 except: 215 isVector=False 216 if isVector: 217 if len(p[2])==3: 218 p[0]=apply(Vector,p[2]) 219 elif len(p[2])==9: 220 p[0]=apply(Tensor,p[2]) 221 else: 222 p[0]=apply(SymmTensor,p[2])
223
224 - def p_prelist(self,p):
225 '''prelist : integer '(' itemlist ')' ''' 226 p[0] = p[3]
227
228 - def p_itemlist(self,p):
229 '''itemlist : itemlist item 230 | item ''' 231 if len(p)==2: 232 if p[1]==None: 233 p[0]=[] 234 else: 235 p[0]=[ p[1] ] 236 else: 237 p[0]=p[1] 238 p[0].append(p[2])
239
240 - def p_dictline(self,p):
241 '''dictline : NAME dictitem ';' 242 | NAME list ';' 243 | NAME prelist ';' 244 | NAME fieldvalue ';' 245 | NAME dictionary''' 246 p[0]= ( p[1] , p[2] )
247
248 - def p_number(self,p):
249 '''number : integer 250 | FCONST''' 251 p[0] = p[1]
252
253 - def p_dimension(self,p):
254 '''dimension : '[' number number number number number number number ']' ''' 255 p[0]=apply(Dimension,p[2:-1])
256
257 - def p_vector(self,p):
258 '''vector : '(' number number number ')' ''' 259 p[0]=apply(Vector,p[2:5])
260
261 - def p_tensor(self,p):
262 '''tensor : '(' number number number number number number number number number ')' ''' 263 p[0]=apply(Tensor,p[2:11])
264
265 - def p_symmtensor(self,p):
266 '''symmtensor : '(' number number number number number number ')' ''' 267 p[0]=apply(SymmTensor,p[2:8])
268
269 - def p_fieldvalue_uniform(self,p):
270 '''fieldvalue : UNIFORM number 271 | UNIFORM vector 272 | UNIFORM tensor 273 | UNIFORM symmtensor''' 274 p[0] = Field(p[2])
275
276 - def p_fieldvalue_nonuniform(self,p):
277 '''fieldvalue : NONUNIFORM NAME list 278 | NONUNIFORM NAME prelist''' 279 p[0] = Field(p[3],name=p[2])
280
281 - def p_dictitem(self,p):
282 '''dictitem : longitem 283 | pitem''' 284 p[0] = p[1]
285
286 - def p_longitem(self,p):
287 '''longitem : pitemlist pitem''' 288 p[0] = p[1]+(p[2],)
289
290 - def p_pitemlist(self,p):
291 '''pitemlist : pitemlist pitem 292 | pitem ''' 293 if len(p)==2: 294 p[0]=(p[1],) 295 else: 296 p[0]=p[1]+(p[2],)
297
298 - def p_pitem(self,p):
299 '''pitem : NAME 300 | SCONST 301 | number 302 | dictionary 303 | list 304 | dimension 305 | empty''' 306 p[0] = p[1]
307
308 - def p_item(self,p):
309 '''item : pitem 310 | list 311 | dictionary''' 312 p[0] = p[1]
313
314 - def p_empty(self,p):
315 'empty :' 316 pass
317
318 - def p_error(self,p):
319 raise "ParserError",("Syntax error at token", p) # .type, p.lineno
320 # Just discard the token and tell the parser it's okay. 321 # self.yacc.errok() 322
323 -class FoamStringParser(FoamFileParser):
324 """Convenience class that parses only a headerless OpenFOAM dictionary""" 325
326 - def __init__(self,content,debug=False):
327 """@param content: the string to be parsed 328 @param debug: output debug information during parsing""" 329 330 FoamFileParser.__init__(self,content,debug=debug,noHeader=True,boundaryDict=False)
331
332 - def __str__(self):
333 return str(FoamFileGenerator(self.data))
334
335 -class ParsedBoundaryDict(ParsedParameterFile):
336 """Convenience class that parses only a OpenFOAM polyMesh-boundaries file""" 337
338 - def __init__(self,name,backup=False,debug=False):
339 """@param name: The name of the parameter file 340 @param backup: create a backup-copy of the file""" 341 342 ParsedParameterFile.__init__(self,name,backup=backup,debug=debug,boundaryDict=True)
343
344 - def parse(self,content):
345 """Constructs a representation of the file""" 346 temp=ParsedParameterFile.parse(self,content) 347 self.content={} 348 for i in range(0,len(temp),2): 349 self.content[temp[i]]=temp[i+1] 350 return self.content
351
352 - def __str__(self):
353 string="// File generated by PyFoam - sorry for the ugliness\n\n" 354 temp=[] 355 for k,v in self.content.iteritems(): 356 temp.append((k,v)) 357 358 temp.sort(lambda x,y:cmp(int(x[1]["startFace"]),int(y[1]["startFace"]))) 359 360 temp2=[] 361 362 for b in temp: 363 temp2.append(b[0]) 364 temp2.append(b[1]) 365 366 generator=FoamFileGenerator(temp2,header=self.header) 367 string+=str(generator) 368 369 return string
370