From: <jd...@us...> - 2008-05-18 21:06:28
|
Revision: 5187 http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5187&view=rev Author: jdh2358 Date: 2008-05-18 14:06:13 -0700 (Sun, 18 May 2008) Log Message: ----------- moved a few more examples to their proper home Added Paths: ----------- trunk/matplotlib/examples/animation/anim.py trunk/matplotlib/examples/animation/dynamic_demo.py trunk/matplotlib/examples/animation/dynamic_image_gtkagg.py trunk/matplotlib/examples/animation/strip_chart_demo.py trunk/matplotlib/examples/event_handling/data_browser.py trunk/matplotlib/examples/event_handling/keypress_demo.py trunk/matplotlib/examples/event_handling/pick_event_demo2.py trunk/matplotlib/examples/event_handling/poly_editor.py trunk/matplotlib/examples/user_interfaces/interactive.py trunk/matplotlib/examples/user_interfaces/interactive2.py trunk/matplotlib/examples/user_interfaces/lineprops_dialog_gtk.py trunk/matplotlib/examples/user_interfaces/pylab_with_gtk.py Removed Paths: ------------- trunk/matplotlib/examples/pylab/anim.py trunk/matplotlib/examples/pylab/data_browser.py trunk/matplotlib/examples/pylab/dynamic_demo.py trunk/matplotlib/examples/pylab/dynamic_image_gtkagg.py trunk/matplotlib/examples/pylab/interactive.py trunk/matplotlib/examples/pylab/interactive2.py trunk/matplotlib/examples/pylab/keypress_demo.py trunk/matplotlib/examples/pylab/lineprops_dialog_gtk.py trunk/matplotlib/examples/pylab/pick_event_demo2.py trunk/matplotlib/examples/pylab/poly_editor.py trunk/matplotlib/examples/pylab/pylab_with_gtk.py trunk/matplotlib/examples/pylab/strip_chart_demo.py Copied: trunk/matplotlib/examples/animation/anim.py (from rev 5186, trunk/matplotlib/examples/pylab/anim.py) =================================================================== --- trunk/matplotlib/examples/animation/anim.py (rev 0) +++ trunk/matplotlib/examples/animation/anim.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -0,0 +1,32 @@ +#!/usr/bin/env python +""" +A simple example of an animated plot in matplotlib. You can test the +speed of animation of various backends by running the script with the +'-dSomeBackend' flag + +SC Aug 31 2005 mpl 0.83.2: +Here are some numbers from my system, where FPS is the frames rendered +per second + + GTK 29 FPS + GTKAgg 18 FPS + GTKCairo 15 FPS + TkAgg 13 FPS + QkAgg 13 FPS +""" +import time + +import pylab as p + +# turn interactive mode on for dynamic updates. If you aren't in +# interactive mode, you'll need to use a GUI event handler/timer. +p.ion() + +tstart = time.time() # for profiling +x = p.arange(0, 2*p.pi, 0.01) # x-array +line, = p.plot(x, p.sin(x)) +for i in p.arange(1,200): + line.set_ydata(p.sin(x+i/10.0)) # update the data + p.draw() # redraw the canvas + +print 'FPS:' , 200/(time.time()-tstart) Copied: trunk/matplotlib/examples/animation/dynamic_demo.py (from rev 5186, trunk/matplotlib/examples/pylab/dynamic_demo.py) =================================================================== --- trunk/matplotlib/examples/animation/dynamic_demo.py (rev 0) +++ trunk/matplotlib/examples/animation/dynamic_demo.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +import gobject +import gtk + +from pylab import * + + +fig = figure(1) +ind = arange(30) +X = rand(len(ind),10) +lines = plot(X[:,0], 'o') + +manager = get_current_fig_manager() +def updatefig(*args): + lines[0].set_data(ind, X[:,updatefig.count]) + manager.canvas.draw() + updatefig.count += 1 + if updatefig.count<10: + return True + else: + return False + +updatefig.count = 0 + +gobject.timeout_add(300, updatefig) +show() Copied: trunk/matplotlib/examples/animation/dynamic_image_gtkagg.py (from rev 5186, trunk/matplotlib/examples/pylab/dynamic_image_gtkagg.py) =================================================================== --- trunk/matplotlib/examples/animation/dynamic_image_gtkagg.py (rev 0) +++ trunk/matplotlib/examples/animation/dynamic_image_gtkagg.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -0,0 +1,45 @@ +#!/usr/bin/env python +""" +An animated image +""" +import time + +import gobject +import gtk + +import matplotlib +matplotlib.use('GTKAgg') +from matplotlib import rcParams + +from pylab import * + +fig = figure(1) +a = subplot(111) +x = arange(120.0)*2*pi/120.0 +x = resize(x, (100,120)) +y = arange(100.0)*2*pi/100.0 +y = resize(y, (120,100)) +y = transpose(y) +z = sin(x) + cos(y) +im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest') + +manager = get_current_fig_manager() +cnt = 0 +tstart = time.time() +def updatefig(*args): + global x, y, cnt, start + x += pi/15 + y += pi/20 + z = sin(x) + cos(y) + im.set_array(z) + manager.canvas.draw() + cnt += 1 + if cnt==50: + print 'FPS', cnt/(time.time() - tstart) + return False + return True + +cnt = 0 + +gobject.idle_add(updatefig) +show() Copied: trunk/matplotlib/examples/animation/strip_chart_demo.py (from rev 5186, trunk/matplotlib/examples/pylab/strip_chart_demo.py) =================================================================== --- trunk/matplotlib/examples/animation/strip_chart_demo.py (rev 0) +++ trunk/matplotlib/examples/animation/strip_chart_demo.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -0,0 +1,72 @@ +""" +Emulate an oscilloscope. Requires the animation API introduced in +matplotlib 0.84. See +http://www.scipy.org/wikis/topical_software/Animations for an +explanation. + +This example uses gtk but does not depend on it intimately. It just +uses the idle handler to trigger events. You can plug this into a +different GUI that supports animation (GTKAgg, TkAgg, WXAgg) and use +your toolkits idle/timer functions. +""" +import gobject, gtk +import matplotlib +matplotlib.use('GTKAgg') +import numpy as np +from matplotlib.lines import Line2D + + +class Scope: + def __init__(self, ax, maxt=10, dt=0.01): + self.ax = ax + self.canvas = ax.figure.canvas + self.dt = dt + self.maxt = maxt + self.tdata = [0] + self.ydata = [0] + self.line = Line2D(self.tdata, self.ydata, animated=True) + self.ax.add_line(self.line) + self.background = None + self.canvas.mpl_connect('draw_event', self.update_background) + self.ax.set_ylim(-.1, 1.1) + self.ax.set_xlim(0, self.maxt) + + def update_background(self, event): + self.background = self.canvas.copy_from_bbox(self.ax.bbox) + + def emitter(self, p=0.01): + 'return a random value with probability p, else 0' + v = np.random.rand(1) + if v>p: return 0. + else: return np.random.rand(1) + + def update(self, *args): + if self.background is None: return True + y = self.emitter() + lastt = self.tdata[-1] + if lastt>self.tdata[0]+self.maxt: # reset the arrays + self.tdata = [self.tdata[-1]] + self.ydata = [self.ydata[-1]] + self.ax.set_xlim(self.tdata[0], self.tdata[0]+self.maxt) + self.ax.figure.canvas.draw() + + self.canvas.restore_region(self.background) + + t = self.tdata[-1] + self.dt + self.tdata.append(t) + self.ydata.append(y) + self.line.set_data(self.tdata, self.ydata) + self.ax.draw_artist(self.line) + + self.canvas.blit(self.ax.bbox) + return True + + +from pylab import figure, show + +fig = figure() +ax = fig.add_subplot(111) +scope = Scope(ax) +gobject.idle_add(scope.update) + +show() Copied: trunk/matplotlib/examples/event_handling/data_browser.py (from rev 5186, trunk/matplotlib/examples/pylab/data_browser.py) =================================================================== --- trunk/matplotlib/examples/event_handling/data_browser.py (rev 0) +++ trunk/matplotlib/examples/event_handling/data_browser.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -0,0 +1,82 @@ +import numpy as np +from pylab import figure, show + + +X = np.random.rand(100, 200) +xs = np.mean(X, axis=1) +ys = np.std(X, axis=1) + +fig = figure() +ax = fig.add_subplot(211) +ax.set_title('click on point to plot time series') +line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance +ax2 = fig.add_subplot(212) + +class PointBrowser: + """ + Click on a point to select and highlight it -- the data that + generated the point will be shown in the lower axes. Use the 'n' + and 'p' keys to browse through the next and pervious points + """ + def __init__(self): + self.lastind = 0 + + self.text = ax.text(0.05, 0.95, 'selected: none', + transform=ax.transAxes, va='top') + self.selected, = ax.plot([xs[0]], [ys[0]], 'o', ms=12, alpha=0.4, + color='yellow', visible=False) + + def onpress(self, event): + if self.lastind is None: return + if event.key not in ('n', 'p'): return + if event.key=='n': inc = 1 + else: inc = -1 + + + self.lastind += inc + self.lastind = np.clip(self.lastind, 0, len(xs)-1) + self.update() + + def onpick(self, event): + + if event.artist!=line: return True + + N = len(event.ind) + if not N: return True + + # the click locations + x = event.mouseevent.xdata + y = event.mouseevent.ydata + + + distances = np.hypot(x-xs[event.ind], y-ys[event.ind]) + indmin = distances.argmin() + dataind = event.ind[indmin] + + self.lastind = dataind + self.update() + + def update(self): + if self.lastind is None: return + + dataind = self.lastind + + ax2.cla() + ax2.plot(X[dataind]) + + ax2.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f'%(xs[dataind], ys[dataind]), + transform=ax2.transAxes, va='top') + ax2.set_ylim(-0.5, 1.5) + self.selected.set_visible(True) + self.selected.set_data(xs[dataind], ys[dataind]) + + self.text.set_text('selected: %d'%dataind) + fig.canvas.draw() + + +browser = PointBrowser() + +fig.canvas.mpl_connect('pick_event', browser.onpick) +fig.canvas.mpl_connect('key_press_event', browser.onpress) + +show() Copied: trunk/matplotlib/examples/event_handling/keypress_demo.py (from rev 5186, trunk/matplotlib/examples/pylab/keypress_demo.py) =================================================================== --- trunk/matplotlib/examples/event_handling/keypress_demo.py (rev 0) +++ trunk/matplotlib/examples/event_handling/keypress_demo.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -0,0 +1,23 @@ +#!/usr/bin/env python +""" +Show how to connect to keypress events +""" +import numpy as n +from pylab import figure, show + +def press(event): + print 'press', event.key + if event.key=='x': + visible = xl.get_visible() + xl.set_visible(not visible) + fig.canvas.draw() + +fig = figure() +ax = fig.add_subplot(111) + +fig.canvas.mpl_connect('key_press_event', press) + +ax.plot(n.random.rand(12), n.random.rand(12), 'go') +xl = ax.set_xlabel('easy come, easy go') + +show() Copied: trunk/matplotlib/examples/event_handling/pick_event_demo2.py (from rev 5186, trunk/matplotlib/examples/pylab/pick_event_demo2.py) =================================================================== --- trunk/matplotlib/examples/event_handling/pick_event_demo2.py (rev 0) +++ trunk/matplotlib/examples/event_handling/pick_event_demo2.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -0,0 +1,45 @@ +""" +compute the mean and stddev of 100 data sets and plot mean vs stddev. +When you click on one of the mu, sigma points, plot the raw data from +the dataset that generated the mean and stddev +""" +import numpy +from pylab import figure, show + + +X = numpy.random.rand(100, 1000) +xs = numpy.mean(X, axis=1) +ys = numpy.std(X, axis=1) + +fig = figure() +ax = fig.add_subplot(111) +ax.set_title('click on point to plot time series') +line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance + + +def onpick(event): + + if event.artist!=line: return True + + N = len(event.ind) + if not N: return True + + + figi = figure() + for subplotnum, dataind in enumerate(event.ind): + ax = figi.add_subplot(N,1,subplotnum+1) + ax.plot(X[dataind]) + ax.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f'%(xs[dataind], ys[dataind]), + transform=ax.transAxes, va='top') + ax.set_ylim(-0.5, 1.5) + figi.show() + return True + +fig.canvas.mpl_connect('pick_event', onpick) + +show() + + + + + Copied: trunk/matplotlib/examples/event_handling/poly_editor.py (from rev 5186, trunk/matplotlib/examples/pylab/poly_editor.py) =================================================================== --- trunk/matplotlib/examples/event_handling/poly_editor.py (rev 0) +++ trunk/matplotlib/examples/event_handling/poly_editor.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -0,0 +1,171 @@ +""" +This is an example to show how to build cross-GUI applications using +matplotlib event handling to interact with objects on the canvas + +""" +from matplotlib.artist import Artist +from matplotlib.patches import Polygon, CirclePolygon +from numpy import sqrt, nonzero, equal, array, asarray, dot, amin, cos, sin +from matplotlib.mlab import dist_point_to_segment + + +class PolygonInteractor: + """ + An polygon editor. + + Key-bindings + + 't' toggle vertex markers on and off. When vertex markers are on, + you can move them, delete them + + 'd' delete the vertex under point + + 'i' insert a vertex at point. You must be within epsilon of the + line connecting two existing vertices + + """ + + showverts = True + epsilon = 5 # max pixel distance to count as a vertex hit + + def __init__(self, ax, poly): + if poly.figure is None: + raise RuntimeError('You must first add the polygon to a figure or canvas before defining the interactor') + self.ax = ax + canvas = poly.figure.canvas + self.poly = poly + + x, y = zip(*self.poly.xy) + self.line = Line2D(x,y,marker='o', markerfacecolor='r', animated=True) + self.ax.add_line(self.line) + #self._update_line(poly) + + cid = self.poly.add_callback(self.poly_changed) + self._ind = None # the active vert + + canvas.mpl_connect('draw_event', self.draw_callback) + canvas.mpl_connect('button_press_event', self.button_press_callback) + canvas.mpl_connect('key_press_event', self.key_press_callback) + canvas.mpl_connect('button_release_event', self.button_release_callback) + canvas.mpl_connect('motion_notify_event', self.motion_notify_callback) + self.canvas = canvas + + + def draw_callback(self, event): + self.background = self.canvas.copy_from_bbox(self.ax.bbox) + self.ax.draw_artist(self.poly) + self.ax.draw_artist(self.line) + self.canvas.blit(self.ax.bbox) + + def poly_changed(self, poly): + 'this method is called whenever the polygon object is called' + # only copy the artist props to the line (except visibility) + vis = self.line.get_visible() + Artist.update_from(self.line, poly) + self.line.set_visible(vis) # don't use the poly visibility state + + + def get_ind_under_point(self, event): + 'get the index of the vertex under point if within epsilon tolerance' + + # display coords + xy = asarray(self.poly.xy) + xyt = self.poly.get_transform().transform(xy) + xt, yt = xyt[:, 0], xyt[:, 1] + d = sqrt((xt-event.x)**2 + (yt-event.y)**2) + indseq = nonzero(equal(d, amin(d)))[0] + ind = indseq[0] + + if d[ind]>=self.epsilon: + ind = None + + return ind + + def button_press_callback(self, event): + 'whenever a mouse button is pressed' + if not self.showverts: return + if event.inaxes==None: return + if event.button != 1: return + self._ind = self.get_ind_under_point(event) + + def button_release_callback(self, event): + 'whenever a mouse button is released' + if not self.showverts: return + if event.button != 1: return + self._ind = None + + def key_press_callback(self, event): + 'whenever a key is pressed' + if not event.inaxes: return + if event.key=='t': + self.showverts = not self.showverts + self.line.set_visible(self.showverts) + if not self.showverts: self._ind = None + elif event.key=='d': + ind = self.get_ind_under_point(event) + if ind is not None: + self.poly.xy = [tup for i,tup in enumerate(self.poly.xy) if i!=ind] + self.line.set_data(zip(*self.poly.xy)) + elif event.key=='i': + xys = self.poly.get_transform().transform(self.poly.xy) + p = event.x, event.y # display coords + for i in range(len(xys)-1): + s0 = xys[i] + s1 = xys[i+1] + d = dist_point_to_segment(p, s0, s1) + if d<=self.epsilon: + self.poly.xy = array( + list(self.poly.xy[:i]) + + [(event.xdata, event.ydata)] + + list(self.poly.xy[i:])) + self.line.set_data(zip(*self.poly.xy)) + break + + + self.canvas.draw() + + def motion_notify_callback(self, event): + 'on mouse movement' + if not self.showverts: return + if self._ind is None: return + if event.inaxes is None: return + if event.button != 1: return + x,y = event.xdata, event.ydata + + self.poly.xy[self._ind] = x,y + self.line.set_data(zip(*self.poly.xy)) + + self.canvas.restore_region(self.background) + self.ax.draw_artist(self.poly) + self.ax.draw_artist(self.line) + self.canvas.blit(self.ax.bbox) + + + +from pylab import * + + + + + +fig = figure() +theta = arange(0, 2*pi, 0.1) +r = 1.5 + +xs = r*cos(theta) +ys = r*sin(theta) + +poly = Polygon(zip(xs, ys,), animated=True) + + + + +ax = subplot(111) +ax.add_patch(poly) +p = PolygonInteractor( ax, poly) + +#ax.add_line(p.line) +ax.set_title('Click and drag a point to move it') +ax.set_xlim((-2,2)) +ax.set_ylim((-2,2)) +show() Deleted: trunk/matplotlib/examples/pylab/anim.py =================================================================== --- trunk/matplotlib/examples/pylab/anim.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/anim.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -A simple example of an animated plot in matplotlib. You can test the -speed of animation of various backends by running the script with the -'-dSomeBackend' flag - -SC Aug 31 2005 mpl 0.83.2: -Here are some numbers from my system, where FPS is the frames rendered -per second - - GTK 29 FPS - GTKAgg 18 FPS - GTKCairo 15 FPS - TkAgg 13 FPS - QkAgg 13 FPS -""" -import time - -import pylab as p - -# turn interactive mode on for dynamic updates. If you aren't in -# interactive mode, you'll need to use a GUI event handler/timer. -p.ion() - -tstart = time.time() # for profiling -x = p.arange(0, 2*p.pi, 0.01) # x-array -line, = p.plot(x, p.sin(x)) -for i in p.arange(1,200): - line.set_ydata(p.sin(x+i/10.0)) # update the data - p.draw() # redraw the canvas - -print 'FPS:' , 200/(time.time()-tstart) Deleted: trunk/matplotlib/examples/pylab/data_browser.py =================================================================== --- trunk/matplotlib/examples/pylab/data_browser.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/data_browser.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,82 +0,0 @@ -import numpy as np -from pylab import figure, show - - -X = np.random.rand(100, 200) -xs = np.mean(X, axis=1) -ys = np.std(X, axis=1) - -fig = figure() -ax = fig.add_subplot(211) -ax.set_title('click on point to plot time series') -line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance -ax2 = fig.add_subplot(212) - -class PointBrowser: - """ - Click on a point to select and highlight it -- the data that - generated the point will be shown in the lower axes. Use the 'n' - and 'p' keys to browse through the next and pervious points - """ - def __init__(self): - self.lastind = 0 - - self.text = ax.text(0.05, 0.95, 'selected: none', - transform=ax.transAxes, va='top') - self.selected, = ax.plot([xs[0]], [ys[0]], 'o', ms=12, alpha=0.4, - color='yellow', visible=False) - - def onpress(self, event): - if self.lastind is None: return - if event.key not in ('n', 'p'): return - if event.key=='n': inc = 1 - else: inc = -1 - - - self.lastind += inc - self.lastind = np.clip(self.lastind, 0, len(xs)-1) - self.update() - - def onpick(self, event): - - if event.artist!=line: return True - - N = len(event.ind) - if not N: return True - - # the click locations - x = event.mouseevent.xdata - y = event.mouseevent.ydata - - - distances = np.hypot(x-xs[event.ind], y-ys[event.ind]) - indmin = distances.argmin() - dataind = event.ind[indmin] - - self.lastind = dataind - self.update() - - def update(self): - if self.lastind is None: return - - dataind = self.lastind - - ax2.cla() - ax2.plot(X[dataind]) - - ax2.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f'%(xs[dataind], ys[dataind]), - transform=ax2.transAxes, va='top') - ax2.set_ylim(-0.5, 1.5) - self.selected.set_visible(True) - self.selected.set_data(xs[dataind], ys[dataind]) - - self.text.set_text('selected: %d'%dataind) - fig.canvas.draw() - - -browser = PointBrowser() - -fig.canvas.mpl_connect('pick_event', browser.onpick) -fig.canvas.mpl_connect('key_press_event', browser.onpress) - -show() Deleted: trunk/matplotlib/examples/pylab/dynamic_demo.py =================================================================== --- trunk/matplotlib/examples/pylab/dynamic_demo.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/dynamic_demo.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -import gobject -import gtk - -from pylab import * - - -fig = figure(1) -ind = arange(30) -X = rand(len(ind),10) -lines = plot(X[:,0], 'o') - -manager = get_current_fig_manager() -def updatefig(*args): - lines[0].set_data(ind, X[:,updatefig.count]) - manager.canvas.draw() - updatefig.count += 1 - if updatefig.count<10: - return True - else: - return False - -updatefig.count = 0 - -gobject.timeout_add(300, updatefig) -show() Deleted: trunk/matplotlib/examples/pylab/dynamic_image_gtkagg.py =================================================================== --- trunk/matplotlib/examples/pylab/dynamic_image_gtkagg.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/dynamic_image_gtkagg.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,45 +0,0 @@ -#!/usr/bin/env python -""" -An animated image -""" -import time - -import gobject -import gtk - -import matplotlib -matplotlib.use('GTKAgg') -from matplotlib import rcParams - -from pylab import * - -fig = figure(1) -a = subplot(111) -x = arange(120.0)*2*pi/120.0 -x = resize(x, (100,120)) -y = arange(100.0)*2*pi/100.0 -y = resize(y, (120,100)) -y = transpose(y) -z = sin(x) + cos(y) -im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest') - -manager = get_current_fig_manager() -cnt = 0 -tstart = time.time() -def updatefig(*args): - global x, y, cnt, start - x += pi/15 - y += pi/20 - z = sin(x) + cos(y) - im.set_array(z) - manager.canvas.draw() - cnt += 1 - if cnt==50: - print 'FPS', cnt/(time.time() - tstart) - return False - return True - -cnt = 0 - -gobject.idle_add(updatefig) -show() Deleted: trunk/matplotlib/examples/pylab/interactive.py =================================================================== --- trunk/matplotlib/examples/pylab/interactive.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/interactive.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,230 +0,0 @@ -#!/usr/bin/env python -"""Multithreaded interactive interpreter with GTK and Matplotlib support. - -Usage: - - pyint-gtk.py -> starts shell with gtk thread running separately - - pyint-gtk.py -pylab [filename] -> initializes matplotlib, optionally running - the named file. The shell starts after the file is executed. - -Threading code taken from: -http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian -McErlean and John Finlay. - -Matplotlib support taken from interactive.py in the matplotlib distribution. - -Also borrows liberally from code.py in the Python standard library.""" - -__author__ = "Fernando Perez <Fer...@co...>" - -import sys -import code -import threading - -import gobject -import gtk - -try: - import readline -except ImportError: - has_readline = False -else: - has_readline = True - -class MTConsole(code.InteractiveConsole): - """Simple multi-threaded shell""" - - def __init__(self,on_kill=None,*args,**kw): - code.InteractiveConsole.__init__(self,*args,**kw) - self.code_to_run = None - self.ready = threading.Condition() - self._kill = False - if on_kill is None: - on_kill = [] - # Check that all things to kill are callable: - for _ in on_kill: - if not callable(_): - raise TypeError,'on_kill must be a list of callables' - self.on_kill = on_kill - # Set up tab-completer - if has_readline: - import rlcompleter - try: # this form only works with python 2.3 - self.completer = rlcompleter.Completer(self.locals) - except: # simpler for py2.2 - self.completer = rlcompleter.Completer() - - readline.set_completer(self.completer.complete) - # Use tab for completions - readline.parse_and_bind('tab: complete') - # This forces readline to automatically print the above list when tab - # completion is set to 'complete'. - readline.parse_and_bind('set show-all-if-ambiguous on') - # Bindings for incremental searches in the history. These searches - # use the string typed so far on the command line and search - # anything in the previous input history containing them. - readline.parse_and_bind('"\C-r": reverse-search-history') - readline.parse_and_bind('"\C-s": forward-search-history') - - def runsource(self, source, filename="<input>", symbol="single"): - """Compile and run some source in the interpreter. - - Arguments are as for compile_command(). - - One several things can happen: - - 1) The input is incorrect; compile_command() raised an - exception (SyntaxError or OverflowError). A syntax traceback - will be printed by calling the showsyntaxerror() method. - - 2) The input is incomplete, and more input is required; - compile_command() returned None. Nothing happens. - - 3) The input is complete; compile_command() returned a code - object. The code is executed by calling self.runcode() (which - also handles run-time exceptions, except for SystemExit). - - The return value is True in case 2, False in the other cases (unless - an exception is raised). The return value can be used to - decide whether to use sys.ps1 or sys.ps2 to prompt the next - line. - """ - try: - code = self.compile(source, filename, symbol) - except (OverflowError, SyntaxError, ValueError): - # Case 1 - self.showsyntaxerror(filename) - return False - - if code is None: - # Case 2 - return True - - # Case 3 - # Store code in self, so the execution thread can handle it - self.ready.acquire() - self.code_to_run = code - self.ready.wait() # Wait until processed in timeout interval - self.ready.release() - - return False - - def runcode(self): - """Execute a code object. - - When an exception occurs, self.showtraceback() is called to display a - traceback.""" - - self.ready.acquire() - if self._kill: - print 'Closing threads...', - sys.stdout.flush() - for tokill in self.on_kill: - tokill() - print 'Done.' - - if self.code_to_run is not None: - self.ready.notify() - code.InteractiveConsole.runcode(self,self.code_to_run) - - self.code_to_run = None - self.ready.release() - return True - - def kill (self): - """Kill the thread, returning when it has been shut down.""" - self.ready.acquire() - self._kill = True - self.ready.release() - -class GTKInterpreter(threading.Thread): - """Run gtk.main in the main thread and a python interpreter in a - separate thread. - Python commands can be passed to the thread where they will be executed. - This is implemented by periodically checking for passed code using a - GTK timeout callback. - """ - TIMEOUT = 100 # Millisecond interval between timeouts. - - def __init__(self,banner=None): - threading.Thread.__init__(self) - self.banner = banner - self.shell = MTConsole(on_kill=[gtk.main_quit]) - - def run(self): - self.pre_interact() - self.shell.interact(self.banner) - self.shell.kill() - - def mainloop(self): - self.start() - gobject.timeout_add(self.TIMEOUT, self.shell.runcode) - try: - if gtk.gtk_version[0] >= 2: - gtk.gdk.threads_init() - except AttributeError: - pass - gtk.main() - self.join() - - def pre_interact(self): - """This method should be overridden by subclasses. - - It gets called right before interact(), but after the thread starts. - Typically used to push initialization code into the interpreter""" - - pass - -class MatplotLibInterpreter(GTKInterpreter): - """Threaded interpreter with matplotlib support. - - Note that this explicitly sets GTKAgg as the backend, since it has - specific GTK hooks in it.""" - - def __init__(self,banner=None): - banner = """\nWelcome to matplotlib, a matlab-like python environment. - help(matlab) -> help on matlab compatible commands from matplotlib. - help(plotting) -> help on plotting commands. - """ - GTKInterpreter.__init__(self,banner) - - def pre_interact(self): - """Initialize matplotlib before user interaction begins""" - - push = self.shell.push - # Code to execute in user's namespace - lines = ["import matplotlib", - "matplotlib.use('GTKAgg')", - "matplotlib.interactive(1)", - "import matplotlib.pylab as pylab", - "from matplotlib.pylab import *\n"] - - map(push,lines) - - # Execute file if given. - if len(sys.argv)>1: - import matplotlib - matplotlib.interactive(0) # turn off interaction - fname = sys.argv[1] - try: - inFile = file(fname, 'r') - except IOError: - print '*** ERROR *** Could not read file <%s>' % fname - else: - print '*** Executing file <%s>:' % fname - for line in inFile: - if line.lstrip().find('show()')==0: continue - print '>>', line, - push(line) - inFile.close() - matplotlib.interactive(1) # turn on interaction - -if __name__ == '__main__': - # Quick sys.argv hack to extract the option and leave filenames in sys.argv. - # For real option handling, use optparse or getopt. - if len(sys.argv) > 1 and sys.argv[1]=='-pylab': - sys.argv = [sys.argv[0]]+sys.argv[2:] - MatplotLibInterpreter().mainloop() - else: - GTKInterpreter().mainloop() Deleted: trunk/matplotlib/examples/pylab/interactive2.py =================================================================== --- trunk/matplotlib/examples/pylab/interactive2.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/interactive2.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,378 +0,0 @@ -#!/usr/bin/env python - -# GTK Interactive Console -# (C) 2003, Jon Anderson -# See www.python.org/2.2/license.html for -# license details. -# -import gtk -import gtk.gdk - -import code -import os, sys -import pango - -import __builtin__ -import __main__ - - -banner = """GTK Interactive Python Console -Thanks to Jon Anderson -%s -""" % sys.version - -banner += """ - -Welcome to matplotlib. - - help(matplotlib) -- shows a list of all matlab(TM) compatible commands provided - help(plotting) -- shows a list of plot specific commands - -""" -class Completer: - """ - Taken from rlcompleter, with readline references stripped, and a local dictionary to use. - """ - def __init__(self, locals): - self.locals = locals - - def complete(self, text, state): - """Return the next possible completion for 'text'. - This is called successively with state == 0, 1, 2, ... until it - returns None. The completion should begin with 'text'. - - """ - if state == 0: - if "." in text: - self.matches = self.attr_matches(text) - else: - self.matches = self.global_matches(text) - try: - return self.matches[state] - except IndexError: - return None - - def global_matches(self, text): - """Compute matches when text is a simple name. - - Return a list of all keywords, built-in functions and names - currently defines in __main__ that match. - - """ - import keyword - matches = [] - n = len(text) - for list in [keyword.kwlist,__builtin__.__dict__.keys(),__main__.__dict__.keys(), self.locals.keys()]: - for word in list: - if word[:n] == text and word != "__builtins__": - matches.append(word) - return matches - - def attr_matches(self, text): - """Compute matches when text contains a dot. - - Assuming the text is of the form NAME.NAME....[NAME], and is - evaluatable in the globals of __main__, it will be evaluated - and its attributes (as revealed by dir()) are used as possible - completions. (For class instances, class members are are also - considered.) - - WARNING: this can still invoke arbitrary C code, if an object - with a __getattr__ hook is evaluated. - - """ - import re - m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) - if not m: - return - expr, attr = m.group(1, 3) - object = eval(expr, __main__.__dict__, self.locals) - words = dir(object) - if hasattr(object,'__class__'): - words.append('__class__') - words = words + get_class_members(object.__class__) - matches = [] - n = len(attr) - for word in words: - if word[:n] == attr and word != "__builtins__": - matches.append("%s.%s" % (expr, word)) - return matches - -def get_class_members(klass): - ret = dir(klass) - if hasattr(klass,'__bases__'): - for base in klass.__bases__: - ret = ret + get_class_members(base) - return ret - - - -class OutputStream: - """ - A Multiplexing output stream. - It can replace another stream, and tee output to the original stream and too - a GTK textview. - """ - def __init__(self,view,old_out,style): - self.view = view - self.buffer = view.get_buffer() - self.mark = self.buffer.create_mark("End",self.buffer.get_end_iter(), False ) - self.out = old_out - self.style = style - self.tee = 1 - - def write(self,text): - if self.tee: - self.out.write(text) - - end = self.buffer.get_end_iter() - - if not self.view == None: - self.view.scroll_to_mark(self.mark, 0, True, 1, 1) - - self.buffer.insert_with_tags(end,text,self.style) - -class GTKInterpreterConsole(gtk.ScrolledWindow): - """ - An InteractiveConsole for GTK. It's an actual widget, - so it can be dropped in just about anywhere. - """ - def __init__(self): - gtk.ScrolledWindow.__init__(self) - self.set_policy (gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC) - - self.text = gtk.TextView() - self.text.set_wrap_mode(True) - - self.interpreter = code.InteractiveInterpreter() - - self.completer = Completer(self.interpreter.locals) - self.buffer = [] - self.history = [] - self.banner = banner - self.ps1 = ">>> " - self.ps2 = "... " - - self.text.add_events( gtk.gdk.KEY_PRESS_MASK ) - self.text.connect( "key_press_event", self.key_pressed ) - - self.current_history = -1 - - self.mark = self.text.get_buffer().create_mark("End",self.text.get_buffer().get_end_iter(), False ) - - #setup colors - self.style_banner = gtk.TextTag("banner") - self.style_banner.set_property( "foreground", "saddle brown" ) - - self.style_ps1 = gtk.TextTag("ps1") - self.style_ps1.set_property( "foreground", "DarkOrchid4" ) - self.style_ps1.set_property( "editable", False ) - self.style_ps1.set_property("font", "courier" ) - - self.style_ps2 = gtk.TextTag("ps2") - self.style_ps2.set_property( "foreground", "DarkOliveGreen" ) - self.style_ps2.set_property( "editable", False ) - self.style_ps2.set_property("font", "courier" ) - - self.style_out = gtk.TextTag("stdout") - self.style_out.set_property( "foreground", "midnight blue" ) - self.style_err = gtk.TextTag("stderr") - self.style_err.set_property( "style", pango.STYLE_ITALIC ) - self.style_err.set_property( "foreground", "red" ) - - self.text.get_buffer().get_tag_table().add(self.style_banner) - self.text.get_buffer().get_tag_table().add(self.style_ps1) - self.text.get_buffer().get_tag_table().add(self.style_ps2) - self.text.get_buffer().get_tag_table().add(self.style_out) - self.text.get_buffer().get_tag_table().add(self.style_err) - - self.stdout = OutputStream(self.text,sys.stdout,self.style_out) - self.stderr = OutputStream(self.text,sys.stderr,self.style_err) - - sys.stderr = self.stderr - sys.stdout = self.stdout - - self.current_prompt = None - - self.write_line(self.banner, self.style_banner) - self.prompt_ps1() - - self.add(self.text) - self.text.show() - - - def reset_history(self): - self.history = [] - - def reset_buffer(self): - self.buffer = [] - - def prompt_ps1(self): - self.current_prompt = self.prompt_ps1 - self.write_line(self.ps1,self.style_ps1) - - def prompt_ps2(self): - self.current_prompt = self.prompt_ps2 - self.write_line(self.ps2,self.style_ps2) - - def write_line(self,text,style=None): - start,end = self.text.get_buffer().get_bounds() - if style==None: - self.text.get_buffer().insert(end,text) - else: - self.text.get_buffer().insert_with_tags(end,text,style) - - self.text.scroll_to_mark(self.mark, 0, True, 1, 1) - - def push(self, line): - - self.buffer.append(line) - if len(line) > 0: - self.history.append(line) - - source = "\n".join(self.buffer) - - more = self.interpreter.runsource(source, "<<console>>") - - if not more: - self.reset_buffer() - - return more - - def key_pressed(self,widget,event): - if event.keyval == gtk.gdk.keyval_from_name('Return'): - return self.execute_line() - - if event.keyval == gtk.gdk.keyval_from_name('Up'): - self.current_history = self.current_history - 1 - if self.current_history < - len(self.history): - self.current_history = - len(self.history) - return self.show_history() - elif event.keyval == gtk.gdk.keyval_from_name('Down'): - self.current_history = self.current_history + 1 - if self.current_history > 0: - self.current_history = 0 - return self.show_history() - elif event.keyval == gtk.gdk.keyval_from_name( 'Home'): - l = self.text.get_buffer().get_line_count() - 1 - start = self.text.get_buffer().get_iter_at_line_offset(l,4) - self.text.get_buffer().place_cursor(start) - return True - elif event.keyval == gtk.gdk.keyval_from_name( 'space') and event.state & gtk.gdk.CONTROL_MASK: - return self.complete_line() - return False - - def show_history(self): - if self.current_history == 0: - return True - else: - self.replace_line( self.history[self.current_history] ) - return True - - def current_line(self): - start,end = self.current_line_bounds() - return self.text.get_buffer().get_text(start,end, True) - - def current_line_bounds(self): - txt_buffer = self.text.get_buffer() - l = txt_buffer.get_line_count() - 1 - - start = txt_buffer.get_iter_at_line(l) - if start.get_chars_in_line() >= 4: - start.forward_chars(4) - end = txt_buffer.get_end_iter() - return start,end - - def replace_line(self,txt): - start,end = self.current_line_bounds() - self.text.get_buffer().delete(start,end) - self.write_line(txt) - - def execute_line(self, line=None): - if line is None: - line = self.current_line() - self.write_line("\n") - else: - self.write_line(line + "\n") - - - more = self.push(line) - - self.text.get_buffer().place_cursor(self.text.get_buffer().get_end_iter()) - - if more: - self.prompt_ps2() - else: - self.prompt_ps1() - - - self.current_history = 0 - - self.window.raise_() - - return True - - def complete_line(self): - line = self.current_line() - tokens = line.split() - token = tokens[-1] - - completions = [] - p = self.completer.complete(token,len(completions)) - while p != None: - completions.append(p) - p = self.completer.complete(token, len(completions)) - - if len(completions) != 1: - self.write_line("\n") - self.write_line("\n".join(completions), self.style_ps1) - self.write_line("\n") - self.current_prompt() - self.write_line(line) - else: - i = line.rfind(token) - line = line[0:i] + completions[0] - self.replace_line(line) - - return True - - -def main(): - w = gtk.Window() - console = GTKInterpreterConsole() - console.set_size_request(640,480) - w.add(console) - - def destroy(arg=None): - gtk.main_quit() - - def key_event(widget,event): - if gtk.gdk.keyval_name( event.keyval) == 'd' and \ - event.state & gtk.gdk.CONTROL_MASK: - destroy() - return False - - w.connect("destroy", destroy) - - w.add_events( gtk.gdk.KEY_PRESS_MASK ) - w.connect( 'key_press_event', key_event) - w.show_all() - - console.execute_line('import matplotlib') - console.execute_line("matplotlib.use('GTKAgg')") - console.execute_line('matplotlib.interactive(1)') - console.execute_line('from pylab import *') - - - if len(sys.argv)>1: - fname = sys.argv[1] - if not os.path.exists(fname): - print >> sys.stderr, '%s does not exist' % fname - for line in file(fname): - line = line.strip() - - console.execute_line(line) - gtk.main() - -if __name__ == '__main__': - main() Deleted: trunk/matplotlib/examples/pylab/keypress_demo.py =================================================================== --- trunk/matplotlib/examples/pylab/keypress_demo.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/keypress_demo.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,23 +0,0 @@ -#!/usr/bin/env python -""" -Show how to connect to keypress events -""" -import numpy as n -from pylab import figure, show - -def press(event): - print 'press', event.key - if event.key=='x': - visible = xl.get_visible() - xl.set_visible(not visible) - fig.canvas.draw() - -fig = figure() -ax = fig.add_subplot(111) - -fig.canvas.mpl_connect('key_press_event', press) - -ax.plot(n.random.rand(12), n.random.rand(12), 'go') -xl = ax.set_xlabel('easy come, easy go') - -show() Deleted: trunk/matplotlib/examples/pylab/lineprops_dialog_gtk.py =================================================================== --- trunk/matplotlib/examples/pylab/lineprops_dialog_gtk.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/lineprops_dialog_gtk.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,25 +0,0 @@ -import matplotlib -matplotlib.use('GTKAgg') -from matplotlib.backends.backend_gtk import DialogLineprops - -import numpy as np -from pylab import figure, show - -def f(t): - s1 = np.cos(2*np.pi*t) - e1 = np.exp(-t) - return np.multiply(s1,e1) - -t1 = np.arange(0.0, 5.0, 0.1) -t2 = np.arange(0.0, 5.0, 0.02) -t3 = np.arange(0.0, 2.0, 0.01) - -fig = figure() -ax = fig.add_subplot(111) -l1, = ax.plot(t1, f(t1), 'bo', label='line 1') -l2, = ax.plot(t2, f(t2), 'k--', label='line 2') - -dlg = DialogLineprops([l1,l2]) -dlg.show() -show() - Deleted: trunk/matplotlib/examples/pylab/pick_event_demo2.py =================================================================== --- trunk/matplotlib/examples/pylab/pick_event_demo2.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/pick_event_demo2.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,45 +0,0 @@ -""" -compute the mean and stddev of 100 data sets and plot mean vs stddev. -When you click on one of the mu, sigma points, plot the raw data from -the dataset that generated the mean and stddev -""" -import numpy -from pylab import figure, show - - -X = numpy.random.rand(100, 1000) -xs = numpy.mean(X, axis=1) -ys = numpy.std(X, axis=1) - -fig = figure() -ax = fig.add_subplot(111) -ax.set_title('click on point to plot time series') -line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance - - -def onpick(event): - - if event.artist!=line: return True - - N = len(event.ind) - if not N: return True - - - figi = figure() - for subplotnum, dataind in enumerate(event.ind): - ax = figi.add_subplot(N,1,subplotnum+1) - ax.plot(X[dataind]) - ax.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f'%(xs[dataind], ys[dataind]), - transform=ax.transAxes, va='top') - ax.set_ylim(-0.5, 1.5) - figi.show() - return True - -fig.canvas.mpl_connect('pick_event', onpick) - -show() - - - - - Deleted: trunk/matplotlib/examples/pylab/poly_editor.py =================================================================== --- trunk/matplotlib/examples/pylab/poly_editor.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/poly_editor.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,171 +0,0 @@ -""" -This is an example to show how to build cross-GUI applications using -matplotlib event handling to interact with objects on the canvas - -""" -from matplotlib.artist import Artist -from matplotlib.patches import Polygon, CirclePolygon -from numpy import sqrt, nonzero, equal, array, asarray, dot, amin, cos, sin -from matplotlib.mlab import dist_point_to_segment - - -class PolygonInteractor: - """ - An polygon editor. - - Key-bindings - - 't' toggle vertex markers on and off. When vertex markers are on, - you can move them, delete them - - 'd' delete the vertex under point - - 'i' insert a vertex at point. You must be within epsilon of the - line connecting two existing vertices - - """ - - showverts = True - epsilon = 5 # max pixel distance to count as a vertex hit - - def __init__(self, ax, poly): - if poly.figure is None: - raise RuntimeError('You must first add the polygon to a figure or canvas before defining the interactor') - self.ax = ax - canvas = poly.figure.canvas - self.poly = poly - - x, y = zip(*self.poly.xy) - self.line = Line2D(x,y,marker='o', markerfacecolor='r', animated=True) - self.ax.add_line(self.line) - #self._update_line(poly) - - cid = self.poly.add_callback(self.poly_changed) - self._ind = None # the active vert - - canvas.mpl_connect('draw_event', self.draw_callback) - canvas.mpl_connect('button_press_event', self.button_press_callback) - canvas.mpl_connect('key_press_event', self.key_press_callback) - canvas.mpl_connect('button_release_event', self.button_release_callback) - canvas.mpl_connect('motion_notify_event', self.motion_notify_callback) - self.canvas = canvas - - - def draw_callback(self, event): - self.background = self.canvas.copy_from_bbox(self.ax.bbox) - self.ax.draw_artist(self.poly) - self.ax.draw_artist(self.line) - self.canvas.blit(self.ax.bbox) - - def poly_changed(self, poly): - 'this method is called whenever the polygon object is called' - # only copy the artist props to the line (except visibility) - vis = self.line.get_visible() - Artist.update_from(self.line, poly) - self.line.set_visible(vis) # don't use the poly visibility state - - - def get_ind_under_point(self, event): - 'get the index of the vertex under point if within epsilon tolerance' - - # display coords - xy = asarray(self.poly.xy) - xyt = self.poly.get_transform().transform(xy) - xt, yt = xyt[:, 0], xyt[:, 1] - d = sqrt((xt-event.x)**2 + (yt-event.y)**2) - indseq = nonzero(equal(d, amin(d)))[0] - ind = indseq[0] - - if d[ind]>=self.epsilon: - ind = None - - return ind - - def button_press_callback(self, event): - 'whenever a mouse button is pressed' - if not self.showverts: return - if event.inaxes==None: return - if event.button != 1: return - self._ind = self.get_ind_under_point(event) - - def button_release_callback(self, event): - 'whenever a mouse button is released' - if not self.showverts: return - if event.button != 1: return - self._ind = None - - def key_press_callback(self, event): - 'whenever a key is pressed' - if not event.inaxes: return - if event.key=='t': - self.showverts = not self.showverts - self.line.set_visible(self.showverts) - if not self.showverts: self._ind = None - elif event.key=='d': - ind = self.get_ind_under_point(event) - if ind is not None: - self.poly.xy = [tup for i,tup in enumerate(self.poly.xy) if i!=ind] - self.line.set_data(zip(*self.poly.xy)) - elif event.key=='i': - xys = self.poly.get_transform().transform(self.poly.xy) - p = event.x, event.y # display coords - for i in range(len(xys)-1): - s0 = xys[i] - s1 = xys[i+1] - d = dist_point_to_segment(p, s0, s1) - if d<=self.epsilon: - self.poly.xy = array( - list(self.poly.xy[:i]) + - [(event.xdata, event.ydata)] + - list(self.poly.xy[i:])) - self.line.set_data(zip(*self.poly.xy)) - break - - - self.canvas.draw() - - def motion_notify_callback(self, event): - 'on mouse movement' - if not self.showverts: return - if self._ind is None: return - if event.inaxes is None: return - if event.button != 1: return - x,y = event.xdata, event.ydata - - self.poly.xy[self._ind] = x,y - self.line.set_data(zip(*self.poly.xy)) - - self.canvas.restore_region(self.background) - self.ax.draw_artist(self.poly) - self.ax.draw_artist(self.line) - self.canvas.blit(self.ax.bbox) - - - -from pylab import * - - - - - -fig = figure() -theta = arange(0, 2*pi, 0.1) -r = 1.5 - -xs = r*cos(theta) -ys = r*sin(theta) - -poly = Polygon(zip(xs, ys,), animated=True) - - - - -ax = subplot(111) -ax.add_patch(poly) -p = PolygonInteractor( ax, poly) - -#ax.add_line(p.line) -ax.set_title('Click and drag a point to move it') -ax.set_xlim((-2,2)) -ax.set_ylim((-2,2)) -show() Deleted: trunk/matplotlib/examples/pylab/pylab_with_gtk.py =================================================================== --- trunk/matplotlib/examples/pylab/pylab_with_gtk.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/pylab_with_gtk.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,54 +0,0 @@ -""" -An example of how to use pylab to manage your figure windows, but -modify the GUI by accessing the underlying gtk widgets -""" -import matplotlib -matplotlib.use('GTKAgg') -from pylab import get_current_fig_manager, subplot, plot, legend, connect, show - -ax = subplot(111) -plot([1,2,3], 'ro-', label='easy as 1 2 3') -plot([1,4,9], 'gs--', label='easy as 1 2 3 squared') -legend() - - -manager = get_current_fig_manager() -# you can also access the window or vbox attributes this way -toolbar = manager.toolbar - -# now let's add a button to the toolbar -import gtk -next = 8; #where to insert this in the mpl toolbar -button = gtk.Button('Click me') -button.show() - -def clicked(button): - print 'hi mom' -button.connect('clicked', clicked) - -toolitem = gtk.ToolItem() -toolitem.show() -toolitem.set_tooltip( - toolbar.tooltips, - 'Click me for fun and profit') - -toolitem.add(button) -toolbar.insert(toolitem, next); next +=1 - -# now let's add a widget to the vbox -label = gtk.Label() -label.set_markup('Drag mouse over axes for position') -label.show() -vbox = manager.vbox -vbox.pack_start(label, False, False) -vbox.reorder_child(manager.toolbar, -1) - -def update(event): - if event.xdata is None: - label.set_markup('Drag mouse over axes for position') - else: - label.set_markup('<span color="#ef0000">x,y=(%f, %f)</span>'%(event.xdata, event.ydata)) - -connect('motion_notify_event', update) - -show() Deleted: trunk/matplotlib/examples/pylab/strip_chart_demo.py =================================================================== --- trunk/matplotlib/examples/pylab/strip_chart_demo.py 2008-05-17 22:05:52 UTC (rev 5186) +++ trunk/matplotlib/examples/pylab/strip_chart_demo.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -1,72 +0,0 @@ -""" -Emulate an oscilloscope. Requires the animation API introduced in -matplotlib 0.84. See -http://www.scipy.org/wikis/topical_software/Animations for an -explanation. - -This example uses gtk but does not depend on it intimately. It just -uses the idle handler to trigger events. You can plug this into a -different GUI that supports animation (GTKAgg, TkAgg, WXAgg) and use -your toolkits idle/timer functions. -""" -import gobject, gtk -import matplotlib -matplotlib.use('GTKAgg') -import numpy as np -from matplotlib.lines import Line2D - - -class Scope: - def __init__(self, ax, maxt=10, dt=0.01): - self.ax = ax - self.canvas = ax.figure.canvas - self.dt = dt - self.maxt = maxt - self.tdata = [0] - self.ydata = [0] - self.line = Line2D(self.tdata, self.ydata, animated=True) - self.ax.add_line(self.line) - self.background = None - self.canvas.mpl_connect('draw_event', self.update_background) - self.ax.set_ylim(-.1, 1.1) - self.ax.set_xlim(0, self.maxt) - - def update_background(self, event): - self.background = self.canvas.copy_from_bbox(self.ax.bbox) - - def emitter(self, p=0.01): - 'return a random value with probability p, else 0' - v = np.random.rand(1) - if v>p: return 0. - else: return np.random.rand(1) - - def update(self, *args): - if self.background is None: return True - y = self.emitter() - lastt = self.tdata[-1] - if lastt>self.tdata[0]+self.maxt: # reset the arrays - self.tdata = [self.tdata[-1]] - self.ydata = [self.ydata[-1]] - self.ax.set_xlim(self.tdata[0], self.tdata[0]+self.maxt) - self.ax.figure.canvas.draw() - - self.canvas.restore_region(self.background) - - t = self.tdata[-1] + self.dt - self.tdata.append(t) - self.ydata.append(y) - self.line.set_data(self.tdata, self.ydata) - self.ax.draw_artist(self.line) - - self.canvas.blit(self.ax.bbox) - return True - - -from pylab import figure, show - -fig = figure() -ax = fig.add_subplot(111) -scope = Scope(ax) -gobject.idle_add(scope.update) - -show() Copied: trunk/matplotlib/examples/user_interfaces/interactive.py (from rev 5186, trunk/matplotlib/examples/pylab/interactive.py) =================================================================== --- trunk/matplotlib/examples/user_interfaces/interactive.py (rev 0) +++ trunk/matplotlib/examples/user_interfaces/interactive.py 2008-05-18 21:06:13 UTC (rev 5187) @@ -0,0 +1,230 @@ +#!/usr/bin/env python +"""Multithreaded interactive interpreter with GTK and Matplotlib support. + +Usage: + + pyint-gtk.py -> starts shell with gtk thread running separately + + pyint-gtk.py -pylab [filename] -> initializes matplotlib, optionally running + the named file. The shell starts after the file is executed. + +Threading code taken from: +http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian +McErlean and John Finlay. + +Matplotlib support taken from interactive.py in the matplotlib distribution. + +Also borrows liberally from code.py in the Python standard library.""" + +__author__ = "Fernando Perez <Fer...@co...>" + +import sys +import code +import threading + +import gobject +import gtk + +try: + import readline +except ImportError: + has_readline = False +else: + has_readline = True + +class MTConsole(code.InteractiveConsole): + """Simple multi-threaded shell""" + + def __init__(self,on_kill=None,*args,**kw): + code.InteractiveConsole.__init__(self,*args,**kw) + self.code_to_run = None + self.ready = threading.Condition() + self._kill = False + if on_kill is None: + on_kill = [] + # Check that all things to kill are callable: + for _ in on_kill: + if not callable(_): + raise TypeError,'on_kill must be a list of callables' + self.on_kill = on_kill + # Set up tab-completer + if has_readline: + import rlcompleter + try: # this form only works with python 2.3 + self.completer = rlcompleter.Completer(self.locals) + except: # simpler for py2.2 + self.completer = rlcompleter.Completer() + + readline.set_completer(self.completer.complete) + # Use tab for completions + readline.parse_and_bind('tab: complete') + # This forces readline to automatically print the above list when tab + # completion is set to 'complete'. + readline.parse_and_bind('set show-all-if-ambiguous on') + # Bindings for incremental searches in the history. These searches + # use the string typed so far on the command line and search + # anything in the previous input history containing them. + readline.parse_and_bind('"\C-r": reverse-search-history') + readline.parse_and_bind('"\C-s": forward-search-history') + + def runsource(self, source, filename="<input>", symbol="single"): + """Compile and run some source in the interpreter. + + Arguments are as for compile_command(). + + One several things can happen: + + 1) The input is incorrect; compile_command() raised an + exception (SyntaxError or OverflowError). A syntax traceback + will be printed by calling the showsyntaxerror() method. + + 2) The input is incomplete, and more input is required; + compile_command() returned None. Nothing happens. + + 3) The input is complete; compile_command() returned a code + object. The code is executed by calling self.runcode() (which + also handles run-time exceptions, except for SystemExit). + + The return v... [truncated message content] |