Debian Codegraph @

07p/python/auto/parseC.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # Visualization for Bifurcation Manifolds
3 # Copyright (C) 1997 Randy Paffenroth and John Maddocks
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public
7 # License as published by the Free Software Foundation; either
8 # version 2 of the License, or (at your option) any later version.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Library General Public License for more details.
14 #
15 # You should have received a copy of the GNU Library General Public
16 # License along with this library; if not, write to the Free
17 # Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
18 # MA 02111-1307, USA
19
20 import sys
21 from auto import AUTOExceptions
22 from auto import AUTOutil
23 from auto import parseB
24
25 # The parseC class parses an AUTO parameter file
26 # THESE EXPECT THE FILE TO HAVE VERY SPECIFIC FORMAT!
27 # it provides 4 methods:
28 # read and write take as an arguement either and input or output
29 # stream (basically any object with has the method "readline"
30 # for reading and "write" for writing)
31 #
32 # readFilename and writeFilename take as an arguement a filename
33 # in which to read/write the parameters (basically it opens the
34 # file and then calles "read" or "write"
35 #
36 # Once the data is read in the class provides a dictionary
37 # interface for manipulating the file.
38
39 class parseC(dict):
40
41 line_comments = ["NDIM,IPS,IRS,ILP",
42 "NICP,(ICP(I),I=1 NICP)",
43 "NTST,NCOL,IAD,ISP,ISW,IPLT,NBC,NINT",
44 "NMX,RL0,RL1,A0,A1",
45 "NPR,MXBF,IID,ITMX,ITNW,NWTN,JAC",
46 "EPSL,EPSU,EPSS",
47 "DS,DSMIN,DSMAX,IADS",
48 "NTHL,(/,I,THL(I)),I=1,NTHL)",
49 "NTHU,(/,I,THU(I)),I=1,NTHU)",
50 "NUZR,(/,I,PAR(I)),I=1,NUZR)"]
51
52 # These keys are preserved when reading in a new constants file,
53 # and the keys are not in the constants file
54 # Other keys are set to "None"
55 special_keys = ["unames", "parnames", "e", "homcont"]
56
57 def __init__(self, filename=None, **kw):
58 self["new"] = True
59 if filename is not None and type(filename) != type(""):
60 dict.__init__(self, filename)
61 self.update(**kw)
62 return
63 dict.__init__(self)
64 for key in ['NPR', 'EPSS', 'ITMX', 'EPSU', 'ITNW', 'NBC',
65 'IADS', 'IPS', 'IID', 'IIS', 'A1', 'DS', 'NMX', 'NTST',
66 'NINT', 'NWTN', 'A0', 'EPSL', 'ISP', 'DSMIN', 'MXBF',
67 'RL0', 'RL1', 'IPLT', 'ILP', 'NCOL',
68 'DSMAX', 'ISW', 'IRS', 'IAD', 'JAC', 'NDIM', 'NPAR',
69 'IBR', 'LAB', 'TY',
70 'NUNSTAB', 'NSTAB', 'IEQUIB', 'ITWIST', 'ISTART',
71 'sv', 's', 'dat',
72 "THL","THU","UZR","UZSTOP","ICP","IREV","IFIXED","IPSI","U","PAR",
73 "SP","STOP"]:
74 self[key] = None
75 if filename:
76 self.readFilename(filename)
77 self.update(**kw)
78
79 def __setitem__(self, key, item):
80 if key in ["THL", "THU", "UZR", "UZSTOP", "U", "PAR", "unames",
81 "parnames"]:
82 if item is not None:
83 if key == "PAR":
84 from auto import parseS
85 if isinstance(item,parseS.AUTOParameters):
86 item = [(k,item(k)) for k in range(1,len(item)+1)]
87 if isinstance(item, dict):
88 item = item.items()
89 new = []
90 for x in item:
91 if isinstance(x, dict):
92 new.append([x["PAR index"], x["PAR value"]])
93 else:
94 new.append([x[0], x[1]])
95 item = new
96 elif key == "DS" and item == '-':
97 if self[key] is None:
98 item = -0.01
99 else:
100 item = -self[key]
101 dict.__setitem__(self, key, item)
102
103 def update(self, d=None, **kw):
104 """ Change the options for this parseC object"""
105 dct = d
106 if dct is None:
107 dct = {}
108 dct.update(kw)
109 for key in dct:
110 value = dct[key]
111 if self.get("homcont") is not None and key in self["homcont"]:
112 self["homcont"][key] = value
113 elif key in self or key in self.special_keys:
114 self[key] = value
115 elif key[:7] != 'Active ':
116 raise AUTOExceptions.AUTORuntimeError(
117 "Unknown option: %s"%(key,))
118
119 def setdefault(self, *args):
120 k = args[0]
121 if len(args) > 1:
122 d = args[1]
123 else:
124 d = None
125 if k not in self:
126 self[k] = d
127 return self.get(*args)
128
129 def readFilename(self, filename):
130 inputfile = open(filename, "r")
131 self.read(inputfile)
132 inputfile.close()
133
134 def writeFilename(self, filename, new=False):
135 output = open(filename, "w")
136 self.write(output, new)
137 output.close()
138
139 def scanvalue(self, line, inputfile=None):
140 # Scans line for a value
141 # returns the value, followed by the rest of the line
142 # The value is returned as a flat list of strings if the line
143 # starts with [ and otherwise as a single string
144 level = 0
145 quote = ' '
146 quoteesc = False
147 prev = ' '
148 npos = 0
149 value = ''
150 isdict = False
151 v = ''
152 line = line.strip()
153 i = 0
154 while True:
155 if i == len(line):
156 if level == 0 or inputfile is None:
157 break
158 line = inputfile.readline().strip()
159 i = 0
160 npos = i
161 c = line[i]
162 if quote == ' ':
163 if c in [',', ' ']:
164 if level == 0:
165 break
166 elif c == ':':
167 pass
168 elif c in [']', '}']:
169 if c == '}':
170 isdict = False
171 if level == 1 and prev in ['[', '{']:
172 value = []
173 level = level - 1
174 if v != '':
175 value.append(v)
176 v = ''
177 if c == ']' and isdict:
178 value.append(']')
179 else:
180 if prev in [',', ' ', ':'] and level > 0 and v != '':
181 value.append(v)
182 v = ''
183 if c in ['[','{']:
184 if level == 0:
185 value = []
186 level = level + 1
187 if c == '{':
188 isdict = True
189 elif isdict:
190 value.append('[')
191 elif c in ['"', "'"]:
192 quote = c
193 else:
194 v = v + c
195 elif c == quote:
196 # ignore "" and ''
197 if (i+1 < len(line) and line[i+1] == c) or quoteesc:
198 quoteesc = not quoteesc
199 else:
200 quote = ' '
201 else:
202 v = v + c
203 prev = c
204 i = i + 1
205 if v != '':
206 value = v
207 while npos < len(line) and line[npos] in [" ", ","]:
208 npos = npos + 1
209 if npos >= len(line) - 1:
210 line = ''
211 else:
212 line = line[npos:].strip()
213 return value, line
214
215 def parseline(self, line, userspec=False, inputfile=None, lineno=None):
216 # parses a new-style constant file line and puts the keys
217 # in the dictionary c; also used for the header of a b. file
218 while line != "":
219 line = line.strip()
220 if line[0] in ['#', '!', '_']:
221 return
222 pos = line.find('=')
223 if pos == -1:
224 return
225 key = line[:pos].strip()
226 value, line = self.scanvalue(line[pos+1:],inputfile)
227 if key in ['ICP', 'IREV', 'IFIXED', 'IPSI']:
228 d = []
229 for v in value:
230 try:
231 v = int(v)
232 except ValueError:
233 pass
234 d.append(v)
235 value = d
236 elif key in ['THU', 'THL', 'UZR', 'UZSTOP', 'U', 'PAR']:
237 d = []
238 i = 0
239 while i < len(value):
240 try:
241 v0 = int(value[i])
242 except ValueError:
243 v0 = value[i]
244 if value[i+1] == '[':
245 i = i + 1
246 v1 = []
247 while i+1 < len(value) and value[i+1] != ']':
248 v1.append(parseB.AUTOatof(value[i+1]))
249 i = i + 1
250 else:
251 v1 = parseB.AUTOatof(value[i+1])
252 d.append([v0,v1])
253 i = i + 2
254 value = self.__compactindexed(d)
255 elif key in ['unames', 'parnames']:
256 value = [[int(value[i]),value[i+1]]
257 for i in range(0,len(value),2)]
258 elif key in ['s', 'dat', 'sv', 'e', 'SP', 'STOP', 'TY']:
259 pass
260 elif key in self:
261 if key[0] in 'IJKLMN':
262 if value[0] == '*':
263 value = 10**len(value)
264 elif key == 'IRS':
265 try:
266 value = int(value)
267 except ValueError:
268 pass
269 else:
270 value = int(value)
271 else:
272 value=parseB.AUTOatof(value)
273 elif lineno is not None:
274 raise AUTOExceptions.AUTORuntimeError(
275 "Unknown AUTO constant %s on line %d"%(key,lineno))
276 else:
277 value = None
278 if value is not None:
279 if userspec:
280 self["Active "+key] = self[key]
281 self[key] = value
282
283 def read(self, inputfile):
284 line = inputfile.readline()
285 lineno = 1
286 while line != '':
287 data = line.split()
288 if len(data) > 0:
289 if data[0][0].isdigit():
290 break
291 self.parseline(line,inputfile=inputfile,lineno=lineno)
292 line = inputfile.readline()
293 lineno += 1
294
295 if line == '':
296 return
297
298 self["new"] = False
299 self["NDIM"] = int(data[0])
300 self["IPS"] = int(data[1])
301 try:
302 self["IRS"] = int(data[2])
303 except ValueError:
304 self["IRS"] = data[2]
305 self["ILP"] = int(data[3])
306
307 line = inputfile.readline()
308 data = line.split()
309 icp = []
310 for i in range(int(data[0])):
311 d = data[i+1]
312 try:
313 d = int(d)
314 except ValueError:
315 pass
316 icp.append(d)
317 self["ICP"] = icp
318
319 for line_comment in self.line_comments[2:7]:
320 line = inputfile.readline()
321 data = line.split()
322 for d, key in zip(data, line_comment.split(",")):
323 if key[0] in 'IJKLMN':
324 self[key] = int(d)
325 else:
326 self[key] = parseB.AUTOatof(d)
327
328 for key in ["THL", "THU", "UZR"]:
329 line = inputfile.readline()
330 data = line.split()
331 item = []
332 for i in range(int(data[0])):
333 line = inputfile.readline()
334 data = line.split()
335 d = data[0]
336 try:
337 d = int(d)
338 except ValueError:
339 pass
340 item.append([d, parseB.AUTOatof(data[1])])
341 self[key] = item
342
343 def __compactindexed(self, value):
344 """compact THL/THU/UZR lists"""
345 d = []
346 v0s = []
347 for v0, v1 in value:
348 if v0 in v0s:
349 if not AUTOutil.isiterable(v1):
350 v1 = [v1]
351 # add to list when parameter was already encountered
352 try:
353 d[v0s.index(v0)][1].extend(v1)
354 except AttributeError:
355 d[v0s.index(v0)][1] = [d[v0s.index(v0)][1]]
356 d[v0s.index(v0)][1].extend(v1)
357 else:
358 v0s.append(v0)
359 d.append([v0,v1])
360 return d
361
362 def __compactstr(self, value):
363 """check if we can use more compact output than str..."""
364 try:
365 str1 = "%.5g" % value
366 str2 = str(value)
367 if float(str1) == float(str2) and 'e' in str1:
368 return str1
369 return str2
370 except TypeError:
371 l = []
372 for v in value:
373 l.append(self.__compactstr(v))
374 return '['+", ".join(l)+']'
375
376 def __newstr(self, lines=None):
377 wdth3keys = ["NMX", "NPR", "NBC", "JAC", "e"]
378 wdth5keys = ["EPSU", "EPSS"]
379 if lines is None:
380 lines = [
381 ["e", "s", "dat", "sv"],
382 ["unames", "parnames"],
383 ["U", "PAR"],
384 ["NDIM", "IPS", "IRS", "ILP"],
385 ["ICP"],
386 ["NTST", "NCOL", "IAD", "ISP", "ISW", "IPLT", "NBC", "NINT"],
387 ["NMX", "NPR", "MXBF", "IID", "ITMX", "ITNW", "NWTN", "JAC"],
388 ["EPSL", "EPSU", "EPSS"],
389 ["DS", "DSMIN", "DSMAX", "IADS"],
390 ["NPAR", "THL", "THU"],
391 ["IIS", "IBR", "LAB", "TY"],
392 ["UZR"],
393 ["UZSTOP"],
394 ["STOP"],
395 ["SP"],
396 ["RL0", "RL1", "A0", "A1"],
397 ["NUNSTAB", "NSTAB", "IEQUIB", "ITWIST", "ISTART"],
398 ["IREV", "IFIXED", "IPSI"]]
399 olist = []
400 for line in lines:
401 pos = 0
402 for key in line:
403 value = self.get(key)
404 if value is None:
405 continue
406 if pos > 0:
407 olist.append(", ")
408 pos = pos + 1
409 if key in wdth3keys:
410 s = "%-3s=" % key
411 elif key in wdth5keys:
412 s = "%-5s=" % key
413 else:
414 s = "%-4s=" % key
415 olist.append(s)
416 if key in ["ICP", "IREV", "IFIXED", "IPSI", "STOP", "SP"]:
417 s = " "+str(value)
418 elif key in ["THL", "THU", "UZR", "UZSTOP", "U", "PAR"]:
419 l = ["'"+str(k)+"': "+self.__compactstr(v) for k, v in value]
420 s = " {"+", ".join(l)+"}"
421 elif key in ["unames", "parnames"]:
422 l = [str(k)+": '"+str(v)+"'" for k, v in value]
423 s = "{"+", ".join(l)+"}"
424 elif key in ["sv", "s", "dat", "e", "TY"]:
425 value = "'"+str(value)+"'"
426 if key in wdth3keys:
427 s = "%5s" % value
428 else:
429 s = "%4s" % value
430 elif key[0] in ["A", "D", "E", "R"]:
431 value = self.__compactstr(value)
432 s = "%6s" % value
433 elif pos > 4:
434 s = "%2s" % value
435 elif key in wdth3keys:
436 s = "%5s" % value
437 else:
438 s = "%4s" % value
439 olist.append(s)
440 if pos > 0:
441 olist.append("\n")
442 return "".join(olist)
443
444 def __oldstr(self):
445 olist = [self.__newstr([
446 ["e", "s", "dat", "sv"],
447 ["unames", "parnames"],
448 ["U", "PAR"],
449 ["NPAR", "IBR", "LAB"],
450 ["STOP"],
451 ["SP"],
452 ["NUNSTAB", "NSTAB", "IEQUIB", "ITWIST", "ISTART"],
453 ["IREV", "IFIXED", "IPSI"]])]
454
455 for j, line_comment in enumerate(self.line_comments):
456 if j==1:
457 s = " ".join([str(len(self["ICP"]))]+map(str,self["ICP"]))
458 elif j==7:
459 s = str(len(self["THL"]))
460 elif j==8:
461 s = str(len(self["THU"]))
462 elif j==9:
463 uzrlist = []
464 for k, v in self["UZR"] or []:
465 if not AUTOutil.isiterable(v):
466 v = [v]
467 for vv in v:
468 uzrlist.append([k, vv])
469 s = str(len(uzrlist))
470 else:
471 s = " ".join([str(self[d]) for d in line_comment.split(",")])
472 olist.append(s+" "*(max(24-len(s),1))+line_comment+"\n")
473 if j==7:
474 for k, v in self["THL"] or []:
475 olist.append("%s %s\n" % (k, v))
476 elif j==8:
477 for k, v in self["THU"] or []:
478 olist.append("%s %s\n" % (k, v))
479 elif j==9:
480 for k, v in uzrlist:
481 olist.append("%s %s\n" % (k, v))
482
483 return "".join(olist)
484
485 def __str__(self):
486 if self["new"]:
487 return self.__newstr()
488 else:
489 return self.__oldstr()
490
491 def write(self, output, new=False):
492 if new and not self["new"]:
493 for key in ["UZR", "THL", "THU"]:
494 self[key] = self.__compactindexed(self[key])
495 output.write(self.__newstr())
496 else:
497 output.write(str(self))
498
499 def pointtest(a):
500 keys = ['NPR', 'UZR', 'EPSS', 'ITMX', 'EPSU', 'ITNW', 'NBC',
501 'IADS', 'IPS', 'IID', 'A1', 'DS', 'NMX', 'NTST',
502 'NINT', 'NWTN', 'A0', 'EPSL', 'ISP', 'DSMIN', 'MXBF',
503 'RL0', 'RL1', 'ICP', 'IPLT', 'ILP', 'NCOL', 'THL',
504 'DSMAX', 'ISW', 'IRS', 'THU', 'IAD', 'JAC', 'NDIM']
505 for key in keys:
506 if key not in a:
507 raise AUTOExceptions.AUTORegressionError("No %s label"%(key,))
508
509 def test():
510 print("Testing reading from a filename")
511 foo = parseC()
512 foo.readFilename("test_data/c.ab")
513 pointtest(foo)
514 foo.write(sys.stdout, new=True)
515
516 print("Testing reading from a stream")
517 foo = parseC()
518 fp = open("test_data/c.ab", "r")
519 foo.read(fp)
520 pointtest(foo)
521
522 print("parseC passed all tests")
523
524 if __name__ == '__main__' :
525 test()
526
527