Debian Codegraph @

07p/python/auto/graphics/pyplaut.py

raw symbols SCIP
1 #!/usr/bin/env autox
2 from auto import bifDiag, parseB, AUTOExceptions
3 from auto.graphics import windowPlotter
4 import code
5 import sys
6 try:
7 import Tkinter
8 except ImportError:
9 import tkinter as Tkinter
10 import select
11 try:
12 import termios
13 except ImportError:
14 pass
15 try:
16 import readline
17 except ImportError:
18 pass
19
20 class PyPlautInteractiveConsole(code.InteractiveConsole):
21 def __init__(self,locals=None,b=None,s=None):
22 code.InteractiveConsole.__init__(self,locals)
23 if locals is None:
24 return
25
26 root=Tkinter.Tk()
27 root.withdraw()
28 self.handle = windowPlotter.WindowPlotter2D(root)
29 self.handle.protocol("WM_DELETE_WINDOW", self.destroy)
30 self.orig_destroy = self.handle.destroy
31 self.handle.destroy = self.destroy
32 try:
33 self.tcattr = termios.tcgetattr(sys.stdin.fileno())
34 except:
35 pass
36
37 if sys.platform == "cygwin":
38 try:
39 self.root = root
40 readline.set_pre_input_hook(self.handleevents)
41 except:
42 pass
43
44 #handle default options
45 config = self.handle.configure()
46 doptions = {"grid": ["no", "no", "no", "yes", "yes"],
47 "use_labels": [ 0, 1, 0, 1, 0],
48 "use_symbols":[ 1, 1, 1, 1, 1],
49 "stability": [ 0, 1, 1, 1, 1]}
50 dict = {}
51 for i in range(5):
52 if "d"+str(i) not in config:
53 di = {}
54 for k,v in doptions.items():
55 di[k] = v[i]
56 dict["d"+str(i)] = (di,None)
57 if "default_option" not in config:
58 dict["default_option"] = ("d1",None)
59 self.handle.grapher.addOptions(**dict)
60
61 try:
62 b = parseB.parseBR(b)
63 bd = bifDiag.bifDiag(b,s,constants=b[0].c)
64 except (IOError, AUTOExceptions.AUTORuntimeError):
65 try:
66 bd = bifDiag.bifDiag(b,s)
67 except AUTOExceptions.AUTORuntimeError:
68 sys.stderr.write(str(sys.exc_info()[1])+"\n")
69 self.orig_destroy()
70 sys.exit(1)
71 dict = {
72 "bifurcation_diagram": bd,
73 "solution": bd(),
74 "letter_symbols": False }
75 for k,v in self[self["default_option"]].items():
76 dict[k] = v
77 for key in list(dict):
78 # check if key was set in .autorc
79 config = self.handle.config(key)
80 if len(config) > 5 and config[5]:
81 del dict[key]
82 self.handle.config(**dict)
83 self.defaults = {}
84 for key in ["xlabel", "ylabel", "zlabel", "top_title"]:
85 self.defaults[key] = self.handle.config(key)[3]
86 self.plotdefaults = {}
87 for key in ["top_title", "grid", "stability", "use_symbols",
88 "use_labels"]:
89 self.plotdefaults[key] = self[key]
90 self.normal_usage()
91 self.b3d = False
92
93 # this polling loop is here so that Cygwin Python does not "hang" the
94 # plot window while Python waits for a user input
95 def handleevents(self):
96 while select.select([sys.stdin],[],[],0.02) == ([], [], []):
97 self.root.dooneevent()
98
99 def raw_input(self, prompt=None):
100 line = ""
101 while 1:
102 if line == "":
103 if self.b3d:
104 print(" ENTER <B3D> COMMAND\n")
105 else:
106 print(" ENTER COMMAND\n")
107 line = raw_input(prompt)
108 line = self.process_input(line)
109
110 def destroy(self):
111 self.orig_destroy()
112 try:
113 termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, self.tcattr)
114 except:
115 pass
116 sys.exit()
117
118 def process_input(self, line):
119 lower = 0
120 upper = 0
121 its = 0
122 for c in line:
123 if c.islower():
124 lower = 1
125 if c.isupper():
126 upper = 1
127 if upper and not lower:
128 line=line.lower()
129 if line in ["stop","exit","quit","end"]:
130 if self.b3d:
131 self.b3d = False
132 self["bifurcation_z"] = None
133 return ""
134 self.orig_destroy()
135 sys.exit()
136 elif line in ["scr","screen"]:
137 return ""
138 elif line in ["ss","set sym"]:
139 return ""
140 elif line == "sd":
141 return ""
142 elif line in ["lab","label"]:
143 self.listlabels()
144 return ""
145 elif line in ["c","cl","clr","clear"]:
146 self.handle.grapher.clear()
147 self.handle.grapher.update()
148 return ""
149 elif line in ["save","sav","sa","s"]:
150 self.savefile()
151 return ""
152 elif line == "help":
153 return self.help()
154 elif line in ["sy","sym","symbol"]:
155 self["use_symbols"] = 1
156 return ""
157 opts = []
158 for j in range(6):
159 if len(line) < j*2+2:
160 break
161 opts.append(line[j*2:j*2+2])
162 if "sy" in opts:
163 self["use_symbols"] = 1
164 its = 1
165 if "dp" in opts:
166 self["stability"] = 1
167 its = 1
168 if "ax" in opts:
169 its = 1
170 try:
171 if self.b3d:
172 print(' ENTER THE NEW THREE AXES FOR (X,Y,Z) <B3D>')
173 line = raw_input().replace(","," ")
174 [xaxis,yaxis,zaxis] = map(int,line.split())
175 self["bifurcation_x"] = [xaxis-1]
176 self["bifurcation_y"] = [yaxis-1]
177 self["bifurcation_z"] = [zaxis-1]
178 else:
179 print(' ENTER HORIZONTAL AND VERTICAL AXIS NUMBER (1,2,...) :')
180 line = raw_input().replace(","," ")
181 [xaxis,yaxis] = map(int,line.split())
182 self["bifurcation_x"] = [xaxis-1]
183 self["bifurcation_y"] = [yaxis-1]
184 except:
185 pass
186 if "st" in opts:
187 self.settitles(1,1,1,1)
188 its = 1
189 for i in range(5):
190 dopt = "d"+str(i)
191 if dopt in opts:
192 self.dset = 1
193 self.expert = 0
194 self.handle.config(self[dopt])
195 its = 1
196 if "nu" in opts:
197 its = 1
198 self.handle.config(**self.defaults)
199 self.handle.grapher.addRCOptions(self.defaults)
200 self.normal_usage()
201 self.handle.config(use_symbols=0,use_labels=0,
202 grid="no",stability=0)
203 self.handle.grapher.plot()
204 if "xp" in opts:
205 its = 1
206 self.expert = 1
207 if "bd" in opts:
208 index = opts.index("bd")
209 if 2*index + 2 < len(line):
210 if line[2*index+2] == "0":
211 self.plotbif(0)
212 return ""
213 self.plotbif()
214 return ""
215 elif line[:2] == "2d":
216 self.plotsol()
217 return ""
218 elif line[:2] == "3d":
219 self.plotsol(use3d=True)
220 return ""
221 elif line == "b3d":
222 self.b3d = True
223 return ""
224 elif line == "sda":
225 return ""
226 elif line == "sdo":
227 return ""
228 elif line == "sci":
229 return ""
230 elif line == "ssy":
231 return ""
232 elif line == "pa":
233 return ""
234 elif line == "sdd":
235 return ""
236 elif line == "sls":
237 return ""
238 elif line == "lda":
239 return ""
240 elif line == "us":
241 return ""
242 elif line == "lls":
243 return ""
244 elif line == "rss":
245 return ""
246 elif line == "rcs":
247 return ""
248 elif line == "res":
249 return ""
250 if its == 0:
251 print(' ILLEGAL COMMAND - REENTER')
252 return ""
253
254 def normal_usage(self):
255 self.dset = 1
256 self.expert = 0
257 self.icl = 0
258 self.ict = 0
259 for key in ["xlabel", "ylabel", "zlabel", "top_title"]:
260 setattr(self, key, self.handle.config(key)[3])
261
262 def savefile(self):
263 print(' ENTER FILE NAME:')
264 flname = raw_input().strip()
265 if flname == '':
266 flname = 'fig.1'
267 self.handle.grapher.postscript(flname)
268
269 def settitles(self,tit,rtit,axlb,raxlb):
270 if self.b3d:
271 labels = ["xlabel","ylabel","zlabel"]
272 else:
273 labels = ["xlabel","ylabel"]
274 for key in labels:
275 if axlb:
276 if raxlb:
277 if not self.expert:
278 print (' ENTER '+ key[0].upper() +
279 ' AXIS LABEL BETWEEN THE QUOTES')
280 print(' " "')
281 setattr(self, key, raw_input().strip())
282 label = getattr(self, key)
283 else:
284 label = ""
285 if label is not None:
286 self[key] = label
287 self.handle.grapher.addRCOptions({key:label})
288 if label is None:
289 self.handle.grapher.plot()
290
291 if rtit:
292 if not self.expert:
293 print(' ENTER TOP TITLE BETWEEN THE QUOTES')
294 print(' " "')
295 self.top_title = raw_input().strip()
296
297 #if not self.expert:
298 # print ' ENTER BOTTOM TITLE BETWEEN THE QUOTES'
299 #print ' " "'
300 if tit:
301 self["top_title"] = self.top_title
302 else:
303 self["top_title"] = ""
304 self.handle.grapher.update()
305 #ax.text(0.5,0,raw_input().strip(),transform=ax.transAxes)
306 #self.handle.grapher.canvas.show()
307
308 def listlabels(self):
309 s = self["solution"]
310 i = 0
311 str='\n THE LABELS ARE : '
312 for label in s.getLabels():
313 str=str+"%5d"%(label)
314 i=i+1
315 if i==10:
316 print(str)
317 str=' '
318 i=0
319 if len(str) > 22:
320 print(str)
321
322 def getopts(self):
323 if self.expert:
324 print(' LAB')
325 else:
326 print(' SOLUTION LABELS ? ( <Y> OR <N> ) ')
327 line = raw_input().strip()
328 self["use_labels"] = line[0].lower() == 'y'
329 if self.expert:
330 print(' GL')
331 else:
332 print(' GRID LINES ? (Y OR N)')
333 line = raw_input().strip()
334 if line[0].lower() == 'y':
335 self["grid"] = "yes"
336 else:
337 self["grid"] = "no"
338 tit = 0
339 rtit = 0
340 axlb = 0
341 raxlb = 0
342 if self.expert:
343 print(' T - C')
344 line = raw_input().strip()
345 if len(line) > 0 and line[0].lower() == 'y':
346 tit = 1
347 if len(line) > 1 and line[1].lower() == 'y':
348 rtit = 1
349 print(' A - C')
350 line = raw_input().strip()
351 if len(line) > 0 and line[0].lower() == 'y':
352 axlb = 1
353 if len(line) > 1 and line[1].lower() == 'y':
354 raxlb = 1
355 else:
356 print(' TITLE ? (Y OR N)')
357 line = raw_input().strip()
358 if len(line) > 0 and line[0].lower() == 'y':
359 tit = 1
360 if not self.ict:
361 self.ict = 1
362 rtit = 1
363 else:
364 print(' CHANGE TITLES ? (Y OR N)')
365 line = raw_input().strip()
366 if len(line) > 0 and line[0].lower() == 'y':
367 rtit = 1
368 print(' AXES LABELS ? (Y OR N)')
369 line = raw_input().strip()
370 if len(line) > 0 and line[0].lower() == 'y':
371 axlb = 1
372 if not self.icl:
373 self.icl = 1
374 raxlb = 1
375 else:
376 print(' CHANGE AXES LABELS ? (Y OR N)')
377 line = raw_input().strip()
378 if len(line) > 0 and line[0].lower() == 'y':
379 raxlb = 1
380 self.settitles(tit,rtit,axlb,raxlb)
381
382 def enterlabels(self):
383 self.listlabels()
384 print('\n ENTER LABELS, OR <A> (ALL)\n')
385 line = raw_input().lower()
386 s = self["solution"]
387 if line[0] == 'a':
388 self["label"] = s.getLabels()
389 else:
390 line=line.replace(',',' ')
391 line=line.replace(':','-')
392 lablist = line.replace(',',' ').split()
393 label = []
394 for lab in lablist:
395 try:
396 lrange = map(int,lab.split('-'))
397 except:
398 print(" INVALID COMMAND, REENTER")
399 return 0
400 if len(lrange) == 2:
401 lrange = range(lrange[0],lrange[1]+1)
402 label = label + lrange
403 self["label"] = label
404 return 1
405
406 def plotsol(self,use3d=False):
407 xaxsn = [1]
408 yaxsn = [2]
409 zaxsn = [3]
410
411 self.handle.config(type = "solution")
412 if use3d:
413 self["solution_z"] = [1]
414 if not self.enterlabels():
415 return
416 s = self["solution"]
417 self.ndim=len(s[0]["data"][0]['u'])+1
418 while 1:
419 its = 0
420 print(' NUMBER OF COMPONENTS :%5d'%(self.ndim))
421 if use3d:
422 axisstr = "%s %s %s"%(xaxsn,yaxsn,zaxsn)
423 else:
424 axisstr = "%s %s"%(xaxsn,yaxsn)
425 axisstr = axisstr.replace("[","")
426 axisstr = axisstr.replace("]","")
427 axisstr = axisstr.replace(", ",",")
428 print (' ENTER AXES (DEFAULT %s),'\
429 ' <D> (DISPLAY), OR <EX> (EXIT)'%axisstr)
430 line = raw_input()
431 lower = 0
432 upper = 0
433 for c in line:
434 if c.islower():
435 lower = 1
436 if c.isupper():
437 upper = 1
438 if upper and not lower:
439 line=line.lower()
440 if line in ['end','ex','e']:
441 return
442 elif line == 'd':
443 if not self.dset:
444 self.getopts()
445 elif line in ["save","sav","sa","s"]:
446 self.savefile()
447 elif (line == '2d' and not use3d) or (line == '3d' and use3d):
448 self.enterlabels()
449 else:
450 try:
451 axislist = map(int,line.replace(","," ").split())
452 if use3d:
453 xaxsn = axislist[:len(axislist)/3]
454 yaxsn = axislist[len(axislist)/3:len(axislist)/3*2]
455 zaxsn = axislist[len(axislist)/3*2:]
456 else:
457 xaxsn = axislist[:len(axislist)/2]
458 yaxsn = axislist[len(axislist)/2:]
459 xaxs = []
460 for x in xaxsn:
461 if x == 1:
462 xaxs.append("t")
463 else:
464 xaxs.append(x-2)
465 yaxs = []
466 for y in yaxsn:
467 if y == 1:
468 yaxs.append("t")
469 else:
470 yaxs.append(y-2)
471 self["solution_x"] = xaxs
472 self["solution_y"] = yaxs
473 self["solution_z"] = None
474 if use3d:
475 zaxs = []
476 for z in zaxsn:
477 if z == 1:
478 zaxs.append("t")
479 else:
480 zaxs.append(z-2)
481 self["solution_z"] = zaxs
482 except:
483 print(" INVALID COMMAND, REENTER")
484
485
486 def plotbif(self,opt=None):
487 if opt is None:
488 while 1:
489 if self.expert:
490 print(' LIMITS')
491 elif self.b3d:
492 print(' ENTER XMIN,XMAX,YMIN,YMAX,ZMIN,ZMAX')
493 else:
494 print(' ENTER XMIN,XMAX,YMIN,YMAX')
495 line = raw_input().replace(","," ")
496 try:
497 if self.b3d:
498 [xmin,xmax,ymin,ymax,
499 zmin,zmax] = map(float,line.split())
500 else:
501 [xmin,xmax,ymin,ymax] = map(float,line.split())
502 break
503 except:
504 pass
505 self.handle.config(type = "bifurcation")
506 if self.b3d:
507 self.handle.config(minx = xmin, maxx = xmax,
508 miny = ymin, maxy = ymax,
509 minz = zmin, maxz = zmax)
510 else:
511 self.handle.config(minx = xmin, maxx = xmax,
512 miny = ymin, maxy = ymax)
513 else:
514 self.handle.config(type = "bifurcation")
515 self.handle.grapher.plot()
516 if not self.dset:
517 self.getopts()
518
519 def __setitem__(self,key,value):
520 self.handle[key] = value
521
522 def __getitem__(self,key):
523 return self.handle[key]
524
525 def help(self):
526 print("""
527 Principal PLAUT Commands :
528
529 <BD0> Bifurcation diagram with default limits
530 <BD> Bifurcation diagram with user-limits
531 <AX> To select bifurcation diagram axes
532 <2D> 2D plot of labeled solutions
533 <SAV> To save the current plot in a file
534 <CL> To clear the graphics window
535 <LAB> List all labeled solutions in Unit 8
536 <END> To End PLAUT
537
538 PLAUT Default Options :
539
540 <D0> Use solid curves, symbols, but no labels
541 <D1> As <D0>, showing stability and labels
542 <D2> As <D1>, without labels
543 <D3> As <D1>, with grid lines
544 <D4> AS <D2>, with grid lines
545
546 Individual Options :
547
548 <SY> Use symbols for special points
549 <DP> Differential Plot (show stability)
550 <ST> Set up titles and axes labels
551 <NU> Normal usage (Reset special options)
552
553 Press RETURN for more or Enter Command ...
554 """)
555 line = raw_input()
556 if line != "":
557 return line
558 print("""
559 Additional PLAUT Commands :
560
561 <SCR> To change the plot size
562 <SS> To define symbols
563 <RSS> Set symbol size
564 <XP> ""Expert"" (Abbreviated prompts)
565 <SD> To change curve type
566
567 <SDA> Set dash spacing
568 <LDA> Set dash size
569 <SDO> Set dot spacing
570 <SCI> Set circle spacing
571 <SSY> Set curve-symbol spacing
572 <RCS> Set curve-symbol size
573 <SDD> Set dash-dot spacing
574 <SLS> Set long-short dash spacing
575 <LLS> Set long-short dash size
576 <PA> Set plotting accuracy
577 <RES> Reset curves and symbols
578
579 <3D> 3D plot of labeled solutions
580 <B3D> 3D bifurcation diagram
581
582 --- End of Help ---
583 """)
584 return ""
585
586 # Export the functions inside AUTOSimpleFunctions in a dictionary
587 # This also allows the setting of the log
588 def exportFunctions(log=None):
589 PyPlautFunctionsInstance = PyPlautInteractiveConsole()
590 dict = {}
591 for name in PyPlautInteractiveConsole.__dict__:
592 if name[0] != '_':
593 dict[name] = getattr(PyPlautFunctionsInstance, name)
594 return dict
595
596 # This is the Python syntax for making a script runable
597 if __name__ == '__main__':
598 sys.ps1=""
599 if len(sys.argv) < 2:
600 b='fort.7'
601 s='fort.8'
602 else:
603 b='b.'+sys.argv[1]
604 s='s.'+sys.argv[1]
605 runner = PyPlautInteractiveConsole(exportFunctions(), b, s)
606 runner.interact(" ENTER <HELP> IN CASE OF DIFFICULTY\n")