Example #1
0
    def execfile(self, name=None):
        """Execute an AUTO CLUI script.

    Type execfile('xxx.auto') to run the script xxx.auto, keeping
    all local state."""
        if name is None:
            automain()
            return
        oldname = self.execfilename
        try:
            lines = open(name, "r")
        except IOError:
            if oldname is None:
                # to give a simple message for "auto notexists.auto".
                try:
                    raise AUTOExceptions.AUTORuntimeError(sys.exc_info()[1])
                except:
                    self.showtraceback()
                    return
            else:
                raise AUTOExceptions.AUTORuntimeError(sys.exc_info()[1])
        self.execfilename = name
        source = ""
        for line in lines:
            while len(line) > 0 and line[-1] in "\r\n":
                line = line[:-1]
            source = source + self.processShorthand(line) + "\n"
        lines.close()
        self.runsource(source, name, "exec")
        self.execfilename = oldname
Example #2
0
 def _demofile(self, name):
     oldname = self.execfilename
     self.execfilename = name
     try:
         f = open(name, "r")
     except IOError:
         raise AUTOExceptions.AUTORuntimeError(sys.exc_info()[1])
     lines = f.readlines()
     f.close()
     runline = ''
     for line in lines:
         while len(line) > 0 and line[-1] in "\r\n":
             line = line[:-1]
         # we only wait if the current line is not a comment
         if len(line.strip()) > 0 and line.strip()[0] != "#":
             sys.stdout.write(sys.ps1 + line)
             raw_input()
         else:
             sys.stdout.write(line + "\n")
         runline = runline + self.processShorthand(line) + "\n"
         if not self.runsource(runline):
             if self.stopdemo:
                 self.stopdemo = False
                 self.execfilename = oldname
                 raise AUTOExceptions.AUTORuntimeError('Demo interrupted')
             runline = ''
     self.execfilename = oldname
Example #3
0
 def runCommand(self, command=None, solution=None):
     """     This is the most generic interface.  It just takes a string as a command
     and tries to run it. """
     global demo_killed, alarm_demo, demo_max_time
     gc.collect()
     if command is None:
         if not (self.options["command"] is None):
             command = self.options["command"]
         else:
             raise AUTOExceptions.AUTORuntimeError("No command set")
     else:
         self.options["command"] = command
     alarm_demo = self.options["dir"]
     if demo_max_time > 0 and hasattr(signal, "alarm"):
         signal.alarm(demo_max_time)
     if hasattr(os, "times"):
         user_time = os.times()[2]
     command = os.path.expandvars(command)
     if self.options["makefile"] is None and sys.stdout is sys.__stdout__:
         try:
             status = self.__runCommand_noredir(command, solution)
         except KeyboardInterrupt:
             if hasattr(signal, 'SIGINT'):
                 status = -signal.SIGINT
             else:
                 status = 1
         except OSError:
             if hasattr(signal, 'SIGKILL'):
                 status = -signal.SIGKILL
             else:
                 status = 1
     else:
         status = self.__runCommand_redir(command, solution)
     if hasattr(signal, "alarm"):
         signal.alarm(0)
     if hasattr(os, "times"):
         user_time = os.times()[2]
     else:
         user_time = 1.0
     if status != 0:
         # in case of error, write constants to fort.2 to enable
         # easier debugging.
         if solution is not None:
             f = open('fort.2', 'w')
             self.__write_constants_solution(f, solution)
             f.close()
         if status < 0:
             status = abs(status)
             for s in signals:
                 if hasattr(signal, s) and status == getattr(signal, s):
                     raise AUTOExceptions.AUTORuntimeError(signals[s])
             raise AUTOExceptions.AUTORuntimeError("Signal %d\n" % status)
         raise AUTOExceptions.AUTORuntimeError("Error running AUTO")
Example #4
0
    def run(self):
        """Run AUTO.

        Run AUTO from the solution with the given AUTO constants.
        Returns a bifurcation diagram of the result.
        """
        self.__setup()
        solution = self.options["selected_solution"]
        constants = solution.c
        if self.options["makefile"] is None:
            if self.options["auto_dir"] is None:
                if "AUTO_DIR" not in os.environ:
                    raise AUTOExceptions.AUTORuntimeError(
                        "AUTO_DIR not set as option or as environment variable"
                    )
                self.options["auto_dir"] = os.environ["AUTO_DIR"]
            curdir = os.getcwd()
            os.chdir(self.options["dir"])
            if (constants["IRS"]
                    and self.options["selected_solution"].coordnames == []):
                raise AUTOExceptions.AUTORuntimeError(
                    "Restart label IRS=%s not found." % constants["IRS"])
            if "e" not in constants:
                raise AUTOExceptions.AUTORuntimeError(
                    "The equation file argument is missing.")
            equation = constants["e"]
            if self.__make(equation):
                line = "Starting %s ...\n" % equation
                sys.stdout.write(line)
                self.__analyseLog(line)
                for filename in [
                        self.fort7_path, self.fort8_path, self.fort9_path
                ]:
                    if os.path.exists(filename):
                        os.remove(filename)
                command = os.path.join(".", equation + ".exe")
                prefix = os.environ.get("AUTO_COMMAND_PREFIX")
                if prefix is not None:
                    command = " ".join((prefix, command))
                self.runCommand(command, solution)
                if os.path.exists("fort.3"):
                    os.remove("fort.3")
                line = "%s ... done\n" % equation
                sys.stdout.write(line)
            os.chdir(curdir)
        else:
            self.runMakefile()
        self.__outputCommand()
        from auto import bifDiag
        return bifDiag.bifDiag(self.fort7_path, self.fort8_path,
                               self.fort9_path, constants)
Example #5
0
 def __getattr__(self,attr):
     if self.__nodata():
         raise AUTOExceptions.AUTORuntimeError("Solution without data.")
     if not self.__fullyParsed and attr != "__del__":
         self.__readAll()
         return getattr(self,attr)
     raise AttributeError(attr)
Example #6
0
 def config(self, cnf=None, **kw):
     if cnf is None and not kw:
         dct = {}
         for key in self.__optionAliases:
             dct[key] = [key, self.__optionAliases[key]]
         for key in self.__options:
             dct[key] = OptionHandler.config(self, key)
         if self.__baseClass is not None:
             dct.update(self.__baseClass.config(self))
         return dct
     if isinstance(cnf, str):
         cnf = self.__applyOptionAliases(cnf)
         if cnf in self.__options:
             return (cnf, cnf, cnf, self.__optionDefaults[cnf],
                     self.__options[cnf], self.__optionRC[cnf])
         if self.__baseClass is None:
             raise AUTOExceptions.AUTORuntimeError("Option %s not found" %
                                                   cnf)
         return self.__baseClass.config(self, cnf)
     dct = (cnf or {}).copy()
     dct.update(kw)
     self.__parseOptions(dct)
     if self.__baseClass is not None:
         for k in list(dct):
             if k not in self.__baseClass.keys(self):
                 del dct[k]
         self.__baseClass.config(self, **dct)
Example #7
0
 def cget(self, key):
     newkey = self.__applyOptionAliases(key)
     if newkey in self.__options:
         return self.__options[newkey]
     else:
         if self.__baseClass is None:
             raise AUTOExceptions.AUTORuntimeError("Option %s not found" %
                                                   key)
         else:
             return self.__baseClass.cget(self, key)
Example #8
0
 def __outputCommand(self):
     # Check to see if output files were created.
     # If not, there must have been an error
     if (not os.path.isfile(self.fort7_path)
             or os.path.getsize(self.fort7_path) == 0
             or not os.path.isfile(self.fort8_path)
             or not os.path.isfile(self.fort9_path)):
         f = open('fort.2', 'w')
         self.__write_constants_solution(f,
                                         self.options["selected_solution"])
         f.close()
         raise AUTOExceptions.AUTORuntimeError("Error running AUTO")
Example #9
0
 def __setitem__(self,key,value):
     if (type(key) == type("") and not key in self.coordnames and
         key != self.indepvarname and not key in self.__parnames):
         shortkey = self.long_data_keys.get(key,key)
         if shortkey in self.data_keys:
             if shortkey == "TY":
                 value = parseB.reverse_type_translation(value)
                 shortkey = "TY number"
             elif shortkey == "BR":
                 self._mbr = 0
             elif shortkey == "LAB":
                 self._mlab = 0
             self.data[shortkey] = value
             return
         if shortkey == "PAR":
             if type(value) == type({}):
                 value = value.items()
             for k,v in value:
                 if isinstance(k,str):
                     self.PAR[k] = v
                 else:
                     self.PAR[k-1] = v
             return
         if shortkey == "p":
             self.PAR = AUTOParameters(coordnames=self.__parnames,
                                       coordarray=value, name=self.name)
             return
         if shortkey == "U":
             if type(value) == type({}):
                 value = value.items()
             for i,(k,v) in enumerate(value):
                 if isinstance(k,str):
                     value[i] = self.coordnames.index(k)
             if len(self.coordarray[0]) > 1:
                 # reduce solution to one point
                 del self.coordarray
                 del self.indepvararray
                 self.coordarray = Points.N.array([[0.0]]*max(dict(value)))
                 self.indepvararray = Points.N.array([0.0])
                 self.data.update({"NTST": 1, "NCOL": 0})
                 del self.data["Active ICP"]
                 del self.data["rldot"]
                 del self.data["udotps"]
             for k,v in value:
                 self.coordarray[k-1,0] = v
             return
     try:
         Points.Pointset.__setitem__(self,key,value)
     except (TypeError, ValueError, KeyError, IndexError):
         if self.__nodata():
             raise AUTOExceptions.AUTORuntimeError("Unknown option: %s"%key)
         self.PAR[key] = value
Example #10
0
 def __make(self, equation, fcon=False):
     var = self.__getmakevars()
     # figure out equation file name
     src = ""
     for ext in [".f90", ".f", ".c"]:
         if os.path.exists(equation + ext):
             src = equation + ext
     if src == "":
         raise AUTOExceptions.AUTORuntimeError(
             "Neither the equation file %s.f90, nor %s.f, nor %s.c exists."
             % (equation, equation, equation))
     # compile
     if not os.path.exists(equation + '.o') or self.__newer(
         [src], equation + '.o'):
         if src[-1] == 'c':
             cmd = "%s %s %s -c %s -o %s.o" % (var["CC"], var["CFLAGS"],
                                               var["OPT"], src, equation)
         else:
             cmd = "%s %s %s -c %s -o %s.o" % (var["FC"], var["FFLAGS"],
                                               var["OPT"], src, equation)
         sys.stdout.write(cmd + "\n")
         self.runCommand(cmd)
     # link
     auto_dir = self.options["auto_dir"]
     libdir = os.path.join(auto_dir, "lib")
     if fcon:
         srcdir = os.path.join(auto_dir, "src")
         incdir = os.path.join(auto_dir, "include")
         libs = os.path.join(srcdir, "fcon.f")
         deps = [libs] + [os.path.join(incdir, "fcon.h")]
         var["FFLAGS"] = var["FFLAGS"] + " -I" + incdir.replace(" ", "\\ ")
         execfile = "fcon"
     else:
         libs = os.path.join(libdir, "*.o")
         deps = glob.glob(libs) + [equation + '.o']
         execfile = equation + ".exe"
     if not os.path.exists(execfile) or self.__newer(deps, execfile):
         if src[-1] == 'c':
             cmd = '%s -L%s %s %s %s.o -o %s %s -lauto_c' % (
                 var["FC"], libdir.replace(" ", "\\ "), var["FFLAGS"],
                 var["OPT"], equation, execfile, libs)
         else:
             cmd = "%s %s %s %s.o -o %s %s" % (var["FC"], var["FFLAGS"],
                                               var["OPT"], equation,
                                               execfile, libs)
         sys.stdout.write(cmd + "\n")
         cmd = cmd.replace(
             libs, " ".join([x.replace(" ", "\\ ") for x in deps[:-1]]))
         self.runCommand(cmd)
     return os.path.exists(equation + '.exe') and not self.__newer(
         deps, equation + '.exe')
Example #11
0
    def runMakefile(self, equation=None):
        """     This function expects self.options["dir"] to be a directory with a Makefile in it and
        a equation file all ready to run (i.e. the Makefile does all of the work,
        like with the demos).  Basically it runs:
        cd dir
        make equation"""
        if equation is None:
            if not (self.options["equation"] is None):
                equation = self.options["equation"]
            else:
                raise AUTOExceptions.AUTORuntimeError("No equation set")
        else:
            self.options["equation"] = equation

        if self.options["auto_dir"] is None:
            if "AUTO_DIR" in os.environ:
                self.options["auto_dir"] = os.environ["AUTO_DIR"]
            else:
                raise AUTOExceptions.AUTORuntimeError(
                    "AUTO_DIR not set as option or as environment variable")

        if self.options["makefile"] == "$AUTO_DIR/cmds/cmds.make fcon":
            self.__make(equation, fcon=True)
        else:
            if self.options["makefile"] == "":
                executable = (
                    "make -e %s AUTO_DIR=%s" %
                    (self.options["equation"], self.options["auto_dir"]))
            else:
                executable = (
                    "make -f %s -e %s AUTO_DIR=%s" %
                    (self.options["makefile"], self.options["equation"],
                     self.options["auto_dir"]))
            path = os.environ["PATH"]
            os.environ["PATH"] = path + os.pathsep + "."
            self.runExecutable(executable)
            os.environ["PATH"] = path
Example #12
0
 def update(self, d=None, **kw):
     """     Change the options for this parseC object"""
     dct = d
     if dct is None:
         dct = {}
     dct.update(kw)
     for key in dct:
         value = dct[key]
         if self.get("homcont") is not None and key in self["homcont"]:
             self["homcont"][key] = value
         elif key in self or key in self.special_keys:
             self[key] = value
         elif key[:7] != 'Active ':
             raise AUTOExceptions.AUTORuntimeError(
                 "Unknown option: %s"%(key,))
Example #13
0
 def __setitem__(self, i, v):
     base, strides, shape = self.__subarray(i)
     if len(strides) == 0:
         self.data[base] = v
     elif len(strides) == 1:
         stop = base + strides[0] * shape[0]
         if stop < 0:
             stop = None
         if isinstance(v, array):
             self.data[base:stop:strides[0]] = v._arrayslice()
         else:
             self.data[base:stop:strides[0]] = N.array(self.typecode, v)
     else:
         raise AUTOExceptions.AUTORuntimeError("2D updates only "
                                               "supported with numpy.")
Example #14
0
    def runExecutable(self, executable=None):
        """     This function expects self.options["dir"] to be a directory with an executable in it and
        a equation file all ready to run.
        Basically it runs:
        cd dir
        executable"""
        if executable is None:
            if not (self.options["executable"] is None):
                executable = self.options["executable"]
            else:
                raise AUTOExceptions.AUTORuntimeError("No executable set")
        else:
            self.options["executable"] = executable

        curdir = os.getcwd()
        os.chdir(self.options["dir"])
        self.runCommand(executable)
        os.chdir(curdir)
Example #15
0
 def load(self,**kw):
     """Load solution with the given AUTO constants.
     Returns a shallow copy with a copied set of updated constants
     """
     irs = kw.get("IRS")
     if irs is None:
         irs = (kw.get("constants") or {}).get("IRS")
     sol = None
     if irs is not None:
         if irs != 0:
             try:    
                 sol = self(irs)
             except KeyError:
                 pass
     elif len(self) > 0:
         sol = self[-1]
     else:
         raise AUTOExceptions.AUTORuntimeError(
             "Cannot start from empty solution list.")
     if sol is None:
         sol = AUTOSolution()
     return sol.load(**kw)
Example #16
0
 def getLabel(self,label):
     if label is None:
         return self
     if isinstance(label, int):
         for d in self:
             if d["Label"] == label:
                 return d
         raise KeyError("Label %s not found"%label)
     if isinstance(label, str) and len(label) > 2 and label[-1].isdigit():
         j = 2
         if not label[2].isdigit():
             j = 3
         number = int(label[j:])
         i = 0
         for d in self:
             if d["Type name"] == label[:j]:
                 i = i + 1
                 if i == number:
                     return d
         raise KeyError("Label %s not found"%label)
     if isinstance(label, types.FunctionType):
         # accept a user-defined boolean function
         f = label
         cnt = getattr(f,"func_code",getattr(f,"__code__",None)).co_argcount
         if cnt == 1:
             # function takes just one parameter
             s = [s for s in self if f(s)]
         elif cnt == 2:
             # function takes two parameters: compare all solutions
             # with each other
             indices = set([])
             for i1, s1 in enumerate(self):
                 if i1 in indices:
                     continue
                 for i2 in range(i1+1,len(self)):
                     if i2 not in indices and f(s1, self[i2]):
                         indices.add(i2)
             s = [self[i] for i in sorted(indices)]
         else:
             raise AUTOExceptions.AUTORuntimeError(
                 "Invalid number of arguments for %s."%f.__name__)
         return self.__class__(s)
     if not AUTOutil.isiterable(label):
         label = [label]
     data = []
     counts = [0]*len(label)
     for d in self:
         ap = None
         if d["Label"] in label or d["Type name"] in label:
             ap = d
         for i in range(len(label)):
             lab = label[i]
             j = 2
             if len(lab) > 2 and not lab[2].isdigit():
                 j = 3
             if (isinstance(lab, str) and len(lab) > j and
                 d["Type name"] == lab[:j]):
                 counts[i] = counts[i] + 1
                 if counts[i] == int(lab[j:]):
                     ap = d
         if ap is not None:
             data.append(ap)
     return self.__class__(data)
Example #17
0
 def __realinit(self, fort7_filename, fort8_filename, fort9_filename,
                constants):
     ioerrors = []
     try:
         parseB.parseBR.__init__(self, fort7_filename)
         for i, d in enumerate(self):
             self[i] = bifDiagBranch(d)
     except IOError:
         ioerrors.append(str(sys.exc_info()[1]))
         parseB.parseBR.__init__(self)
         fort7_filename = None
     if isinstance(fort8_filename, parseS.AUTOSolution):
         fort8_filename = [fort8_filename]
     try:
         solution = parseS.parseS(fort8_filename)
     except IOError:
         ioerrors.append(str(sys.exc_info()[1]))
         solution = None
         if fort7_filename is None:
             raise AUTOExceptions.AUTORuntimeError('\n'.join(ioerrors))
     if fort7_filename is None and fort8_filename is not None:
         # simulate a bifurcation diagram
         labels = {}
         for s in solution:
             br = s["Branch number"]
             if labels == {} or br != branch.BR:
                 if labels != {}:
                     branch.labels = Points.PointInfo(labels)
                 branch = bifDiagBranch()
                 self.append(branch)
                 branch.BR = br
                 branch.coordarray = []
                 branch.coordnames = []
                 branch.headernames = []
                 branch.headerlist = []
                 branch.c = constants
                 labels = {}
                 base = 0
                 i = 0
             pt = s["PT"]
             lab = s["LAB"]
             ty = s["TY number"]
             if i >= base + pt - 1:
                 # point numbers wrapped around
                 base += 9999
             i = base + pt - 1
             labels[i] = {s["TY"]: {"LAB": lab, "TY number": ty, "PT": pt}}
         if labels != {}:
             branch.labels = Points.PointInfo(labels)
     if fort9_filename is not None and self.data != []:
         try:
             # for now just attach diagnostics information to first branch
             self[0].diagnostics = parseD.parseD(fort9_filename)
         except IOError:
             pass
     i = 0
     if solution is not None:
         for d in self:
             if constants is None and d.c is not None:
                 constants = d.c
             constants = parseC.parseC(constants)
             for k in constants:
                 if k in self.nonekeys:
                     constants[k] = None
             for ind in d.labels.getIndices():
                 if i >= len(solution):
                     break
                 x = d._gettypelabel(ind)[1]
                 s = solution[i]
                 if x.get("LAB", 0) != 0 or s["LAB"] == 0:
                     i = i + 1
                     s = x["solution"] = parseS.AUTOSolution(
                         s, constants=constants)
                     if d.coordnames != []:
                         s.b = d[ind]
Example #18
0
    def runDemo(self, d):
        """     This function compiles the demo, then calls the runMakefile
        method, and then cleans up"""
        global demo_killed

        # Garbage collect just before the run to make sure we're not
        # running out of memory quickly.
        gc.collect()
        if self.options["auto_dir"] is None:
            if "AUTO_DIR" in os.environ:
                self.options["auto_dir"] = os.environ["AUTO_DIR"]
            else:
                raise AUTOExceptions.AUTORuntimeError(
                    "AUTO_DIR not set as option or as environment variable")

        if self.options["demos_dir"] is None:
            self.options["demos_dir"] = os.path.join(self.options["auto_dir"],
                                                     "demos")
        self.options["dir"] = os.path.join(self.options["demos_dir"], d)

        var = self.__getmakevars()
        var["FFLAGS"] = var["FFLAGS"] + " " + var["OPT"]
        var["CFLAGS"] = var["CFLAGS"] + " " + var["OPT"]
        del var["OPT"]
        for envvar in var:
            os.environ[envvar] = var[envvar]
        sys.stderr.write("===%s start===\n" % (d, ))
        curdir = os.getcwd()
        os.chdir(self.options["dir"])
        if os.path.exists(d + ".exe"):
            os.remove(d + ".exe")
        cmd = "make -e %s.exe AUTO_DIR=%s" % (d, self.options["auto_dir"])
        if "subprocess" in sys.modules:
            p = self.__popen(cmd.split(), stderr=subprocess.PIPE)
            stdout, stderr = p.stdout, p.stderr
        else:
            stdout, stdin, stderr = popen2.popen3(cmd)
            stdin.close()

        sys.stdout.write(stdout.read())
        sys.stderr.write(stderr.read())
        stdout.close()
        stderr.close()

        self.runMakefile()

        if self.options["clean"] == "yes":
            os.chdir(self.options["dir"])
            cmd = "make -e clean"
            if "subprocess" in sys.modules:
                p = self.__popen(cmd.split(), stderr=subprocess.PIPE)
                stdout, stderr = p.stdout, p.stderr
            else:
                stdout, stdin, stderr = popen2.popen3(cmd)
                stdin.close()
            sys.stdout.write(stdout.read())
            sys.stderr.write(stderr.read())
            stdout.close()
            stderr.close()
        os.chdir(curdir)

        if demo_killed != 0:
            sys.stdout.write(
                "***Demo was killed because it took too long***\n")
            sys.stderr.write(
                "***Demo was killed because it took too long***\n")

        sys.stderr.write("===%s end===\n" % (d, ))
Example #19
0
 def parseline(self, line, userspec=False, inputfile=None, lineno=None):
     # parses a new-style constant file line and puts the keys
     # in the dictionary c; also used for the header of a b. file
     while line != "":
         line = line.strip()
         if line[0] in ['#', '!', '_']:
             return
         pos = line.find('=')
         if pos == -1:
             return
         key = line[:pos].strip()
         value, line = self.scanvalue(line[pos+1:],inputfile)
         if key in ['ICP', 'IREV', 'IFIXED', 'IPSI']:
             d = []
             for v in value:
                 try:
                     v = int(v)
                 except ValueError:
                     pass
                 d.append(v)
             value = d
         elif key in ['THU', 'THL', 'UZR', 'UZSTOP', 'U', 'PAR']:
             d = []
             i = 0
             while i < len(value):
                 try:
                     v0 = int(value[i])
                 except ValueError:
                     v0 = value[i]
                 if value[i+1] == '[':
                     i = i + 1
                     v1 = []
                     while i+1 < len(value) and value[i+1] != ']':
                         v1.append(parseB.AUTOatof(value[i+1]))
                         i = i + 1
                 else:
                     v1 = parseB.AUTOatof(value[i+1])
                 d.append([v0,v1])
                 i = i + 2
             value = self.__compactindexed(d)
         elif key in ['unames', 'parnames']:
             value = [[int(value[i]),value[i+1]] 
                      for i in range(0,len(value),2)]
         elif key in ['s', 'dat', 'sv', 'e', 'SP', 'STOP', 'TY']:
             pass
         elif key in self:
             if key[0] in 'IJKLMN':
                 if value[0] == '*':
                     value = 10**len(value)
                 elif key == 'IRS':
                     try:
                         value = int(value)
                     except ValueError:
                         pass
                 else:
                     value = int(value)
             else:
                 value=parseB.AUTOatof(value)
         elif lineno is not None:
             raise AUTOExceptions.AUTORuntimeError(
                 "Unknown AUTO constant %s on line %d"%(key,lineno))
         else:
             value = None
         if value is not None:
             if userspec:
                 self["Active "+key] = self[key]
             self[key] = value