Debian Codegraph @

07p/python/auto/parseS.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 os
21 import sys
22 import struct
23 try:
24 from UserDict import UserDict
25 from UserList import UserList
26 except ImportError: #Python 3
27 from collections import UserDict, UserList
28 try:
29 file
30 except NameError: #Python 3
31 from io import IOBase as file
32 from auto import AUTOExceptions
33 import copy
34 from auto import parseB
35 from auto import parseC
36 from auto import Points
37 import gzip
38 from auto import AUTOutil
39 from auto.AUTOutil import format19_10E3
40 import types
41
42 # End of data exception definition
43 class PrematureEndofData(Exception):
44 pass
45
46 class IncorrectHeaderLength(Exception):
47 pass
48
49 # This is the number of parameters. Should be read from auto.h...
50 # This is not required anymore in AUTO97, since the last entry in
51 # the header line is this number
52 NPAR = 20
53
54 class fileS(object):
55 def __init__(self, filename):
56 if isinstance(filename, str):
57 inputfile = AUTOutil.openFilename(filename,"rb")
58 else:
59 inputfile = filename
60 self.inputfile = inputfile
61 self.name = inputfile.name
62 self.solutions = []
63
64 # We now go through the file and read the solutions.
65 prev = None
66 # for fort.8 we need to read everything into memory; otherwise load the
67 # data on demand from disk when we really need it
68 # on Windows always load everything because deleting open files is
69 # impossible there
70 inmemory = (os.path.basename(inputfile.name) == 'fort.8' or
71 sys.platform in ['cygwin', 'win32'])
72 while len(inputfile.read(1)) > 0:
73 line = inputfile.readline()
74 if not line: raise PrematureEndofData
75 try:
76 header = list(map(int, line.split()))
77 except ValueError:
78 raise PrematureEndofData
79 if len(header) < 10:
80 raise PrematureEndofData
81 if len(header) == 10:
82 # This is the case for AUTO94 and before
83 header = header + [NPAR]
84 numLinesPerEntry = header[8]
85 start_of_data = inputfile.tell()
86 if prev is not None and all(
87 [header[i] == prevheader[i] for i in [4, 6, 7, 8, 11]]):
88 # guess the end from the previous solution
89 end += inputfile.tell() - prev
90 # See if the guess for the solution end is correct
91 inputfile.seek(end)
92 data = inputfile.readline().split()
93 # This is where we detect the end of the file
94 if len(data) == 0:
95 data = inputfile.read(1)
96 if len(data) != 0:
97 try:
98 # Check length of line...
99 if len(data) != 12 and len(data) != 16:
100 raise IncorrectHeaderLength
101 # and the fact they are all integers
102 map(int,data)
103 # and the fact that NCOL*NTST+1=NTPL
104 if int(data[9])*int(data[10])+1 != int(data[6]):
105 end = None
106 # If it passes all these tests we say it is a header line
107 # and we can read quickly
108 except:
109 # otherwise the guessed end is not valid
110 end = None
111 else:
112 end = None
113 data = None
114 if end is None:
115 # We skip the correct number of lines in the entry to
116 # determine its end.
117 inputfile.seek(start_of_data)
118 if inmemory:
119 data = "".encode("ascii").join([inputfile.readline()
120 for i in range(numLinesPerEntry)])
121 else:
122 for i in range(numLinesPerEntry):
123 inputfile.readline()
124 end = inputfile.tell()
125 elif inmemory:
126 inputfile.seek(start_of_data)
127 data = inputfile.read(end - start_of_data)
128 else:
129 inputfile.seek(end)
130 if data is None:
131 data = (start_of_data, end)
132 self.solutions.append({'header': header, 'data': data})
133 prev = start_of_data
134 prevheader = header
135
136 def readstr(self, i):
137 solution = self.solutions[i]
138 data = solution['data']
139 if not isinstance(data, tuple):
140 return data
141 start = data[0]
142 end = data[1]
143 self.inputfile.seek(start)
144 solution['data'] = self.inputfile.read(end - start)
145 return solution['data']
146
147 def readfloats(self, i, total):
148 if not Points.numpyimported:
149 Points.importnumpy()
150 N = Points.N
151 data = self.readstr(i)
152 if hasattr(N, "ndarray") and isinstance(data, N.ndarray):
153 return data
154 fromstring = Points.fromstring
155 if fromstring:
156 fdata = []
157 if "D".encode("ascii") not in data:
158 fdata = fromstring(data, dtype=float, sep=' ')
159 if fdata == [] or len(fdata) != total:
160 fdata = N.array(map(parseB.AUTOatof,
161 data.split()), 'd')
162 else:
163 #make sure the last element is correct
164 #(fromstring may not do this correctly for a
165 #string like -2.05071-106)
166 fdata[-1] = parseB.AUTOatof(
167 data[data.rfind(" ".encode("ascii"))+1:].strip())
168 else:
169 data = data.split()
170 try:
171 fdata = N.array(map(float, data), 'd')
172 except ValueError:
173 fdata = N.array(map(parseB.AUTOatof, data), 'd')
174 if total != len(fdata):
175 raise PrematureEndofData
176 del self.solutions[i]['data']
177 self.solutions[i]['data'] = fdata
178 return fdata
179
180 def conditionalclose(self):
181 # if everything is in memory, close the file
182 for s in self.solutions:
183 if isinstance(s['data'], tuple):
184 return
185 self.inputfile.close()
186
187 # The parseS class parses an AUTO fort.8 file
188 # THESE EXPECT THE FILE TO HAVE VERY SPECIFIC FORMAT!
189 # it provides 4 methods:
190 # read and write take as an arguement either and input or output
191 # stream (basically any object with has the method "readline"
192 # for reading and "write" for writing)
193 #
194 # readFilename and writeFilename take as an arguement a filename
195 # in which to read/write the parameters (basically it opens the
196 # file and then calles "read" or "write"
197 #
198 # Once the data is read in the class provides a list all the points
199 # in the fort.8 file.
200
201 class parseS(list):
202 def __init__(self,filename=None):
203 if isinstance(filename, str):
204 list.__init__(self)
205 self.readFilename(filename)
206 else:
207 if filename is None:
208 list.__init__(self)
209 else:
210 list.__init__(self,filename)
211
212 def __str__(self):
213 rep = ""
214 rep = rep + "Number of solutions: " + str(len(self)) + "\n"
215 labels = self.getLabels()
216 rep = rep + "Labels: "
217 for label in labels:
218 rep = rep + str(label) + " "
219 rep = rep + "\n"
220 return rep
221
222 def __call__(self,label=None):
223 return self.getLabel(label)
224
225 def load(self,**kw):
226 """Load solution with the given AUTO constants.
227 Returns a shallow copy with a copied set of updated constants
228 """
229 irs = kw.get("IRS")
230 if irs is None:
231 irs = (kw.get("constants") or {}).get("IRS")
232 sol = None
233 if irs is not None:
234 if irs != 0:
235 try:
236 sol = self(irs)
237 except KeyError:
238 pass
239 elif len(self) > 0:
240 sol = self[-1]
241 else:
242 raise AUTOExceptions.AUTORuntimeError(
243 "Cannot start from empty solution list.")
244 if sol is None:
245 sol = AUTOSolution()
246 return sol.load(**kw)
247
248 # This function needs a little explanation
249 # It trys to read a new point from the input file, and if
250 # it cannot (because the file ends prematurely) is sets the
251 # file pointer back to the way it was when it started and returns
252 # This will be used to check a file to see if it has a new point
253 # and it will ignore a partially created solution.
254 # Basically it for an VBM kind of program.
255 def tryNextPointRead(self,inputfile):
256 current_position = inputfile.tell()
257 try:
258 self.append(AUTOSolution(inputfile,name=inputfile.name))
259 except PrematureEndofData:
260 inputfile.seek(current_position)
261
262 def read(self,inputfile=None):
263 # We now go through the file and read the solutions.
264 if inputfile is None:
265 # read everything into memory
266 for solution in self:
267 solution.read()
268 return
269 if not isinstance(inputfile, fileS):
270 inputfile = fileS(inputfile)
271 for i in range(len(inputfile.solutions)):
272 solution = AUTOSolution(inputfile,i,inputfile.name)
273 self.append(solution)
274 if len(self) > 0:
275 mbr, mlab = 0, 0
276 for d in self:
277 if d["BR"] > mbr: mbr = d["BR"]
278 if d["LAB"] > mlab: mlab = d["LAB"]
279 for d in self:
280 d._mbr, d._mlab = mbr, mlab
281
282 def write(self,output,mlab=False):
283 for i in range(len(self)):
284 x = self[i]
285 if i == len(self) - 1:
286 # maybe write a header after the last solution so that AUTO can
287 # pickup a new branch and solution label number
288 x.write(output,mlab)
289 else:
290 x.write(output)
291 output.flush()
292
293 def readFilename(self,filename):
294 inputfile = fileS(filename)
295 self.read(inputfile)
296 inputfile.conditionalclose()
297 # else don't close but garbage collect
298
299 def writeFilename(self,filename,append=False,mlab=False):
300 # read all solutions because we may overwrite
301 self.read()
302 if append:
303 output = open(filename,"ab")
304 else:
305 output = open(filename,"wb")
306 self.write(output,mlab)
307 output.close()
308
309 # Removes solutions with the given labels or type name
310 def deleteLabel(self,label=None,keep=0):
311 if label is None:
312 label = [lab for lab in parseB.all_point_types if lab not in
313 ["No Label", "RG", "UZ"]]
314 if isinstance(label, (str, int)):
315 label = [label]
316 indices = []
317 for i in range(len(self)):
318 x = self[i]
319 if ((not keep and (x["Label"] in label or x["Type name"] in label)
320 or (keep and not x["Label"] in label and
321 not x["Type name"] in label))):
322 indices.append(i)
323 indices.reverse()
324 for i in indices:
325 del self[i]
326 if len(self) > 0:
327 maxlab = max(self.getLabels())
328 for d in self:
329 d._mlab = maxlab
330
331 # Relabels the first solution with the given label
332 def relabel(self,old_label=None,new_label=None):
333 if old_label is None and new_label is None:
334 i = 1
335 new = parseS()
336 for d in self:
337 news = d.__class__(d)
338 news["LAB"] = i
339 news._mlab = len(self)
340 i = i + 1
341 new.append(news)
342 return new
343 if isinstance(old_label, int):
344 old_label = [old_label]
345 new_label = [new_label]
346 for j in range(len(old_label)):
347 for d in self:
348 if d["Label"] == old_label[j]:
349 d["Label"] = new_label[j]
350 if len(self) > 0:
351 maxlab = max(self.getLabels())
352 for d in self:
353 d._mlab = maxlab
354
355 # Make all labels in the file unique and sequential
356 def uniquelyLabel(self):
357 i = 1
358 for d in self:
359 d["Label"] = i
360 d._mlab = len(self)
361 i = i + 1
362
363 # Given a label, return the correct solution
364 def getLabel(self,label):
365 if label is None:
366 return self
367 if isinstance(label, int):
368 for d in self:
369 if d["Label"] == label:
370 return d
371 raise KeyError("Label %s not found"%label)
372 if isinstance(label, str) and len(label) > 2 and label[-1].isdigit():
373 j = 2
374 if not label[2].isdigit():
375 j = 3
376 number = int(label[j:])
377 i = 0
378 for d in self:
379 if d["Type name"] == label[:j]:
380 i = i + 1
381 if i == number:
382 return d
383 raise KeyError("Label %s not found"%label)
384 if isinstance(label, types.FunctionType):
385 # accept a user-defined boolean function
386 f = label
387 cnt = getattr(f,"func_code",getattr(f,"__code__",None)).co_argcount
388 if cnt == 1:
389 # function takes just one parameter
390 s = [s for s in self if f(s)]
391 elif cnt == 2:
392 # function takes two parameters: compare all solutions
393 # with each other
394 indices = set([])
395 for i1, s1 in enumerate(self):
396 if i1 in indices:
397 continue
398 for i2 in range(i1+1,len(self)):
399 if i2 not in indices and f(s1, self[i2]):
400 indices.add(i2)
401 s = [self[i] for i in sorted(indices)]
402 else:
403 raise AUTOExceptions.AUTORuntimeError(
404 "Invalid number of arguments for %s."%f.__name__)
405 return self.__class__(s)
406 if not AUTOutil.isiterable(label):
407 label = [label]
408 data = []
409 counts = [0]*len(label)
410 for d in self:
411 ap = None
412 if d["Label"] in label or d["Type name"] in label:
413 ap = d
414 for i in range(len(label)):
415 lab = label[i]
416 j = 2
417 if len(lab) > 2 and not lab[2].isdigit():
418 j = 3
419 if (isinstance(lab, str) and len(lab) > j and
420 d["Type name"] == lab[:j]):
421 counts[i] = counts[i] + 1
422 if counts[i] == int(lab[j:]):
423 ap = d
424 if ap is not None:
425 data.append(ap)
426 return self.__class__(data)
427
428 def getIndex(self,index):
429 return self[index]
430
431 # Return a list of all the labels in the file.
432 def getLabels(self):
433 return [x["Label"] for x in self]
434
435 # an old-style point and point keys within an AUTOSolution
436 class SLPointKey(UserList):
437 def __init__(self, solution=None, index=None, coords=None):
438 if coords=="u dot":
439 self.solution = solution["udotps"]
440 else:
441 self.solution = solution
442 self.index = index
443 def __getattr__(self, attr):
444 if attr == 'data':
445 return [point[self.index] for point in self.solution.coordarray]
446 raise AttributeError(attr)
447 def __setitem__(self, i, item):
448 self.solution.coordarray[i,self.index] = item
449 def __str__(self):
450 return str(self.data)
451 def append(self, item):
452 self.enlarge(1)
453 self.solution.coordarray[-1,self.index] = item
454 self.data.append(item)
455 def extend(self, other):
456 self.enlarge(len(other))
457 for i in range(len(other)):
458 self.solution.coordarray[-len(other)+i,self.index] = other[i]
459 def enlarge(self, ext):
460 # enlarges the dimension of coordarray and coordnames
461 s = self.solution
462 if s._dims is None:
463 s._dims = [s.dimension]*len(s)
464 s0 = s.coordnames[0]
465 s.extend([s0[0:s0.find('(')+1]+str(s.dimension+i+1)+')'
466 for i in range(ext)])
467 s._dims[self.index] = s.dimension
468 if min(s._dims) == max(s._dims):
469 s._dims = None
470
471 class SLPoint(Points.Point):
472 def __init__(self, p, solution=None, index=None):
473 Points.Point.__init__(self, p)
474 self.index = index
475 self.solution = solution
476
477 def __contains__(self, key):
478 return key in ["u", "u dot", "t"] or Points.Point.has_key(self,key)
479
480 def has_key(self, key):
481 return self.__contains__(key)
482
483 def __getitem__(self, coords):
484 if coords == "t":
485 return self.solution.indepvararray[self.index]
486 if coords in ["u", "u dot"]:
487 return SLPointKey(self.solution, self.index, coords)
488 return Points.Point.__getitem__(self, coords)
489
490 def __setitem__(self, coords, item):
491 if coords == 't':
492 self.solution.indepvararray[self.index] = item
493 Points.Point.__setitem__(self, coords, item)
494
495 def __str__(self):
496 return str({ "t" : self["t"], "u" : self["u"], "u dot" : self["u dot"]})
497
498 __repr__ = __str__
499
500 class AUTOParameters(Points.Point):
501 def __init__(self, kwd=None, **kw):
502 if isinstance(kwd, self.__class__):
503 for k,v in kwd.__dict__.items():
504 self.__dict__[k] = v
505 return
506 if kwd is None and kw == {}:
507 self.coordnames = []
508 self.dimension = 0
509 return
510 coordnames = kw.get("coordnames",[])[:]
511 if "coordarray" in kw:
512 coordarray = kw["coordarray"]
513 if len(coordarray) < len(coordnames):
514 kw["coordarray"] = (list(coordarray) +
515 (len(coordnames)-len(coordarray)) * [0.0])
516 for i in range(len(coordnames),len(coordarray)):
517 coordnames.append("PAR(%d)"%(i+1))
518 kw["coordtype"] = Points.float64
519 kw["coordnames"] = coordnames
520 Points.Point.__init__(self,kwd,**kw)
521
522 def __call__(self,index):
523 return self.coordarray[index-1]
524
525 def __str__(self):
526 rep = []
527 for i in range(1,len(self)+1,5):
528 j = min(i+4,len(self))
529 line = "PAR(%-7s "%("%d:%d):"%(i,j))
530 for k in range(i,j+1):
531 if self.coordnames[k-1] != "PAR(%d)"%k:
532 for k in range(i,j+1):
533 line += " %-15s"%self.coordnames[k-1]
534 rep.append(line)
535 line = 12*" "
536 break
537 line += "".join([format19_10E3(self(k)) for k in range(i,j+1)])
538 rep.append(line)
539 return "\n".join(rep)
540
541 # The AUTOsolution class parses an AUTO fort.8 file
542 # THESE EXPECT THE FILE TO HAVE VERY SPECIFIC FORMAT!
543 # it provides 4 methods:
544 # read and write take as an argument either and input or output
545 # stream (basically any object with has the method "readline"
546 # for reading and "write" for writing)
547 #
548 # readFilename and writeFilename take as an argument a filename
549 # in which to read/write the parameters (basically it opens the
550 # file and then calles "read" or "write"
551 #
552 # Used by itself is only reads in ONE solution from the file
553 # for example readFilename will only read the first solution
554 # Commonly it will be used in a container class only using the
555 # read and write methods and letting the outside class take care
556 # of opening the file.
557
558 class AUTOSolution(UserDict,Points.Pointset):
559
560 data_keys = set(["PT", "BR", "TY number", "TY", "LAB",
561 "ISW", "NTST", "NCOL", "Active ICP", "rldot",
562 "udotps", "NPARI", "NDIM", "IPS", "IPRIV"])
563
564 long_data_keys = {
565 "Parameters": "p",
566 "parameters": "p",
567 "Parameter NULL vector": "rldot",
568 "Free Parameters": "Active ICP",
569 "Point number": "PT",
570 "Branch number": "BR",
571 "Type number": "TY number",
572 "Type name": "TY",
573 "TY name": "TY",
574 "Label": "LAB"}
575
576 def __init__(self,input=None,index=None,name=None,t=None,**kw):
577 if isinstance(input,self.__class__):
578 for k,v in input.__dict__.items():
579 self.__dict__[k] = v
580 UserDict.__init__(self,input)
581 else:
582 UserDict.__init__(self)
583 self.c = None
584 self.__input = None
585 self.__fullyParsed = False
586 self._dims = None
587 self._mbr = 0
588 self._mlab = 0
589 self.name = name
590 self.data.update({"BR":1, "PT":1, "TY number":9, "LAB":0,
591 "ISW":1, "NTST": 1, "NCOL": 0,
592 "NPARI":0, "NDIM": 0, "IPS": None, "IPRIV":0})
593 self.indepvarname = 't'
594 self.coordnames = []
595 self.__parnames = []
596
597 if isinstance(input,(file,gzip.GzipFile)):
598 input = fileS(input)
599 if isinstance(input,fileS):
600 self.read(input,index)
601 elif input is not None:
602 self.__readarray(input,t)
603 self.update(**kw)
604
605 def update(self, dct=None, **kw):
606 par = None
607 if "constants" in kw:
608 self.c = kw["constants"]
609 del kw["constants"]
610 unames = dict(self.c.get("unames") or [])
611 self.coordnames = [unames.get(i+1,'U(%d)'%(i+1))
612 for i in range(len(self.coordnames))]
613 parlen = len(self.__parnames)
614 parnames = dict(self.c.get("parnames") or [])
615 if parnames != {}:
616 parlen = max(parlen, max(parnames))
617 par = dict(self.c.get("PAR") or [])
618 for key in par:
619 if key not in parnames.values():
620 parlen = max(key, parlen)
621 self.__parnames = [parnames.get(i,"PAR(%d)"%i)
622 for i in range(1,parlen+1)]
623 if ((self.name is None or os.path.basename(self.name) == 'fort.8')
624 and self.c.get("e") is not None):
625 self.name = self.c["e"]
626
627 if self.name is None:
628 self.name = ''
629 if self.__fullyParsed:
630 self.makeIxMaps()
631 self.PAR = AUTOParameters(coordnames=self.__parnames,
632 coordarray=Points.array(self.PAR),
633 name=self.name)
634 if dct is not None:
635 for k,v in dct.items():
636 self.data[k] = v
637 for k,v in kw.items():
638 self[k] = v
639
640 if par is not None and not self.__nodata():
641 self["PAR"] = par
642 u = self.c.get("U")
643 if u is not None:
644 self["U"] = u
645
646 def __nodata(self):
647 return self.__input is None and not self.__fullyParsed
648
649 def __getstate__(self):
650 # For pickle: read everything
651 self.__readAll()
652 return Points.Pointset.__getstate__(self)
653
654 def __str__(self):
655 self.__readAll()
656 keys = list(self.data)
657 for key in ["BR","PT","LAB","TY number","ISW","NTST","NCOL","NDIM",
658 "IPS","IPRIV","NPARI"]:
659 keys.remove(key)
660 keys.sort()
661 rep=" BR PT TY LAB ISW NTST NCOL"
662 #add corresponding L2-NORM, etc, from fort.7
663 if self["IPS"] is not None:
664 rep = rep+" NDIM IPS IPRIV"
665 for key in keys:
666 if key not in self.data_keys:
667 rep = rep+"%19s"%key
668 rep=rep+ "\n%4d%6d%4s%5d%4d%5d%5d" % (self["BR"], self["PT"],
669 self["TY"], self["LAB"],
670 self["ISW"], self["NTST"],
671 self["NCOL"])
672 if self["IPS"] is not None:
673 rep = rep+"%5d%4d%6d"%(self["NDIM"],self["IPS"],self["IPRIV"])
674 for key in list(keys):
675 if key not in self.data_keys:
676 rep = rep+format19_10E3(self[key])
677 keys.remove(key)
678 if not self.__nodata():
679 rep=rep+"\n"+Points.Pointset.__repr__(self)
680 for key in keys:
681 v = self[key]
682 if isinstance(v,Points.Pointset):
683 v = repr(v)
684 elif type(v) not in [type(1),type(1.0),Points.float64,type("")]:
685 v = list(v)
686 if type(v) == type([]) and type(v[0]) not in [type(1),type(1.0),
687 Points.float64]:
688 v = map(str,v)
689 rep=rep+"\n"+str(key)+": "+str(v)
690 if not self.__nodata():
691 rep=rep+"\n"+str(self.PAR)
692 return rep
693
694 def __repr__(self):
695 result = id(self)
696 if result < 0:
697 # avoid negative addresses and Python 2.3 warnings
698 result += 256 ** struct.calcsize('P')
699 return "<_=%s instance at %#010x>"%(self.__class__.__name__,result)
700
701 def __len__(self):
702 return Points.Pointset.__len__(self)
703
704 def __setitem__(self,key,value):
705 if (type(key) == type("") and not key in self.coordnames and
706 key != self.indepvarname and not key in self.__parnames):
707 shortkey = self.long_data_keys.get(key,key)
708 if shortkey in self.data_keys:
709 if shortkey == "TY":
710 value = parseB.reverse_type_translation(value)
711 shortkey = "TY number"
712 elif shortkey == "BR":
713 self._mbr = 0
714 elif shortkey == "LAB":
715 self._mlab = 0
716 self.data[shortkey] = value
717 return
718 if shortkey == "PAR":
719 if type(value) == type({}):
720 value = value.items()
721 for k,v in value:
722 if isinstance(k,str):
723 self.PAR[k] = v
724 else:
725 self.PAR[k-1] = v
726 return
727 if shortkey == "p":
728 self.PAR = AUTOParameters(coordnames=self.__parnames,
729 coordarray=value, name=self.name)
730 return
731 if shortkey == "U":
732 if type(value) == type({}):
733 value = value.items()
734 for i,(k,v) in enumerate(value):
735 if isinstance(k,str):
736 value[i] = self.coordnames.index(k)
737 if len(self.coordarray[0]) > 1:
738 # reduce solution to one point
739 del self.coordarray
740 del self.indepvararray
741 self.coordarray = Points.N.array([[0.0]]*max(dict(value)))
742 self.indepvararray = Points.N.array([0.0])
743 self.data.update({"NTST": 1, "NCOL": 0})
744 del self.data["Active ICP"]
745 del self.data["rldot"]
746 del self.data["udotps"]
747 for k,v in value:
748 self.coordarray[k-1,0] = v
749 return
750 try:
751 Points.Pointset.__setitem__(self,key,value)
752 except (TypeError, ValueError, KeyError, IndexError):
753 if self.__nodata():
754 raise AUTOExceptions.AUTORuntimeError("Unknown option: %s"%key)
755 self.PAR[key] = value
756
757 def __getitem__(self,key):
758 big_data_keys = ["data","Active ICP","rldot","p","udotps"]
759 if (isinstance(key,str) and key not in self.coordnames and
760 key != self.indepvarname and key not in self.__parnames):
761 shortkey = self.long_data_keys.get(key,key)
762 if shortkey in big_data_keys:
763 self.__readAll()
764 if shortkey in self.data_keys:
765 if shortkey == "TY":
766 return parseB.type_translation(
767 self.data["TY number"])["short name"]
768 return self.data[shortkey]
769 if shortkey == "p":
770 return self.PAR
771 if shortkey == "data":
772 return self
773 if isinstance(key,str) and hasattr(self,"b") and key in self.b:
774 if not self.__fullyParsed or not key in self.PAR:
775 if key not in self.coordnames:
776 return self.b[key]
777 self.__readAll()
778 if isinstance(key, str):
779 try:
780 return Points.Pointset.__getitem__(self,key)
781 except:
782 try:
783 return self.PAR[key]
784 except:
785 return self.data[key]
786 ret = Points.Pointset.__getitem__(self,key)
787 if not isinstance(key, int):
788 return ret
789 return SLPoint(ret, self, key)
790
791 def __call__(self, p=None, coords=None):
792 if p is None:
793 return(str(self))
794 return Points.Pointset.__call__(self, p, coords)
795
796 def __copy__(self):
797 return self.__class__(self)
798
799 def copy(self):
800 return self.__copy__()
801
802 def __contains__(self,key):
803 return (key in ["data","TY"] or key in self.long_data_keys or
804 key in self.__parnames or
805 (not self.__fullyParsed and key in self.data_keys) or
806 (self.__fullyParsed and key in self.data) or
807 (hasattr(self,"b") and key in self.b) or
808 Points.Pointset.has_key(self,key))
809
810 def has_key(self, key):
811 return self.__contains__(key)
812
813 def get(self, key, failobj=None):
814 if key in self:
815 return self[key]
816 return failobj
817
818 def type(self):
819 return parseB.type_translation(self["Type number"])["long name"]
820
821 def load(self,**kw):
822 """Load solution with the given AUTO constants.
823 Returns a shallow copy with a copied set of updated constants
824 """
825 constants = kw.get("constants")
826 if "constants" in kw:
827 del kw["constants"]
828 c = parseC.parseC(self.c)
829 datakw = {}
830 for key in self.data_keys:
831 if key in kw and (key not in c or key in ["LAB", "TY"]):
832 datakw[key] = kw[key]
833 if key not in ["LAB", "TY"]:
834 del kw[key]
835 oldirs = c["IRS"]
836 c.update(constants, **kw)
837 if oldirs is not None and c["IRS"] == 0:
838 return AUTOSolution(constants=c, **datakw)
839 if self["LAB"] != 0:
840 c["IRS"] = self["LAB"]
841 return AUTOSolution(self, constants=c, **datakw)
842
843 def run(self,**kw):
844 """Run AUTO.
845
846 Run AUTO from the solution with the given AUTO constants.
847 Returns a bifurcation diagram of the result.
848 """
849 from auto import runAUTO
850 return runAUTO.runAUTO(selected_solution=self.load(**kw)).run()
851
852 def readAllFilename(self,filename):
853 inputfile = fileS(filename)
854 self.readAll(inputfile)
855 inputfile.close()
856
857 def readFilename(self,filename):
858 inputfile = fileS(filename)
859 self.read(inputfile)
860 inputfile.conditionalclose()
861 # else don't close the input file but garbage collect
862
863 def writeFilename(self,filename,mlab=False):
864 output = open(filename,"wb")
865 self.write(output,mlab)
866 output.flush()
867 output.close()
868
869 def writeRawFilename(self,filename):
870 output = open(filename,"w")
871 self.writeRaw(output)
872 output.flush()
873 output.close()
874
875 def toArray(self):
876 return [
877 [vector["t"]] + [point for point in vector["u"]]
878 for vector in self["data"]]
879
880 def writeRaw(self,output):
881 s = "%24.15E"*(self.coordarray.shape[0]+1)
882 for i in range(self.coordarray.shape[1]):
883 output.write(s%((self.indepvararray[i],)+
884 tuple(self.coordarray[:,i]))+"\n")
885
886 def read(self, inputfile=None, index=0):
887 if self.__fullyParsed:
888 return
889 if inputfile is None:
890 # read data into memory
891 self.__input.readstr(self.__index)
892 self.__input.conditionalclose()
893 return
894 if not isinstance(inputfile, fileS):
895 inputfile = fileS(inputfile)
896 self.__input = inputfile
897 self.__index = index
898 self.__readHeader()
899
900 def readAll(self, inputfile):
901 self.read(inputfile)
902 self.__readAll()
903
904 def __readHeader(self):
905 header = self.__input.solutions[self.__index]['header']
906 self.indepvarname = 't'
907 self.__numEntriesPerBlock = header[7]
908 ndim = self.__numEntriesPerBlock-1
909 if ndim < len(self.coordnames):
910 self.coordnames = self.coordnames[:ndim]
911 for i in range(len(self.coordnames),
912 self.__numEntriesPerBlock-1):
913 self.coordnames.append("U(%d)"%(i+1))
914
915 self.update({"NPARI": 0, "NDIM": 0, "IPS": None, "IPRIV": 0})
916 for i, key in enumerate(["BR", "PT", "TY number", "LAB", "",
917 "ISW", "", "", "", "NTST",
918 "NCOL", "", "NPARI", "NDIM", "IPS",
919 "IPRIV"]):
920 if key and i < len(header):
921 self[key] = header[i]
922 self.__numChangingParameters = header[4]
923 self.__numSValues = header[6]
924 self.__numLinesPerEntry = header[8]
925 self.__numFreeParameters = header[11]
926
927 def __readAll(self):
928 if self.__fullyParsed or self.__nodata():
929 return
930 if not Points.numpyimported:
931 Points.importnumpy()
932 fromstring = Points.fromstring
933 N = Points.N
934 self.__fullyParsed = True
935 n = self.__numEntriesPerBlock
936 nrows = self.__numSValues
937 total = n * nrows + self.__numFreeParameters
938 nlinessmall = (((n-1)/7+1) * nrows + (self.__numFreeParameters+6)/7)
939 if self["NTST"] != 0 and self.__numLinesPerEntry > nlinessmall:
940 total += 2 * self.__numChangingParameters + (n-1) * nrows
941 fdata = self.__input.readfloats(self.__index, total)
942 ups = N.reshape(fdata[:n * nrows],(nrows,n))
943 self.indepvararray = ups[:,0]
944 self.coordarray = N.transpose(ups[:,1:])
945 j = n * nrows
946
947 # Check if direction info is given
948 if self["NTST"] != 0 and self.__numLinesPerEntry > nlinessmall:
949 nfpr = self.__numChangingParameters
950 self["Active ICP"] = list(map(int,fdata[j:j+nfpr]))
951 j = j + nfpr
952 self["rldot"] = fdata[j:j+nfpr]
953 j = j + nfpr
954 n = n - 1
955 self["udotps"] = N.transpose(
956 N.reshape(fdata[j:j+n * self.__numSValues],(-1,n)))
957 udotnames = ["UDOT(%d)"%(i+1) for i in
958 range(self.__numEntriesPerBlock-1)]
959 self["udotps"] = Points.Pointset({
960 "coordarray": self["udotps"],
961 "coordnames": udotnames,
962 "name": self.name})
963 self["udotps"]._dims = None
964 j = j + n * nrows
965
966 self.PAR = fdata[j:j+self.__numFreeParameters]
967 Points.Pointset.__init__(self,{
968 "indepvararray": self.indepvararray,
969 "indepvarname": self.indepvarname,
970 "coordarray": self.coordarray,
971 "coordnames": self.coordnames,
972 "name": self.name})
973 self.update()
974
975 def __readarray(self,coordarray,indepvararray=None):
976 #init from array
977 if not Points.numpyimported:
978 Points.importnumpy()
979 N = Points.N
980 if not hasattr(coordarray[0],'__len__'):
981 # point
982 indepvararray = [0.0]
983 ncol = 0
984 ntst = 1
985 coordarray = [[d] for d in coordarray]
986 pararray = []
987 else:
988 # time + solution
989 if indepvararray is None:
990 indepvararray = coordarray[0]
991 coordarray = coordarray[1:]
992 ncol = 1
993 ntst = len(indepvararray)-1
994 t0 = indepvararray[0]
995 period = indepvararray[-1] - t0
996 if period != 1.0 or t0 != 0.0:
997 #scale to [0,1]
998 for i in range(len(indepvararray)):
999 indepvararray[i] = (indepvararray[i] - t0)/period
1000 # set PAR(11) to period
1001 pararray = 10*[0.0] + [period]
1002 indepvarname = "t"
1003 ndim = len(coordarray)
1004 coordnames = ["U(%d)"%(i+1) for i in range(ndim)]
1005 Points.Pointset.__init__(self,{"indepvararray": indepvararray,
1006 "indepvarname": indepvarname,
1007 "coordarray": coordarray,
1008 "coordnames": coordnames})
1009 self.__fullyParsed = True
1010 self.data.update({"NTST": ntst, "NCOL": ncol, "LAB": 1, "NDIM": ndim})
1011 self.__numChangingParameters = 1
1012 self.PAR = pararray
1013
1014 def __getattr__(self,attr):
1015 if self.__nodata():
1016 raise AUTOExceptions.AUTORuntimeError("Solution without data.")
1017 if not self.__fullyParsed and attr != "__del__":
1018 self.__readAll()
1019 return getattr(self,attr)
1020 raise AttributeError(attr)
1021
1022 def write(self,output,mlab=False):
1023 if self.__nodata():
1024 return
1025 try:
1026 "".encode("ascii") + ""
1027 #write encoded
1028 def write_enc(s):
1029 output.write(s)
1030 except TypeError: #Python 3.0
1031 if hasattr(output, "encoding"):
1032 # output is a text stream
1033 if os.linesep == "\n":
1034 def write_enc(s):
1035 output.write(s)
1036 else:
1037 def write_enc(s):
1038 output.write(s.replace(os.linesep, "\n"))
1039 else:
1040 # output is a binary stream (common case)
1041 def write_enc(s):
1042 output.write(s.encode("ascii"))
1043
1044 if self.__fullyParsed:
1045 ndim = len(self.coordarray)
1046 npar = len(self["Parameters"])
1047 ntpl = len(self)
1048 nrowpr = (ndim//7+1) * ntpl + (npar+6)//7
1049 nfpr = self.__numChangingParameters
1050 if "Active ICP" in self.data:
1051 nfpr = len(self.get("Active ICP",[0]))
1052 nrowpr += (nfpr+19)//20 + (nfpr+6)//7 + (ndim+6)//7 * ntpl
1053 else:
1054 ndim = self.__numEntriesPerBlock-1
1055 npar = self.__numFreeParameters
1056 ntpl = self.__numSValues
1057 nfpr = self.__numChangingParameters
1058 nrowpr = self.__numLinesPerEntry
1059
1060 line = "%6d%6d%6d%6d%6d%6d%8d%6d%8d%5d%5d%5d" % (self["BR"],
1061 self["PT"],
1062 self["TY number"],
1063 self["LAB"],
1064 nfpr,
1065 self["ISW"],
1066 ntpl,
1067 ndim+1,
1068 nrowpr,
1069 self["NTST"],
1070 self["NCOL"],
1071 npar
1072 )
1073 if self["IPS"] is not None:
1074 line += "%5d%5d%5d%5d" % (self["NPARI"],self["NDIM"],self["IPS"],
1075 self["IPRIV"])
1076 write_enc(line+os.linesep)
1077 # If the file isn't already parsed, we can just copy from the input
1078 # file into the output file
1079 if not self.__fullyParsed:
1080 inputsolution = self.__input.readstr(self.__index)
1081 if hasattr(output, "encoding") and hasattr(inputsolution, "decode"):
1082 inputsolution = inputsolution.decode("ascii")
1083 output.write(inputsolution)
1084 # Otherwise we do a normal write. NOTE: if the solution isn't already
1085 # parsed it will get parsed here.
1086 else:
1087 slist = []
1088 for i in range(len(self.indepvararray)):
1089 slist.append(" "+format19_10E3(self.indepvararray[i]))
1090 for j in range(1,len(self.coordarray)+1):
1091 if j%7==0:
1092 slist.append(os.linesep+" ")
1093 slist.append(format19_10E3(self.coordarray[j-1,i]))
1094 slist.append(os.linesep)
1095 write_enc("".join(slist))
1096 if "Active ICP" in self.data:
1097 # Solution contains derivative information.
1098 j = 0
1099 for parameter in self["Active ICP"]:
1100 write_enc("%5d" % (parameter))
1101 j = j + 1
1102 if j%20==0:
1103 write_enc(os.linesep)
1104 if j%20!=0:
1105 write_enc(os.linesep)
1106
1107 line = " "
1108 i = 0
1109 for vi in self["rldot"]:
1110 num = format19_10E3(vi)
1111 if i != 0 and i%7==0:
1112 line = line + os.linesep + " "
1113 line = line + num
1114 i = i + 1
1115 write_enc(line+os.linesep)
1116
1117 # write UDOTPS
1118 slist = []
1119 c = self["udotps"].coordarray
1120 l = len(c)
1121 for i in range(len(self.indepvararray)):
1122 slist.append(" ")
1123 for j in range(len(self.coordarray)):
1124 if j!=0 and j%7==0:
1125 slist.append(os.linesep+" ")
1126 if j<l:
1127 slist.append(format19_10E3(c[j,i]))
1128 else:
1129 slist.append(format19_10E3(0))
1130 slist.append(os.linesep)
1131 write_enc("".join(slist))
1132
1133 line = " "
1134 j = 0
1135 for parameter in self.PAR.toarray():
1136 num = format19_10E3(parameter)
1137 line = line + num
1138 j = j + 1
1139 if j%7==0:
1140 write_enc(line+os.linesep)
1141 line = " "
1142 if j%7!=0:
1143 write_enc(line+os.linesep)
1144 if mlab and (self._mbr > 0 or self._mlab > 0) and not (
1145 self._mbr == self["BR"] and self._mlab == self["LAB"]):
1146 # header for empty solution so that AUTO can pickup the maximal
1147 # label and branch numbers.
1148 if self["IPS"] is not None:
1149 write_enc("%6d%6d%6d%6d%6d%6d%8d%6d%8d%5d%5d%5d%5d%5d%5d%5d%s"%
1150 ((self._mbr, 0, 0, self._mlab) + 12*(0,) + (os.linesep,)))
1151 else:
1152 write_enc("%6d%6d%6d%6d%6d%6d%8d%6d%8d%5d%5d%5d%s"%
1153 ((self._mbr, 0, 0, self._mlab) + 8*(0,) + (os.linesep,)))
1154 output.flush()
1155
1156 def pointtest(a,b):
1157 keys = ['Type number', 'Type name', 'Parameter NULL vector',
1158 'Free Parameters', 'Branch number',
1159 'data', 'NCOL', 'Label', 'ISW', 'NTST',
1160 'Point number', 'Parameters']
1161
1162 # make sure the solutions are fully parsed...
1163 scratch=a['Parameters']
1164 scratch=b['Parameters']
1165 for key in keys:
1166 if key not in a:
1167 raise AUTOExceptions.AUTORegressionError("No %s label"%(key,))
1168 if len(a["data"]) != len(b["data"]):
1169 raise AUTOExceptions.AUTORegressionError("Data sections have different lengths")
1170
1171
1172 def test():
1173 print("Testing reading from a filename")
1174 foo = parseS()
1175 foo.readFilename("test_data/fort.8")
1176 if len(foo) != 5:
1177 raise AUTOExceptions.AUTORegressionError("File length incorrect")
1178 pointtest(foo.getIndex(0),foo.getIndex(3))
1179
1180 print("Testing reading from a stream")
1181 foo = parseS()
1182 fp = open("test_data/fort.8","rb")
1183 foo.read(fp)
1184 if len(foo) != 5:
1185 raise AUTOExceptions.AUTORegressionError("File length incorrect")
1186 pointtest(foo.getIndex(0),foo.getIndex(3))
1187
1188
1189
1190 print("parseS passed all tests")
1191
1192 if __name__ == '__main__' :
1193 test()