Debian Codegraph @

07p/python/auto/runAUTO.py

raw symbols SCIP
1 #! /usr/bin/env python
2 import getopt,sys,os
3 import signal
4 try:
5 from cStringIO import StringIO
6 except ImportError: # Python 3
7 from io import StringIO
8 import re
9 import glob
10 from auto import AUTOExceptions,parseC,parseS
11 import gc
12 try:
13 import subprocess
14 except ImportError:
15 import popen2
16 import shlex
17
18 # A few global variables for the signal handler
19 alarm_demo=""
20 demo_killed=0
21 demo_max_time=-1
22
23 signals = {
24 "SIGHUP": "Hangup",
25 "SIGINT": "Interrupt",
26 "SIGQUIT": "Quit",
27 "SIGILL": "Illegal instruction",
28 "SIGTRAP": "Trace/breakpoint trap",
29 "SIGABRT": "Aborted",
30 "SIGBUS": "Bus error",
31 "SIGFPE": "Floating point exception",
32 "SIGKILL": "Killed",
33 "SIGUSR1": "User defined signal 1",
34 "SIGSEGV": "Segmentation fault",
35 "SIGUSR2": "User defined signal 2",
36 "SIGPIPE": "Broken pipe",
37 "SIGALRM": "Alarm clock",
38 "SIGTERM": "Terminated",
39 "SIGSTKFLT": "Stack fault",
40 "SIGCHLD": "Child exited",
41 "SIGCONT": "Continued",
42 "SIGSTOP": "Stopped (signal)",
43 "SIGTSTP": "Stopped",
44 "SIGTTIN": "Stopped (tty input)",
45 "SIGTTOU": "Stopped (tty output)",
46 "SIGURG": "Urgent I/O condition",
47 "SIGXCPU": "CPU time limit exceeded",
48 "SIGXFSZ": "File size limit exceeded",
49 "SIGVTALRM": "Virtual timer expired",
50 "SIGPROF": "Profiling timer expired",
51 "SIGWINCH": "Window changed",
52 "SIGIO": "I/O possible",
53 "SIGPWR": "Power failure",
54 "SIGSYS": "Bad system call"
55 }
56
57 class runAUTO:
58 def __init__(self,**kw):
59 # Set the signal handler
60 if hasattr(signal,'SIGALRM') and demo_max_time > 0:
61 signal.signal(signal.SIGALRM, self.__handler)
62
63 self.options={}
64 self.options["log"] = None
65 self.options["err"] = None
66 self.options["auto_dir"] = None
67 self.options["demos_dir"] = None
68 self.options["equation"] = "all"
69 self.options["verbose"] = "yes" # note: this is ignored!
70 self.options["clean"] = "no"
71 self.options["dir"] = "."
72 self.options["executable"] = None
73 self.options["command"] = None
74 self.options["makefile"] = None
75 self.options["constants"] = parseC.parseC()
76 self.options["solution"] = parseS.AUTOSolution()
77 self.options["homcont"] = None
78 self.options["selected_solution"] = None
79
80 kw = self.config(**kw)
81
82 def config(self,**kw):
83 """ Change the options for this runner object"""
84 # first the normal parameters, then IRS=... style parameters
85 for key in self.options:
86 if key in kw:
87 value = kw[key]
88 del kw[key]
89 if key == 'log':
90 if self.options[key] is None:
91 self.stdout = sys.stdout
92 sys.stdout = value or self.stdout
93 elif key == 'err':
94 if self.options[key] is None:
95 self.stderr = sys.stderr
96 sys.stderr = value or self.stderr
97 elif key == 'constants':
98 # do not completely replace existing constants data but
99 # leave the special keys such as unames, parnames, etc,
100 # intact
101 self.options[key].update(value)
102 value = self.options[key]
103 elif key == 'solution' and not hasattr(value, "load"):
104 t=kw.get('t')
105 if "t" in kw and value is not None:
106 del kw["t"]
107 value = parseS.AUTOSolution(value,t=t)
108 self.options[key] = value
109
110 self.options["constants"].update(**kw)
111
112 def __analyseLog(self,text):
113 # now we also want to look at the log information to try and determine
114 # where the data was written to
115 files = ["fort.7", "fort.8", "fort.9"]
116 v = self.options["constants"].get("sv")
117 if v is None:
118 value = re.findall("(Saved as|Appended to) \*\.(\w*)",text)
119 if len(value):
120 v = value[-1][1]
121 if v is not None:
122 files = ["b."+v, "s."+v, "d."+v]
123 # return as the output data the last filename which was
124 # either saved or appended to or
125 # otherwise we assume it is fort.7 and fort.8
126 self.fort7_path = os.path.join(self.options["dir"],files[0])
127 self.fort8_path = os.path.join(self.options["dir"],files[1])
128 self.fort9_path = os.path.join(self.options["dir"],files[2])
129
130 def __popen(self,args,stdin=None,stderr=None):
131 # subprocess.Popen wrapper:
132 return subprocess.Popen(args, stdin=stdin, stdout=subprocess.PIPE,
133 stderr=stderr, bufsize=1,
134 universal_newlines=True)
135
136 def __handler(self, signum, frame):
137 global demo_killed,alarm_demo,demo_max_time
138 sys.stdout.write('Demo taking too long: '+alarm_demo+'\n')
139 sys.stdout.write('Finding processes to kill...\n')
140 if "subprocess" in sys.modules:
141 p1 = self.__popen(["ps","ww"])
142 p2 = self.__popen(["grep",alarm_demo+".exe"], p1.stdout)
143 p3 = self.__popen(["grep","-v","grep"], p2.stdout)
144 pids = p3.communicate()[0]
145 p1.stdout.close()
146 p2.stdout.close()
147 else:
148 cout,cin = popen2.popen2(
149 "ps ww | grep %s.exe | grep -v grep"%(alarm_demo,))
150 cin.close()
151 pids = cout.read()
152 cout.close()
153 pids = pids.splitlines()
154 for pid in pids:
155 sys.stdout.write('Killing: %s\n'%pid)
156 pid = pid.split()
157 pid = int(pid[0])
158 command = "/bin/kill -KILL %d\n"%(pid,)
159 sys.stdout.write(command)
160 if hasattr(os,"kill"):
161 os.kill(pid,signal.SIGKILL)
162 else:
163 os.system("sh -c '%s'"%command)
164 sys.stdout.flush()
165 # Restart the alarm to make sure everything gets killed
166 if hasattr(signal,"alarm"):
167 signal.alarm(20)
168
169 def runDemo(self,d):
170 """ This function compiles the demo, then calls the runMakefile
171 method, and then cleans up"""
172 global demo_killed
173
174 # Garbage collect just before the run to make sure we're not
175 # running out of memory quickly.
176 gc.collect()
177 if self.options["auto_dir"] is None:
178 if "AUTO_DIR" in os.environ:
179 self.options["auto_dir"]=os.environ["AUTO_DIR"]
180 else:
181 raise AUTOExceptions.AUTORuntimeError("AUTO_DIR not set as option or as environment variable")
182
183 if self.options["demos_dir"] is None:
184 self.options["demos_dir"] = os.path.join(self.options["auto_dir"],
185 "demos")
186 self.options["dir"] = os.path.join(self.options["demos_dir"],d)
187
188 var = self.__getmakevars()
189 var["FFLAGS"] = var["FFLAGS"] + " " + var["OPT"]
190 var["CFLAGS"] = var["CFLAGS"] + " " + var["OPT"]
191 del var["OPT"]
192 for envvar in var:
193 os.environ[envvar] = var[envvar]
194 sys.stderr.write("===%s start===\n"%(d,))
195 curdir = os.getcwd()
196 os.chdir(self.options["dir"])
197 if os.path.exists(d+".exe"):
198 os.remove(d+".exe")
199 cmd = "make -e %s.exe AUTO_DIR=%s"%(d,self.options["auto_dir"])
200 if "subprocess" in sys.modules:
201 p = self.__popen(cmd.split(), stderr=subprocess.PIPE)
202 stdout,stderr = p.stdout,p.stderr
203 else:
204 stdout,stdin,stderr = popen2.popen3(cmd)
205 stdin.close()
206
207 sys.stdout.write(stdout.read())
208 sys.stderr.write(stderr.read())
209 stdout.close()
210 stderr.close()
211
212 self.runMakefile()
213
214 if self.options["clean"] == "yes":
215 os.chdir(self.options["dir"])
216 cmd = "make -e clean"
217 if "subprocess" in sys.modules:
218 p = self.__popen(cmd.split(), stderr=subprocess.PIPE)
219 stdout,stderr = p.stdout,p.stderr
220 else:
221 stdout,stdin,stderr = popen2.popen3(cmd)
222 stdin.close()
223 sys.stdout.write(stdout.read())
224 sys.stderr.write(stderr.read())
225 stdout.close()
226 stderr.close()
227 os.chdir(curdir)
228
229 if demo_killed != 0:
230 sys.stdout.write("***Demo was killed because it took too long***\n")
231 sys.stderr.write("***Demo was killed because it took too long***\n")
232
233 sys.stderr.write("===%s end===\n"%(d,))
234
235 def __setup(self):
236 """ This function sets up self.options["dir"] by possibly
237 creating the fort.12 file. The "constants", "solution",
238 and "homcont" options
239 can be anything with a writeFilename method. NOTE: The
240 values set here will often be overridden by
241 runMakefile (thought almost never by runExecutable
242 or runCommand)"""
243 solution = self.options["selected_solution"]
244 constants = solution.c
245 if os.path.exists("fort.2"):
246 os.remove("fort.2")
247 if os.path.exists("fort.3"):
248 os.remove("fort.3")
249 if constants["homcont"] is not None:
250 constants["homcont"].writeFilename("fort.12")
251 elif os.path.exists("fort.12"):
252 os.remove("fort.12")
253
254 def __newer(self,sources,target):
255 targettime = os.stat(target).st_mtime
256 for src in sources:
257 if os.stat(src).st_mtime > targettime:
258 return True
259 return False
260
261 def __getmakevars(self):
262 # do the same as $AUTO_DIR/cmds/cmds.make but in Python
263 # first get the configure-set variables
264 auto_dir = self.options["auto_dir"]
265 f = open(os.path.join(auto_dir,"cmds","cmds.make"),"r")
266 var = {}
267 for line in f:
268 line = line.split()
269 if len(line) < 2 or line[1] != '=':
270 continue
271 if line[0] == "SRC":
272 break
273 for key in ["CC","FC","CFLAGS","FFLAGS","OPT"]:
274 if line[0] == key:
275 if len(line) == 2:
276 v = ""
277 else:
278 v = " ".join(line[2:])
279 v = v.replace("$(AUTO_DIR)",auto_dir)
280 var[key] = v
281 f.close()
282 return var
283
284 def __make(self,equation,fcon=False):
285 var = self.__getmakevars()
286 # figure out equation file name
287 src = ""
288 for ext in [".f90",".f",".c"]:
289 if os.path.exists(equation+ext):
290 src = equation+ext
291 if src == "":
292 raise AUTOExceptions.AUTORuntimeError(
293 "Neither the equation file %s.f90, nor %s.f, nor %s.c exists."%(
294 equation,equation,equation))
295 # compile
296 if not os.path.exists(equation+'.o') or self.__newer([src],
297 equation+'.o'):
298 if src[-1] == 'c':
299 cmd = "%s %s %s -c %s -o %s.o"%(var["CC"],var["CFLAGS"],
300 var["OPT"],src,equation)
301 else:
302 cmd = "%s %s %s -c %s -o %s.o"%(var["FC"],var["FFLAGS"],
303 var["OPT"],src,equation)
304 sys.stdout.write(cmd+"\n")
305 self.runCommand(cmd)
306 # link
307 auto_dir = self.options["auto_dir"]
308 libdir = os.path.join(auto_dir,"lib")
309 if fcon:
310 srcdir = os.path.join(auto_dir,"src")
311 incdir = os.path.join(auto_dir,"include")
312 libs = os.path.join(srcdir,"fcon.f")
313 deps = [libs] + [os.path.join(incdir,"fcon.h")]
314 var["FFLAGS"] = var["FFLAGS"] + " -I" + incdir.replace(" ","\\ ")
315 execfile = "fcon"
316 else:
317 libs = os.path.join(libdir,"*.o")
318 deps = glob.glob(libs) + [equation+'.o']
319 execfile = equation + ".exe"
320 if not os.path.exists(execfile) or self.__newer(deps,execfile):
321 if src[-1] == 'c':
322 cmd = '%s -L%s %s %s %s.o -o %s %s -lauto_c'%(var["FC"],libdir.replace(" ","\\ "),
323 var["FFLAGS"],var["OPT"],equation,execfile,libs)
324 else:
325 cmd = "%s %s %s %s.o -o %s %s"%(var["FC"],var["FFLAGS"],var["OPT"],
326 equation,execfile,libs)
327 sys.stdout.write(cmd+"\n")
328 cmd = cmd.replace(libs, " ".join([x.replace(" ","\\ ") for x in deps[:-1]]))
329 self.runCommand(cmd)
330 return os.path.exists(equation+'.exe') and not self.__newer(deps,equation+'.exe')
331
332 def load(self,**kw):
333 """Load solution with the given AUTO constants.
334 Returns a shallow copy with a copied set of updated constants
335 """
336 self.config(**kw)
337 ret = self.options["solution"].load(constants=self.options["constants"],
338 homcont=self.options["homcont"])
339 self.options["selected_solution"] = ret
340 return ret
341
342 def run(self):
343 """Run AUTO.
344
345 Run AUTO from the solution with the given AUTO constants.
346 Returns a bifurcation diagram of the result.
347 """
348 self.__setup()
349 solution = self.options["selected_solution"]
350 constants = solution.c
351 if self.options["makefile"] is None:
352 if self.options["auto_dir"] is None:
353 if "AUTO_DIR" not in os.environ:
354 raise AUTOExceptions.AUTORuntimeError(
355 "AUTO_DIR not set as option or as environment variable")
356 self.options["auto_dir"]=os.environ["AUTO_DIR"]
357 curdir = os.getcwd()
358 os.chdir(self.options["dir"])
359 if (constants["IRS"] and
360 self.options["selected_solution"].coordnames == []):
361 raise AUTOExceptions.AUTORuntimeError(
362 "Restart label IRS=%s not found."%constants["IRS"])
363 if "e" not in constants:
364 raise AUTOExceptions.AUTORuntimeError(
365 "The equation file argument is missing.")
366 equation = constants["e"]
367 if self.__make(equation):
368 line = "Starting %s ...\n"%equation
369 sys.stdout.write(line)
370 self.__analyseLog(line)
371 for filename in [self.fort7_path,self.fort8_path,
372 self.fort9_path]:
373 if os.path.exists(filename):
374 os.remove(filename)
375 command = os.path.join(".",equation + ".exe")
376 prefix = os.environ.get("AUTO_COMMAND_PREFIX")
377 if prefix is not None:
378 command = " ".join((prefix, command))
379 self.runCommand(command, solution)
380 if os.path.exists("fort.3"):
381 os.remove("fort.3")
382 line = "%s ... done\n"%equation
383 sys.stdout.write(line)
384 os.chdir(curdir)
385 else:
386 self.runMakefile()
387 self.__outputCommand()
388 from auto import bifDiag
389 return bifDiag.bifDiag(self.fort7_path,self.fort8_path,
390 self.fort9_path,constants)
391
392 def runMakefileWithSetup(self,equation=None):
393 self.__setup()
394 self.runMakefile(equation)
395 self.__outputCommand()
396 def runMakefile(self,equation=None):
397 """ This function expects self.options["dir"] to be a directory with a Makefile in it and
398 a equation file all ready to run (i.e. the Makefile does all of the work,
399 like with the demos). Basically it runs:
400 cd dir
401 make equation"""
402 if equation is None:
403 if not(self.options["equation"] is None):
404 equation = self.options["equation"]
405 else:
406 raise AUTOExceptions.AUTORuntimeError("No equation set")
407 else:
408 self.options["equation"] = equation
409
410 if self.options["auto_dir"] is None:
411 if "AUTO_DIR" in os.environ:
412 self.options["auto_dir"]=os.environ["AUTO_DIR"]
413 else:
414 raise AUTOExceptions.AUTORuntimeError("AUTO_DIR not set as option or as environment variable")
415
416 if self.options["makefile"] == "$AUTO_DIR/cmds/cmds.make fcon":
417 self.__make(equation,fcon=True)
418 else:
419 if self.options["makefile"] == "":
420 executable = ("make -e %s AUTO_DIR=%s"%
421 (self.options["equation"],
422 self.options["auto_dir"]))
423 else:
424 executable = ("make -f %s -e %s AUTO_DIR=%s"%
425 (self.options["makefile"],
426 self.options["equation"],
427 self.options["auto_dir"]))
428 path = os.environ["PATH"]
429 os.environ["PATH"] = path+os.pathsep+"."
430 self.runExecutable(executable)
431 os.environ["PATH"] = path
432
433 def runExecutableWithSetup(self,executable=None):
434 self.__setup()
435 self.runExecutable(executable)
436 self.__outputCommand()
437 def runExecutable(self,executable=None):
438 """ This function expects self.options["dir"] to be a directory with an executable in it and
439 a equation file all ready to run.
440 Basically it runs:
441 cd dir
442 executable"""
443 if executable is None:
444 if not(self.options["executable"] is None):
445 executable = self.options["executable"]
446 else:
447 raise AUTOExceptions.AUTORuntimeError("No executable set")
448 else:
449 self.options["executable"] = executable
450
451 curdir = os.getcwd()
452 os.chdir(self.options["dir"])
453 self.runCommand(executable)
454 os.chdir(curdir)
455
456 def runCommandWithSetup(self,command=None):
457 self.__setup()
458 self.runCommand(command,self.options["selected_solution"])
459 self.__outputCommand()
460 def runCommand(self,command=None,solution=None):
461 """ This is the most generic interface. It just takes a string as a command
462 and tries to run it. """
463 global demo_killed,alarm_demo,demo_max_time
464 gc.collect()
465 if command is None:
466 if not(self.options["command"] is None):
467 command = self.options["command"]
468 else:
469 raise AUTOExceptions.AUTORuntimeError("No command set")
470 else:
471 self.options["command"] = command
472 alarm_demo = self.options["dir"]
473 if demo_max_time > 0 and hasattr(signal,"alarm"):
474 signal.alarm(demo_max_time)
475 if hasattr(os,"times"):
476 user_time = os.times()[2]
477 command = os.path.expandvars(command)
478 if self.options["makefile"] is None and sys.stdout is sys.__stdout__:
479 try:
480 status = self.__runCommand_noredir(command, solution)
481 except KeyboardInterrupt:
482 if hasattr(signal, 'SIGINT'):
483 status = -signal.SIGINT
484 else:
485 status = 1
486 except OSError:
487 if hasattr(signal, 'SIGKILL'):
488 status = -signal.SIGKILL
489 else:
490 status = 1
491 else:
492 status = self.__runCommand_redir(command, solution)
493 if hasattr(signal,"alarm"):
494 signal.alarm(0)
495 if hasattr(os,"times"):
496 user_time = os.times()[2]
497 else:
498 user_time = 1.0
499 if status != 0:
500 # in case of error, write constants to fort.2 to enable
501 # easier debugging.
502 if solution is not None:
503 f = open('fort.2', 'w')
504 self.__write_constants_solution(f, solution)
505 f.close()
506 if status < 0:
507 status = abs(status)
508 for s in signals:
509 if hasattr(signal,s) and status == getattr(signal,s):
510 raise AUTOExceptions.AUTORuntimeError(signals[s])
511 raise AUTOExceptions.AUTORuntimeError("Signal %d\n"%status)
512 raise AUTOExceptions.AUTORuntimeError("Error running AUTO")
513
514 def __write_constants_solution(self, f, solution):
515 solution.c.write(f,new=True)
516 f.write("s='/'\n")
517 if hasattr(f, 'buffer'):
518 f = f.buffer
519 solution.write(f,mlab=True)
520
521 def __runCommand_noredir(self,command,solution=None):
522 sys.stdout.flush()
523 args = shlex.split(os.path.expandvars(command))
524 if solution is None:
525 if "subprocess" in sys.modules:
526 return subprocess.call(args)
527 elif hasattr(os,"spawnlp"):
528 return os.spawnlp(os.P_WAIT, args[0], *args)
529 else:
530 return os.system(command)
531 if "subprocess" in sys.modules:
532 obj = subprocess.Popen(args, stdin=subprocess.PIPE,
533 universal_newlines=True)
534 stdin = obj.stdin
535 else:
536 stdin = os.popen(command, "w")
537 status = 0
538 self.__write_constants_solution(stdin, solution)
539 stdin.close()
540 if "subprocess" in sys.modules:
541 status = obj.wait()
542 return status
543
544 def __runCommand_redir(self,command,solution=None):
545 global demo_killed
546 tmp_out = []
547 if "subprocess" in sys.modules or hasattr(popen2,"Popen3"):
548 # The command runs here.
549 # This is done as the object version so I can use the "poll" method
550 # later on to see if it is still running.
551 if "subprocess" in sys.modules:
552 args = shlex.split(os.path.expandvars(command))
553 demo_object = self.__popen(args, subprocess.PIPE,
554 subprocess.PIPE)
555 stdin, stdout, stderr = (demo_object.stdin, demo_object.stdout,
556 demo_object.stderr)
557 teststatus = None
558 else:
559 demo_object = popen2.Popen3(command,1,1)
560 stdin, stdout, stderr = (demo_object.tochild,
561 demo_object.fromchild, demo_object.childerr)
562 teststatus = -1
563 if solution is not None:
564 self.__write_constants_solution(stdin, solution)
565 stdin.close()
566 status = demo_object.poll()
567 while status == teststatus:
568 try:
569 line = stdout.readline()
570 sys.stdout.write(line)
571 sys.stdout.flush()
572 tmp_out.append(line)
573 except IOError:
574 demo_killed = 1
575 status = demo_object.poll()
576 else:
577 stdout, stdin, stderr = popen2.popen3(command)
578 self.__write_constants_solution(stdin, solution)
579 stdin.close()
580 status = 0
581 line = stdout.readline()
582 # Read the rest of the data from stdout
583 while len(line) > 0:
584 tmp_out.append(line)
585 sys.stdout.write(line)
586 sys.stdout.flush()
587 line = stdout.readline()
588 self.__analyseLog("".join(tmp_out))
589 sys.stderr.write(stderr.read())
590 stdout.close()
591 stderr.close()
592 return status
593
594 def __outputCommand(self):
595 # Check to see if output files were created.
596 # If not, there must have been an error
597 if (not os.path.isfile(self.fort7_path) or
598 os.path.getsize(self.fort7_path) == 0 or
599 not os.path.isfile(self.fort8_path) or
600 not os.path.isfile(self.fort9_path)):
601 f = open('fort.2', 'w')
602 self.__write_constants_solution(f,
603 self.options["selected_solution"])
604 f.close()
605 raise AUTOExceptions.AUTORuntimeError("Error running AUTO")
606
607 def test():
608 log = StringIO()
609 stdout = sys.stdout
610 class teeStringIO(object):
611 def write(self,s):
612 stdout.write(s)
613 log.write(s)
614 def flush(self):
615 stdout.flush()
616 class quiet(object):
617 def write(self,s): pass
618 def flush(self): pass
619 runner = runAUTO(clean="yes",log=teeStringIO(),err=quiet(),
620 makefile="",
621 demos_dir=os.path.join(os.environ["AUTO_DIR"],"python"))
622 runner.runDemo("wav")
623 stdout.write(log.getvalue()+"\n")
624 log.truncate(0)
625 runner.config(equation="clean",log=log)
626 runner.runDemo("wav")
627 stdout.write(log.getvalue()+"\n")
628 log.truncate(0)
629 runner.config(equation="first")
630 runner.runDemo("wav")
631 stdout.write(log.getvalue()+"\n")
632 runner.config(log=None, err=None)
633
634
635 if __name__ == "__main__":
636 #Parse command line arguements
637 opts_list,args=getopt.getopt(sys.argv[1:],"l:")
638 opts={}
639 for x in opts_list:
640 opts[x[0]]=x[1]
641 log = None
642 err = None
643 if "-l" in opts:
644 log = open(opts["-l"],"w")
645 err = open(opts["-l"]+"errors","w")
646
647 runner = runAUTO()
648 if len(args) == 0:
649 test()
650 if len(args) == 1:
651 runner.runDemo(args[0],log=log,err=err)
652 if len(args) == 2:
653 runner.runDemo(args[0],part=args[1],log=log,err=err)
654
655
656
657