[matplotlib-devel] partial ring patch
Hi,
We found we needed to draw a partial ring, but didn't see one in
patches.py.
Attached is a generalization of Wedge to accept an inner and an outer
radius.
Should I add this to patches?
Note that rather saving the unit ring and constructing a transform as
in Wedge:
def get_patch_transform(self):
x = self.convert_xunits(self.center[0])
y = self.convert_yunits(self.center[1])
rx = self.convert_xunits(self.r2)
ry = self.convert_yunits(self.r2)
self._patch_transform = transforms.Affine2D() \
.scale(rx, ry).translate(x, y)
return self._patch_transform
I just transform the coordinates directly:
v *= r2
v += numpy.array(center)
self._path = Path(v,c)
self._patch_transform = transforms.IdentityTransform()
Any reason to prefer one over the other?
- Paul
from math import fmod
import numpy
import matplotlib.cbook as cbook
import matplotlib.transforms as transforms
import matplotlib.artist as artist
import matplotlib.patches as patches
from matplotlib.path import Path
class Ring(patches.Patch):
"""
Ring patch.
"""
def __str__(self):
return "Ring(%g,%g,%g,%g)"%(self.r1,self.r2,self.theta1,self.theta2)
def __init__(self,
center=(0,0),
r1=0,
r2=None,
theta1=0,
theta2=360,
**kwargs
):
"""
Draw a ring centered at *x*, *y* center with inner radius *r1* and
outer radius *r2* that sweeps *theta1* to *theta2* (in degrees).
Valid kwargs are:
%(Patch)s
"""
patches.Patch.__init__(self, **kwargs)
self.center = center
self.r1, self.r2 = r1,r2
self.theta1, self.theta2 = theta1,theta2
# Inner and outer rings are connected unless the annulus is complete
delta=abs(theta2-theta1)
if fmod(delta,360)<=1e-12*delta:
theta1,theta2 = 0,360
connector = Path.MOVETO
else:
connector = Path.LINETO
# Form the outer ring
arc = Path.arc(theta1,theta2)
if r1 > 0:
# Partial annulus needs to draw the outter ring
# followed by a reversed and scaled inner ring
v1 = arc.vertices
v2 = arc.vertices[::-1]*float(r1)/r2
v = numpy.vstack([v1,v2,v1[0,:],(0,0)])
c = numpy.hstack([arc.codes,arc.codes,connector,Path.CLOSEPOLY])
c[len(arc.codes)]=connector
else:
# Wedge doesn't need an inner ring
v = numpy.vstack([arc.vertices,[(0,0),arc.vertices[0,:],(0,0)]])
c = numpy.hstack([arc.codes,[connector,connector,Path.CLOSEPOLY]])
v *= r2
v += numpy.array(center)
self._path = Path(v,c)
self._patch_transform = transforms.IdentityTransform()
__init__.__doc__ = cbook.dedent(__init__.__doc__) % artist.kwdocd
def get_path(self):
return self._path
def demo():
import pylab
axes = pylab.gca()
# Full ring
axes.add_patch(Ring(center=(3,3),r1=4, r2=7,theta1=70,theta2=70,
fill=True,fc='yellow',ec='darkblue',alpha=0.5))
# Full circle
axes.add_patch(Ring(center=(-3,-3),r2=4,
fill=True,fc='purple',ec='darkblue',alpha=0.6))
# Filled segment
axes.add_patch(Ring(r1=5,r2=10,theta1=0,theta2=90,
fill=True,fc='gray',ec='black',alpha=0.2))
# Unfilled segment
axes.add_patch(Ring(r1=6,r2=8,theta1=30,theta2=280,fill=False,ec='black'))
# Overlapping segment
axes.add_patch(Ring(r1=3,r2=9,theta1=80,theta2=130,
fill=True,fc='orange',ec='black',alpha=0.2))
# Unfilled wedge
axes.add_patch(Ring(r2=7,theta1=170,theta2=220,
fill=False,fc='orange',ec='green',alpha=0.2))
# Wedge
axes.add_patch(Ring(r2=7,theta1=70,theta2=220,
fill=False,fc='blue',ec='darkblue',alpha=0.6))
## Wedge
#from matplotlib.patches import Wedge
#axes.add_patch(Wedge((0,0),r=7,theta1=70,theta2=220,
# fill=False,fc='blue',ec='darkblue',alpha=0.6))
pylab.axis('equal')
#pylab.axis([-10,10,-10,10])
pylab.show()
if __name__ == "__main__": demo()
One problem is that I had to explicitly set the axes limits 1because
add_patch
wasn't updating the limits to include the bounds of the new patch.-
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/___
Matplotlib-devel mailing list
[email protected]
http
Re: [matplotlib-devel] partial ring patch
On Nov 14, 2008, at 9:59 AM, Michael Droettboom wrote: > Paul Kienzle wrote: >> Hi, >> >> We found we needed to draw a partial ring, but didn't see one in >> patches.py. >> >> Attached is a generalization of Wedge to accept an inner and an >> outer radius. >> >> Should I add this to patches? > Looks like a useful feature to me. Could be used for doing these > sort of "hierarchical pie chart" graphs: > > http://linux.byexamples.com/wp-content/uploads/2007/04/baobab.png That's pretty, though I have no idea what it is supposed to represent. > > Any reason not to implement this simply as an additional kwarg to > Wedge, rather than a new class -- since Ring with a r2 == 0 is > equivalent to Wedge anyway? Just thinking of having less code to > maintain...but maybe that's more confusing for end users. Okay, I will replace Wedge on svn. - Paul - This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] partial ring patch
On Nov 14, 2008, at 12:36 PM, Paul Kienzle wrote: >> >> Any reason not to implement this simply as an additional kwarg to >> Wedge, rather than a new class -- since Ring with a r2 == 0 is >> equivalent to Wedge anyway? Just thinking of having less code to >> maintain...but maybe that's more confusing for end users. > > Okay, I will replace Wedge on svn. Done. The keyword I used is *width* for the width of the ring. Using width=None draws the whole wedge. - Paul - This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Native backend for Mac OS X
On Dec 19, 2008, at 7:52 AM, John Hunter wrote: > Could you post the script you are using to do the profiling? The call > to subplot/plot/bar should not trigger a draw, unless "interactive" is > set to True > > http://matplotlib.sourceforge.net/users/shell.html > > Interactive is not the best word, but it is the rc parameter meaning > "you are using mpl from the interactive prompt and want every pyplot > command to update the plot". If the macosx backend is not doing this > it should. If tkagg is issuing draw commands on pyplot commands when > interactive is False, it is a bug that we should be able to fix. The interactive backends (wx, tk, gtk) all handle draw_idle in a way which delays the drawing until there are no more commands to run. By changing draw_if_interactive to use draw_idle instead of draw, wouldn't this automatically smooth over the performance issues without the user having to toggle interactive in their scripts? - Paul -- ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] matplotlib+setuptools
Hi,
I'm sending a little module I use to force a particular version of
matplotlib and backend in my library.
This is imported in my package __init__.py to make sure the
environment is sane. It can also be imported in the beginning of the
app to set up a sane environment, which may be necessary if the app
uses matplotlib outside my library.
I don't think there is anything we can do within matplotlib to
address the version requirements.
The backend check could be a little easier if we modify matplotlib.use
() to be silent if the backend is already in use, or raise an error
if it isn't. ImportError seems appropriate, since use() is kind of
like an import. Calling switch_backend() is another option.
- Paul
# This program is public domain
"""
Configure plotter for plottools.
This must be imported first in __init__.py for plottools.
If your application uses matplotlib outside plottools, then
please do the following at the start of your application:
# Select matplotlib version and backend
import danse.common.plottools.config
Note that plottools requires particular versions of matplotlib
and a particular backend. As of this writing it is the WXAgg
backend for matplotlib>=0.98.
The plottools package uses pkg_resources if available to select
the correct version of matplotlib. If you need multiple matplotlib
versions in your path, be sure to use "easy_install -m" for all
of them. If a version is installed without "-m" that does not
meet the requirements, then pkg_resources.require() will fail,
even if you have installed a suitable version with "-m". In this
case you will need to fix up your site-packages directory,
probably by removing site-packages/matplotlib and the associated
egg file for that version, and reinstalling with "-m". You may
also need to edit site-packages/easy-install.pth.
"""
import sys
__all__ = []
plot_version="0.98"
plot_backend="WXAgg"
# Sort out matplotlib version
try:
import pkg_resources
pkg_resources.require("matplotlib>="+plot_version)
except ImportError:
import matplotlib
from distutils.version import StrictVersion as Version
if Version(matplotlib.__version__) < Version(plot_version):
raise ImportError("Matplotlib version must be %s or newer"%(plot_version,))
# Sort out matplotlib backend
import matplotlib
if 'matplotlib.backends' not in sys.modules:
# if no backend yet, be sure to use the correct one
matplotlib.use(plot_backend)
elif matplotlib.get_backend() != plot_backend:
# if a backend has already been selected, make sure it is the correct one.
raise ImportError("Matplotlib not using backend "+plot_backend)
--
Check out the new SourceForge.net Marketplace.
It is the best place to buy or sell services for
just about anything Open Source.
http://p.sf.net/sfu/Xq1LFB___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Matplotlib patch on EPD trac?
On Jan 9, 2009, at 6:12 PM, Ryan May wrote: > Maybe it's time to refactor here to get routine(s) that operate how > we want (IMO > more sanely than Matlab), and we provide wrappers that give Matlab- > like behavior. > Maybe we can also get these sane routines upstream into Scipy. At > that point, > however, I'm not sure what to do about the plotting functions, > since there's a > variety of behavior. My policy when working on Octave was to avoid inventing new interfaces when the existing interfaces are good enough. This doesn't apply to the same degree in pylab of course because there is little hope of running matlab code directly off the net, but it still helps users if things with the same name share the same interface. It would not be good if importing psd from the matlab compatibility package gave a different interface than the same function name imported directly from mpl or scipy. In terms of refactoring, consider having a spectral density object. The following properties of psd naturally lends itself to an object interface: * a number of related functions (psd, csd, transfer function, coherence) can be calculated from the same internal state * the state can be fed new inputs and updated frame by frame, * confidence intervals may or may not be requested, * data can be plotted in multiple ways * users may want to extract the data for further processing It would be pretty easy to build the matlab interface on top of such an object. - Paul -- This SF.net email is sponsored by: SourcForge Community SourceForge wants to tell your story. http://p.sf.net/sfu/sf-spreadtheword ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] interactive property editor
Hi, What's the status of interactive property editors for mpl graphs? I would like something that would allow me to change properties such as the size and position of the graph, grids, scales, ranges, colors, symbols, line styles, fonts, etc., and add annotations. Some of this already exists, but allowing users to enter specific values will need an underlying widget toolkit. Does anybody have anything that I can build on for wx? Thanks, - Paul -- Apps built with the Adobe(R) Flex(R) framework and Flex Builder(TM) are powering Web 2.0 with engaging, cross-platform capabilities. Quickly and easily build your RIAs with Flex Builder, the Eclipse(TM)based development software that enables intelligent coding and step-through debugging. Download the free 60 day trial. http://p.sf.net/sfu/www-adobe-com ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] interactive property editor
On Mar 12, 2009, at 9:49 AM, Michael Droettboom wrote: > We've done some experiments with Enthought Traits at various times to > address this issue. There were always various obstacles to making it > work, but it may be worth another look. Traits has its nice auto- > built > property editors (that may address your request), but it would also > address one of my long-standing niggles that properties of graphs are > often checked far too late and the error messages presented to the > user > are very obscured because of it. > > Of course, all that is a major undertaking -- basically rewriting all > the getters and setters on the artist classes to use traits -- but I > could see it having quite the payoff in the end. > I'm not sure if traits can do it. I would like to see CSS-like properties, so that when I change the font size on the graph, the title, which is size +2, and the legend which is size -1 also get updated. I can imagine changing the font for an axes, for a figure or for all figures. The latter should be stored in a resource file so it doesn't have to be done every session. Properties which are not set should look up their values elsewhere; if the property of some object has been specialized, then it should not change when the figure properties are set. Properties for printed figures may be different from properties of figures on the screen, e.g., because the printer is monochrome. Eventually I would like interactive editing of properties by point and click. Particularly for plotted data the question will be whether the change applies to the data point only, to its line, or to all lines on the graph, to all graphs on the figure, or to all figures, depending on the property. Doing this without cluttering the UI will be a challenge. - Paul -- Apps built with the Adobe(R) Flex(R) framework and Flex Builder(TM) are powering Web 2.0 with engaging, cross-platform capabilities. Quickly and easily build your RIAs with Flex Builder, the Eclipse(TM)based development software that enables intelligent coding and step-through debugging. Download the free 60 day trial. http://p.sf.net/sfu/www-adobe-com ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] ginput_rect
Hi, I wanted to be able to select a rectangular region from the graph as one part of a script so I combined BlockingInput and RectangleSelector to create BlockingRectangleSelector, and the pylab style interface function, ginput_rect This serves my immediate needs and I'm unlikely to develop it further. Before adding it to matplotlib a couple of changes are needed:: * Other kinds of selectors, such as span, line and lasso should be possible * Selectors such as RectangularSelector can be added to a set of axes but not removed. Removing them requires unhooking the mpl_connect callbacks, but the cid is not being saved. * The graph wasn't always drawn before selection in ipython or before a subsequent show() so I forced it with explicit draw_idle() calls. This may lead to unnecessary redraws. - Paul # This program is public domain # Author: Paul Kienzle """ Select a region of the graph. ginput_rect(ax) selects a region from the axes and continues the script. s = BlockingRectangleSelector(ax) adds a rectangle selector to the axes and lets the script call s.select() whenever a new region is needed. demo() shows the selector in action. """ from matplotlib.pyplot import gca from matplotlib.widgets import RectangleSelector from matplotlib.blocking_input import BlockingInput class BlockingRectangleSelector: """ Blocking rectangle selector selects once then continues with script. """ def __init__(self, ax=None): if ax is None: ax=gca() self.ax = ax # drawtype is 'box' or 'line' or 'none' self.selector = RectangleSelector(self.ax, self._callback, drawtype='box',useblit=True, minspanx=5,minspany=5,spancoords='pixels') self.selector.set_active(False) self.block = BlockingInput(self.ax.figure) def _callback(self, event1, event2): """ Selection callback. event1 and event2 are the press and release events """ x1, y1 = event1.xdata, event1.ydata x2, y2 = event2.xdata, event2.ydata if x1>x2: x1,x2 = x2,x1 if y1>y2: y1,y2 = y2,y1 self.x1,self.x2,self.y1,self.y2 = x1,x2,y1,y2 self.ax.figure.canvas.stop_event_loop() def select(self): """ Wait for box to be selected on the axes. """ # Make sure the graph is drawn before select. # This appears to be needed for ipython. self.ax.figure.canvas.draw_idle() # Wait for selector to complete self.selector.set_active(True) self.block() self.selector.set_active(False) # Force redraw, otherwise next show() doesn't # update the graph. #self.ax.figure.canvas.draw_idle() def remove(self): """ Remove the selector from the axes. Note: this currently does nothing since matplotlib doesn't allow widgets to be removed from axes. """ pass # rectangle widget can't be removed from axes def ginput_rect(ax=None): """ Wait for user to select a region on the axes. Returns x1,x2,y1,y2 """ s = BlockingRectangleSelector(ax=ax) s.select() s.remove() return s.x1,s.x2,s.y1,s.y2 def demo(): # Example comes from matplotlib/examples/rectangle_selector.py from numpy import arange, sin, cos, pi from pylab import subplot, plot, axis, show subplot(111) # If N is large one can see improvement by blitting! N=10 x=10.0*arange(N)/(N-1) plot(x,sin(.2*pi*x),lw=3,c='b',alpha=.7) plot(x,cos(.2*pi*x),lw=3.5,c='r',alpha=.5) plot(x,-sin(.2*pi*x),lw=3.5,c='g',alpha=.3) print "\n click --> release" x1,x2,y1,y2 = ginput_rect() print "(%3.2f, %3.2f) --> (%3.2f, %3.2f)"%(x1,y1,x2,y2) # Zoom in to the selected rectangle axis([x1, x2, y1, y2]) show() if __name__ == "__main__": demo() -- Come build with us! The BlackBerry(R) Developer Conference in SF, CA is the only developer event you need to attend this year. Jumpstart your developing skills, take BlackBerry mobile applications to market and stay ahead of the curve. Join us from November 9 - 12, 2009. Register now! http://p.sf.net/sfu/devconference___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] mac install 1.0.0
Note a small issue on the install of matplotlib-1.0.0 python 2.6 mac dmg. The files in mpl-data/images were not installed with read permissions for all. This resulted in an error that _cidgcf was not a valid attribute in FigureManager. This affected one 10.5 machine but not another --- we have no idea why. - Paul -- Start uncovering the many advantages of virtual appliances and start using them to simplify application deployment and accelerate your shift to cloud computing. http://p.sf.net/sfu/novell-sfdev2dev ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] canvas objects
Hi, I've been playing with the pick infrastructure in 0.90 and find that it doesn't meet my needs. The issue is that events from all artists go to the same callback, so you are forced write your callback as a series of if statements for each artist which may receive a pick event. I would rather have an infrastructure more like a canvas, where I can register callbacks to particular handles for particular mouse events (enter, leave, motion, press and release). I would like to rely on the zorder attribute of artists when processing the events. If the callback succeeds, then the event is consumed and no more handles are checked. If the callback fails then the next lower zorder handle is checked. I can simulate what I want with the current infrastructure by having the mouse events call figure.pick() and the pick event capture every object that was picked, but it is ugly and not very efficient (not every object wants to track enter/motion/leave events for example, but they get asked on every pick even if they only want to monitor mouse clicks). Instead I would like to start by splitting the current pick method into two parts: contains(event,picker) which returns truth value,details pick(event) which generates the current pick event Later I can construct the infrastructure I want on the contains() function for each artist. Does this approach seem reasonable to those who will approve the patches I will send? Thanks, Paul Kienzle [EMAIL PROTECTED] - This SF.net email is sponsored by DB2 Express Download DB2 Express C - the FREE version of DB2 express and take control of your XML. No limits. Just data. Click to get it now. http://sourceforge.net/powerbar/db2/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] canvas objects
On Fri, Jul 06, 2007 at 10:15:48AM -0500, John Hunter wrote: > On 7/6/07, Paul Kienzle <[EMAIL PROTECTED]> wrote: > > Hi, > > > > I've been playing with the pick infrastructure in 0.90 and find that > > it doesn't meet my needs. The issue is that events from all artists > > go to the same callback, so you are forced write your callback as a > > series of if statements for each artist which may receive a pick event. > > I definitely agree that having to write one callback for all the > different objects you may want to pick on is a bad design, so I'd be > happy to see something better. Do you think it would make sense to > register callbacks with a given artist -- eg if you are picked call me > -- or with a class (eg all Line3D picks call me), or do you have > another approach in mind? I definitely want to be able to associate different callbacks with different specific artists. For example, I might want to define a gaussian peak that I want to drag around and match to the peak in some data. The data and the peak will both be represented using lines, but I only want to drag the peak, not the data. Having a default callback for a class may be useful in many places as well, such as automatically highlighting the corresponding legend entry on mouseover. For now I have no opinion on whether the additional complexity is worthwhile. - Paul - This SF.net email is sponsored by DB2 Express Download DB2 Express C - the FREE version of DB2 express and take control of your XML. No limits. Just data. Click to get it now. http://sourceforge.net/powerbar/db2/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] canvas objects
On Fri, Jul 06, 2007 at 10:15:48AM -0500, John Hunter wrote: > On 7/6/07, Paul Kienzle <[EMAIL PROTECTED]> wrote: > > Instead I would like to start by splitting the current pick method > > into two parts: > >contains(event,picker) which returns truth value,details > >pick(event) which generates the current pick event > > I don't really understand the contains part -- can you elaborate a little bit? > > I would definitely be amenable to accepting patches that improve the > current API :-) I have an initial patch against CVS available which implements contains() for most classes. Legend is too complex for simple hacks. I have a number of questions regarding details of implementation, in particular determining sizes of things on the plot. The question now is what to do with it? I can post it to the patch tracker on sourceforge, but I'm hesitant to do so since it still has issues. Do you want it there or on the list? Let me know... - Paul - This SF.net email is sponsored by DB2 Express Download DB2 Express C - the FREE version of DB2 express and take control of your XML. No limits. Just data. Click to get it now. http://sourceforge.net/powerbar/db2/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] canvas objects
On Fri, Jul 06, 2007 at 05:31:58PM -0400, Paul Kienzle wrote: > On Fri, Jul 06, 2007 at 10:15:48AM -0500, John Hunter wrote: > > On 7/6/07, Paul Kienzle <[EMAIL PROTECTED]> wrote: > > > Instead I would like to start by splitting the current pick method > > > into two parts: > > >contains(event,picker) which returns truth value,details > > >pick(event) which generates the current pick event > > > > I don't really understand the contains part -- can you elaborate a little > > bit? > > > > I would definitely be amenable to accepting patches that improve the > > current API :-) > > I have an initial patch against CVS available which implements > contains() for most classes. Legend is too complex for simple hacks. > I have a number of questions regarding details of implementation, > in particular determining sizes of things on the plot. > > The question now is what to do with it? I can post it to the patch > tracker on sourceforge, but I'm hesitant to do so since it still > has issues. Do you want it there or on the list? I submitted the 'contains' patch to the patch tracker on sourceforge. I've worked out most of the issues, including selecting lines instead of just points. I still haven't addressed legend picking, and I don't know how to handle line offsets. I'm also unhappy with relying on a cached renderer for some of the size checks (e.g., text extents). One solution is to send this along with the 'contains' test, though that would mean changing the interface to pick. Any other suggestions? In backend_bases.FigureCanvasBase.__init__ there is an "if False" statement. Turn it to True and all objects on every graph will be highlighted as the mouse hovers over them and restored when it moves away. I worked through many of the demos in the repository to check that the various objects are recognized. Sorry about the size of the patch --- I wanted to keep the system in a working state so I had to do everything. Also I spent some time writing __str__ methods for a lot of the artists so that it was easier for me to debug. Let me know if you want these stripped and sent as a separate patch. - Paul - This SF.net email is sponsored by DB2 Express Download DB2 Express C - the FREE version of DB2 express and take control of your XML. No limits. Just data. Click to get it now. http://sourceforge.net/powerbar/db2/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] canvas objects
On Sun, Jul 08, 2007 at 03:04:41AM -0400, Paul Kienzle wrote:
> I submitted the 'contains' patch to the patch tracker on sourceforge.
I've updated the 'contains' patch to handle figure enter/leave, at
least on wx backends, and fixed a minor hit test bug in ellipse.
I've also removed the special status of the pick event notifier,
using the mpl_connect event processing framework to handle it.
You can attach the enter/leave artist highlighting demo to a
figure using:
figure.canvas.mpl_connect("motion_notify_event",figure.canvas.hilite)
You can disable pick on a figure using:
fig.canvas.mpl_disconnect(fig.canvas.button_pick_id)
fig.canvas.mpl_disconnect(fig.canvas.scroll_pick_id)
Now I can work on an event handling framework which connects
directly to the artists rather than filtering all callbacks to
the same pick function. I'll mostly follow tk canvas handling
conventions unless anyone has suggests for a better approach.
- Paul
-
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] canvas objects
On Mon, Jul 09, 2007 at 10:37:35AM -0500, John Hunter wrote:
> One minor bug I fixed for non wx backends in the (very cool)
> figure.canvas.mpl_connect("motion_notify_event",figure.canvas.hilite)
> functionality. gui_repaint is a wx only method, and I just commented
> it out and replaced the "draw" with a draw_idle. This should work
> across backends. Note draw_idle by default in backend_bases just
> calls draw, but backends can override it to use their GUIs idle
> handler. This is usually a good idea so you don't get an event pile
> up. In particular, it is not implemented for backend_wx, so one of
> you wx gurus/users may want to consider adding it, because for
> interactive stuff like motion events, it can be a big win.
This change works for me under wx os OS X.
I got the gui_paint idea from examples/dynamic_demo_wx.py. Replacing
gui_paint with draw_idle seems to work okay there as well. I'll
create a patch. Do you small patches like this on tracker as well?
- Paul
-
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] numpification and imports
On Fri, Jul 13, 2007 at 03:06:45PM -0500, John Hunter wrote:
> Because the mpl_ prefix occurs nowhere else, we can easily change this
> to whatever we want with a single search replace.
I haven't sync'd with the repository yet so I can check this assertion:
h123063:~/src/matplotlib$ find . -name "*.py" | xargs grep mpl_ | wc
191 627 20498
These are mostly mpl_connect and mpl_disconnect, so not too bad.
The only other use of mpl_ is the following:
h123063:~/src/matplotlib$ find . -name "*.py" | xargs grep mpl_ | grep -v
mpl_connect | grep -v mpl_disconnect
./examples/mpl_with_glade.py:self.widgets =
gtk.glade.XML('mpl_with_glade.glade')
./lib/matplotlib/backends/backend_wx.py: - mpl_with_glade.py | N/A
(2) | N/A (2) |
./OME/python/matplotlib/backends/backend_wx.py: - mpl_with_glade.py |
N/A (2) | N/A (2) |
- Paul
-
This SF.net email is sponsored by DB2 Express
Download DB2 Express C - the FREE version of DB2 express and take
control of your XML. No limits. Just data. Click to get it now.
http://sourceforge.net/powerbar/db2/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] remove artist from axes?
Hi, I don't see an obvious way to remove a line from an axes object. Shall I add remove_child(h) which searches through all the lists of containers and removes the one that I don't want? For now I will rerender the graph without the missing child. - Paul - This SF.net email is sponsored by DB2 Express Download DB2 Express C - the FREE version of DB2 express and take control of your XML. No limits. Just data. Click to get it now. http://sourceforge.net/powerbar/db2/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] sandbox
Hi, I've made some progress on an MPL canvas infrastructure built on top of the contains() methods patch I submitted earlier (and now in svn). I would like to post it to svn so that interested parties can play with it and contribute to the development, but it is not yet ready to be put in the trunk. I was browsing the svn tree looking for a sandbox to put it in, but the closest I found is /matplotlib/branches. Any objections to me putting it into /matplotlib/branches/canvas? Thanks in advance, - Paul - This SF.net email is sponsored by DB2 Express Download DB2 Express C - the FREE version of DB2 express and take control of your XML. No limits. Just data. Click to get it now. http://sourceforge.net/powerbar/db2/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] remove artist from axes?
On Mon, Jul 16, 2007 at 08:38:17AM -0500, John Hunter wrote: > On 7/15/07, Paul Kienzle <[EMAIL PROTECTED]> wrote: > > Hi, > > > > I don't see an obvious way to remove a line from an axes object. > > > > Shall I add remove_child(h) which searches through all the lists > > of containers and removes the one that I don't want? > > That's one way to do it, but you might consider something along the > lines -- every time someone adds an Artist anywhere in the figure, > they add an entry into a Figure remove dictionary that maps the artist > to a function to remove it > > class Figure: > def register_remove(self, artist, func): > 'register a function to remove an artist' > self.removemap[artist] = func > self.lastArtist = artist # this can be used to handle Gael's request > > def remove_artist(self, artist): > 'remove the artist' > func = self.removemap.get(artist, None) > if func is None: return > func() # poof, it's gone > del self.removemap(artist) > > def remove_last(self): > 'remove the most recently registered artist' > self.remove_artist(self.lastArtist) > self.lastArtist = None > class Axes: > def add_line(self, line): > self.figure.register_remove(line, lambda x: self.lines.remove(line)) > self.lines.append(line) I'm not to keen on yet another registry, especially since it will have to be maintained when, e.g., cla() is called. How about storing the remove function with the artist itself? Then it would just be h.remove() rather than fig.remove_artist(h). BTW, I can't think of a use case for 'remove last' from an applications standpoint. Maybe it would be useful to someone entering plot commands from the console, but even then it is a poor substitute for 'undo'. > Then the user won't need to know whether the artist is stored by the > Axes, Axis, XTick, etc... This is likely more efficient and easier to > implement than recursively searching On the topic of efficiency, every tick line (1,2) grid line (1,2) and every tick label (1,2) has an artist associated with it. Is there any reason not to represent this as one or two line collections and a text collection? Our application has multiple panels in a wxAUI interface, and graph rendering is slow even on tiny data sets. - Paul - This SF.net email is sponsored by DB2 Express Download DB2 Express C - the FREE version of DB2 express and take control of your XML. No limits. Just data. Click to get it now. http://sourceforge.net/powerbar/db2/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] negative log transforms
On Tue, Jul 17, 2007 at 08:33:47AM -0500, John Hunter wrote: > Speaking of branches, we may need to seriously consider a branch here, > mpl1. The changes here may involve breaking a fair amount of code, > which I don't mind doing to get it right, but I'm somewhat inclined to > branch off here for matplotlib1.0, with the goal of using traits, > fixing axis handling (eg multiple y-axis with arbitrary placement), > and rewriting the transforms. On the topic of transforms, I would like to be able to do dynamic range compression on a decaying oscillatory signal. Think of it as a logarithmic axis which supports negative numbers. AFAICT, the current transform infrastructure does not allow me to add this as a third party package. The axis would look something like: |- 10**2 | |- 10**1 | |- 10**0 | |- 10**-1 | |- 0 | |- -10**-1 | |- -10**0 As well as a max and min parameter, there would have to be a cutoff parameter. For auto axes, choose a cutoff which allows a reasonable number of decades to be displayed (I'm guessing reasonable is seven). The transform would be something like the following: if (x[i] > cut) newx[i] = log10(x[i]) - log10cut; else if (x[i] < -cut) newx[i] = log10cut - log10(-x[i]); else newx[i] = 0.; with inverse: if (x[i] < 0) newx[i] = -pow(10.0, log10cut - x[i]); else if (x[i] > 0) newx[i] = pow(10.0, x[i] - log10cut); else x[i] = 0. Even extending the current LOG10 support would present a challenge of how to get the cut value into the transform. Suggestions how I can implement this in the current architecture, or should I wait for the new transforms code? - Paul - This SF.net email is sponsored by DB2 Express Download DB2 Express C - the FREE version of DB2 express and take control of your XML. No limits. Just data. Click to get it now. http://sourceforge.net/powerbar/db2/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] negative log transforms
On Tue, Jul 17, 2007 at 11:54:19AM -0400, Perry Greenfield wrote: > This is exactly the sort of thing that I thought a transform approach > would make easier to do. So if it isn't urgent, waiting probably > would be better. (by the way, we see exactly the same sort of log > scale you propose in one of our older (non-python) packages. So there > is a call for this sort of thing. This is not an urgent project. I'm going to finish work on the canvas objects first, and use them for a couple of applications such as a 2D mesh slicer and a multiple peak fitter. It will be a couple of months before we need to address log scales. I wonder if it is worth refactoring the code with the idea of allowing transforms to be implemented in Python+Numpy. It will mean redoing data structures so that vertices for things like line collections and tic marks are stored in dense arrays which can be transformed en masse rather than point by point. I haven't looked closely enough to see how ambitious this proposal would be. - Paul - This SF.net email is sponsored by DB2 Express Download DB2 Express C - the FREE version of DB2 express and take control of your XML. No limits. Just data. Click to get it now. http://sourceforge.net/powerbar/db2/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] polar_demo.py broken
The polar demo in examples/polar_demo.py no longer displays the spiral and axes. It worked a couple of weeks ago when I was testing the contains() method. I downloaded a fresh build of matplotlib pulled from svn today. Tested on python 2.5 OS X. Should be on the wxAgg backend, though I don't know how to confirm that. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] infinite lines
Probably a better question for the help list, but has anybody written an artist that can display a semi-infinite or infinite line? axvline and axhline can fake it for vertical and horizontal infinite lines, but they cannot handle slopes or semi-infinite lines. Thanks, - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] mpl1 draft
On Thu, Jul 19, 2007 at 03:31:26PM -0700, Christopher Barker wrote: > > In matplotlib, the plot functions are matplotlib.axes.Axes methods and > > I think there is consensus that this is a poor design. > > Well, the OO interface has always felt a bit clunky to me, but I'm not > sure where else plot functions could go -- I'd love to hear ideas, though. With a few primitives (add_artist, set_property, get_property, x/y axis, labels, grids), all of the plot types can be implemented identically outside of the axes class. Most of them are implemented that way already, and only need to change ax.plot to plot(self=ax). Default to gca() and you have pylab. > > Also, everything should be numpy enabled, > > and the sequence-of-python-tuples approach that many of the > > collections take should be dropped. > > who hoo! > > However, numpy doesn't handle "ragged" arrays well. I wonder if there's > a good way to implement those, so that transforms can be done > numpy-efficient. Can you do it with simple vectors, and an index vector indicating where the different objects start? The transformations can run simply through the sets of indices without bothering about object boundaries. The path objects can use vector slices, which IIRC, are simply views into the vectors and don't require copying the data. It would be easy enough to hide this in a class so that it acts like a sequence of lines to the caller. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] mpl1 draft
On Thu, Jul 19, 2007 at 12:18:21PM -0500, John Hunter wrote: > = Z-ordering, containers, etc = > > Peter has been doing a lot of nice work on z-order and layers for > chaco, stuff that looks really useful for picking, interaction, etc... > We should look at this approach, and think carefully about how this > should be handled. Paul may be a good candidate for this, since he > has been working recently on the picking API. I'm certainly interested in any advice on the best way to implement canvas objects. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Polygon examples broken
On Fri, Jul 20, 2007 at 08:53:30AM -0400, Rob Hetland wrote: > Second, much of what I do involves plotting model data (on a > curvilinear grid). I generally like to use pcolor for these plots. > I *always* want shading='flat' Some of my grids are large, and I > only see lines if I don't. Even with smaller grids, those black > lines get in the way. I don't want to suggest an RC setting for > everything, but this one single setting would save me thousands of > characters typed per week. Can we add an RC shading option? If your data is on a quadrilateral mesh, try using the pcolormesh function. It is orders of magnitude faster than pcolor and we solved the black lines problem by using transparency on the mesh grid (though of course you can use 'flat' if you want). We only implemented this for the Agg backend, otherwise it falls back to the pcolor style rendering of a collection of polygons. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] remove artists
Hi, Not hearing back one way or the other, I checked in the remove artist stuff. It is a pretty minor patch. It is cheap (a lambda and an attribute per artist), but unfortunately not free for those who don' need it :-( I can turn the lambdas into methods pretty easily if the python experts say the savings will be significant. I'll submit an example this weekend which uses it. I've got a pretty extensive application now which uses it, but I need something smaller for that purpose. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Polygon examples broken
On Fri, Jul 20, 2007 at 06:57:26AM -1000, Eric Firing wrote: > Paul Kienzle wrote: > > On Fri, Jul 20, 2007 at 08:53:30AM -0400, Rob Hetland wrote: > >> Second, much of what I do involves plotting model data (on a > >> curvilinear grid). I generally like to use pcolor for these plots. > >> I *always* want shading='flat' Some of my grids are large, and I > >> only see lines if I don't. Even with smaller grids, those black > >> lines get in the way. I don't want to suggest an RC setting for > >> everything, but this one single setting would save me thousands of > >> characters typed per week. Can we add an RC shading option? > > > > If your data is on a quadrilateral mesh, try using the pcolormesh > > function. It is orders of magnitude faster than pcolor and we > > solved the black lines problem by using transparency on the mesh > > grid (though of course you can use 'flat' if you want). We only > > implemented this for the Agg backend, otherwise it falls back to > > the pcolor style rendering of a collection of polygons. > > Paul, > > Quadmesh has a bug in it that I would love to see squashed. Can you > look at it, or induce someone else to do so? I tried but couldn't > figure it out--it is something deep in the use of Agg. It is illustrated > by examples/quadmesh_demo.py. With masked data (right-hand subplot), > the masked region is not set to the background but is instead picking up > odd things. If you don't see it immediately, try reshaping and resizing > the plot a few times. We should be able to track it down. We need to go deep in the code again anyway to figure out why performance bogs when zooming. We won't be touching it before the end of summer though. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Polygon examples broken
On Fri, Jul 20, 2007 at 11:02:45AM -0700, Christopher Barker wrote: > Rob Hetland wrote: > > First, it has bothered me that from pylab import * and from numpy > > import * both import 'load' statements. Yes, I realize that I can put > > them in their own name space, but I only use python for mpl and numpy > > > That's why: "Namespaces are one honking great idea". They really are. > Trust me on this. > > Also, doesn't pylab hold all of numerix anyway? Why do you need both? > > If you want to use the latest numpy API (which I do) then again -- > "Namespaces are one honking great idea". This is what they are for. > > Otherwise, you're stuck with using numerix and waiting until MPL goes > pure numpy ( I don't know when that might be). pylab and numpy stomp all > over each other (if you use import *) by design. > > It comes down to this: if you use "import *" you're forced to use the > decision made by others -- the numerix API, which, quite reasonably, > they are keeping backward compatible. > > Is it really that hard to use this? > > import numpy as N # or "as npy", the mpl standard. > > a = N.arange(10) > > a.sum() > > etc, etc... > > One of the nice things about numpy is that there are lot more array > methods, rather than functions, so it works better with namespaces -- > you really don't need to type the "N." all that much. > > from pylab import * > import numpy as N > > May be a reasonable compromise. > > > -- for me python is a matlab replacement. > > In many ways it is for me too, but it's so much better! take advantage > of the advantages -- like namespaces. > > If you're anything like me, you may not be writing big programs, but > even quickie scripts are edited and re-edited a lot -- a little extra > typing makes little difference. > > -Chris To throw out some nonsense: import numpy as npy res = npy.sqrt(2*npy.sin(npy.pi*x**2) + npy.cos(x**2) - npy.exp(2*npy.pi*1j)) is not very readable. This is improved somewhat as: import numpy as N res = N.sqrt(2*N.sin(N.pi*x**2) + N.cos(x**2) - N.exp(2*N.pi*1j)) but the following is better: from mpl.math import * res = sqrt(2*sin(pi*x**2) + cos(x**2) - exp(2*pi*1j)) Can we create a math.py which makes a standard set of math functions available? Posix libc is an excellent place to start, though I would also appreciate inf, nan, pi and eps as well. I'm guessing a function sqrt(-1.) which returns 1j is out of the question? - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Polygon examples broken
On Fri, Jul 20, 2007 at 09:03:21AM -1000, Eric Firing wrote: > Good, thank you. This brings up the larger question of the major > redesign that is underway, and how to make sure we don't lose the > benefit of wonderful speedups like quadmesh. How hard would it be to > translate it to use the swig-wrapped version of agg rather than > accessing agg directly via the present pycxx _backend_agg.cpp? And how > much performance do you think would be lost? Alternatively, is there a > better way to put the fast rendering capability in a smaller piece of > extension code that can be used in the new framework and that would not > rely on pycxx? E.g., a small swiggable chunk? It is a long time since I've looked at the code, and I wasn't even the original author. Furthermore I don't know swig, nor am I particularly familiar with pycxx, so I can't answer your question. I imagine given an agg context, however that is usually done, that a walk of some arrays is all we need to do. Simplifying the representations on the python side will help a lot IIRC. The interface to my OpenGL plotter (not pylab enabled, sorry!) wasn't complex. Anyway, I'll be gone next week until mid-August, so don't expect anything before the end of summer. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Polygon examples broken
On Fri, Jul 20, 2007 at 12:34:44PM -0700, Christopher Barker wrote: > You're right that for math expressions, it is nice to have them in the > namespace, so this is used a lot: > > from numpy import sqrt, sin, cos, exp > > Maybe it's a reasonable idea to write a Nmath.py, which would have an > import line like that. > > Out of 491 names in the numpy namespace, I found 26 that would commonly > be found in math expressions. Not bad, really, much better than > including all 491. > > Inf NaN abs angle arccos arccosh arcsin arcsinh arctan > arctan2 arctanh cos cosh exp log log10 pi sign sin > sinc sinh sqrt square tan tanh The C99 math/complex headers define a number of symbols. constants: log: M_E M_LOG2E M_LOG10E M_LN2 M_LN10 pi: M_PI M_PI_2 M_PI_4 M_1_PI M_2_PI M_2_SQRTPI sqrt(2): M_SQRT2 M_SQRT1_2 functions: isfinite isnormal isnan isinf acos asin atan atan2 cos sin tan acosh asinh atanh cosh sinh tanh exp log log10 expm1 log1p exp2 log2 pow sqrt cbrt erf erfc lgamma tgamma hypot fmod remainder remquo fabs fdim fmax fmin copysign signbit frexp ldexp logb modf scalbn ceil floor rint nexttoward nearbyingt round trunc complex functions: acos asin atan atan2 cos sin tan acosh asinh atanh cosh sinh tanh exp log pow sqrt conj cproj abs arg imag real The glibc header files are not the most concise source so likely I've made mistakes (e.g., missing inf/nan defs) and included things that are not actually standard (e.g., hypot?). Making a lot of these available in mpl.math would be nice. Short of installing all of scipy, anyone know where I can pick up erf()? > > I'm guessing a function sqrt(-1.) which returns 1j is out of the question? > > what's wrong with "1j" as a literal? Let me rephrase: Can we have a function sqrt(x) which returns real if x is nonnegative, and complex if it is negative? Similarly for other math functions such as log which produce complex values for negative numbers? I suppose the numpy list is the place to debate this, but it seems like it ought to be a feature of pylab in as much as pylab helps matlab users do pythonic things in a familiar environment. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Polygon examples broken
On Fri, Jul 20, 2007 at 02:53:42PM -0700, Christopher Barker wrote: > Paul Kienzle wrote: > > On Fri, Jul 20, 2007 at 12:34:44PM -0700, Christopher Barker wrote: > >> Out of 491 names in the numpy namespace, I found 26 that would commonly > >> be found in math expressions. > > > The C99 math/complex headers define a number of symbols. > > Sure, but you don't need all of those. My idea was thus: > > "Namespaces are one honking great idea" > > but they are kind of ugly inside math expressions. But: > > "Practicality beats purity" > > so I think it does make sense to bring the common names that show up in > math expressions into the main namespace. Not all the handy little names > ( like isnan, zeros, linspace, etc.) only the ones that show up in the > depths of nested math expressions, so that we can write code that looks > like math. That's how I came up with my personal list of 26. > > This is probably best just done by each individual according to his/her > taste. That's what I'm trying to get away from. I want to be able to write the contains() function in patch.py and just use the normal math where it makes sense to use normal math. I suppose one approach is to go through all of mpl, find what is being imported with what frequency, and build the list based on that. Maybe I will get a chance this weekend. Right now I have to go back to the "matplotlib svn doesn't build on windows" problem. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] mpl.math namespace [was: Polygon examples broken]
On Fri, Jul 20, 2007 at 05:05:40PM -0700, Christopher Barker wrote: > >> so I think it does make sense to bring the common names that show up in > >> math expressions into the main namespace. > > >> This is probably best just done by each individual according to his/her > >> taste. > > > > That's what I'm trying to get away from. I want to be able to write > > the contains() function in patch.py and just use the normal math where > > it makes sense to use normal math. > > Ahh -- we're back on an a mpl-devel topic now. > > I was thinking that you were proposing a "math" namespace for pylab > users -- but it sounds like you're proposing a standard set of math > names that will be brought in to modules for the matplotlib project > itself. Different issue. Through the use of "from mpl.math import *" yes. > I don't write enough MPL internal code to have any opinion on that. I'll let the code speak for itself: ~/src/matplotlib/lib/matplotlib pkienzle$ for sym in $symlist; do > echo `grep "[^A-Za-z0-9_]$sym[^A-Za-z0-9_]" *.py | wc -l` $sym; > done | sort -n -r | column -c 75 163 max 7 remainder 1 cosh 0 isnormal 136 arg 7 pow 1 arctanh 0 isinf 109 min 7 inf 1 arcsinh 0 isfinite 102 log 6 arctan2 1 arccosh 0 frexp 64 pi 5 fabs 0 trunc 0 fmin 56 sqrt 4 imag 0 tgamma0 fmax 44 abs 3 tan 0 signbit 0 fdim 38 sin 3 nan 0 scalbn0 expm1 28 cos 3 log2 0 rint 0 exp2 23 minimum 3 hypot 0 remquo0 erfc 22 round2 isnan 0 nexttoward0 erf 19 maximum 2 arctan0 nearbyingt0 cproj 19 floor2 arcsin0 modf 0 copysign 18 log102 arccos0 logb 0 conj 18 ceil 1 tanh 0 log1p 0 cbrt 13 real 1 sinh 0 lgamma0 NaN 12 exp 1 fmod 0 ldexp 0 Inf I used the following list: symlist=`cat
Re: [matplotlib-devel] mpl.math namespace [was: Polygon examples broken]
On Sat, Jul 21, 2007 at 09:42:16AM -0500, John Hunter wrote: > On 7/21/07, Paul Kienzle <[EMAIL PROTECTED]> wrote: > > I used the following list: > > > > symlist=`cat < > pi inf Inf nan NaN > > isfinite isnormal isnan isinf > > arccos arcsin arctan arctan2 cos sin tan > > arccosh arcsinh arctanh cosh sinh tanh > > exp log log10 expm1 log1p exp2 log2 > > pow sqrt cbrt erf erfc lgamma tgamma hypot > > fmod remainder remquo > > fabs fdim fmax fmin > > copysign signbit frexp ldexp logb modf scalbn > > ceil floor rint nexttoward nearbyingt round trunc > > conj cproj abs arg imag real > > min max minimum maximum > > EOF` > > > > This measure doesn't distinguish between comments and > > code, but it should still be good enough for the purposes > > As far as namespaecs are concerned, I agree they are a good idea and > should be used in almost all places. I also don't want the perfect to > be the enemy of the good, or succumb to a foolish consistency, so I > think is is OK to have some very common names that have a clear > meaning to be used w/o a namespace. I have been following your > discussion at a bit of a distance: are you talking about using scalar > functions or array functions here, eg math.sqrt vs numpy.sqrt? Also, Since numpy.* handles scalars but math.* doesn't handle vectors, I suggest importing from numpy. > a few of your symbols clash with python builtins (min, max, abs) which > is best avoided. Feel free to tune the list appropriately. Particularly since max/min/abs already do the right things with vectors: >>> import numpy >>> a = numpy.array([1,2,3,4]) >>> b = numpy.array([4,3,-2,-1]) >>> abs(b) array([4, 3, 2, 1]) >>> isinstance(abs(b),numpy.ndarray) True >>> min(a) 1 >>> min(b) -2 Well, mostly 8-) >>> min(a,b) Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() > Finally, how would you feel about allowing these > symbols in the module namespace, but w/o the import * semantics, eg, > for these symbols we do > > from mpl.math import exp, sin, pi, sin, cos, ... > > it does defeat the purpose of your idea a bit, which is to have a set > of commonly agreed on math symbols that everyone agrees on and we can > always rely on with easy convenience. On the other hand, I am more > comfortable being explicit here. That's acceptable. If the list of common items were shorter it would be easier. Now whenever I use an expression I have to search the file for the math import statement and check whether the particular symbol I need has already been added to the list. For my own projects I started making a standard import line I could cut and paste into every file, but it came to more than 80 characters. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] sample canvas object code
Hi,
I'm attaching the canvas object code I've been playing with.
The API is still incomplete, but in the spirit of release early,
release often, I'll put it out there for people to comment on.
This should use a common callback mechanism with mpl (e.g., the
user should bind to a axis limit change event in much the same
way that they bind to mouse events on an artist), but for the
purposes of putting together a demo I created a small one of
my own. Maybe someone with Traits knowledge can show me how
much better it could be?
- Paul
"""
Extension to MPL to support the binding of artists to key/mouse events.
"""
class Selection:
"""
Store and compare selections.
"""
# TODO: We need some way to check in prop matches, preferably
# TODO: without imposing structure on prop.
artist=None
prop={}
def __init__(self,artist=None,prop={}):
self.artist,self.prop = artist,self.prop
def __eq__(self,other):
return self.artist is other.artist
def __ne__(self,other):
return self.artist is not other.artist
def __nonzero__(self):
return self.artist is not None
class BindArtist:
# Track keyboard modifiers for events.
# TODO: Move keyboard modifier support into the backend. We cannot
# TODO: properly support it from outside the windowing system since there
# TODO: is no way to recognized whether shift is held down when the mouse
# TODO: first clicks on the the application window.
control,shift,alt,meta=False,False,False,False
# Track doubleclick
dclick_threshhold = 0.25
_last_button, _last_time = None, 0
# Mouse/keyboard events we can bind to
events= ['enter','leave','motion','click','dclick','drag','release',
'scroll','key','keyup']
# TODO: Need our own event structure
def __init__(self,figure):
canvas = figure.canvas
# Link to keyboard/mouse
self._connections = [
canvas.mpl_connect('motion_notify_event',self._onMotion),
canvas.mpl_connect('button_press_event',self._onClick),
canvas.mpl_connect('button_release_event',self._onRelease),
canvas.mpl_connect('key_press_event',self._onKey),
canvas.mpl_connect('key_release_event',self._onKeyRelease),
canvas.mpl_connect('scroll_event',self._onScroll)
]
# Turn off picker if it hasn't already been done
try:
canvas.mpl_disconnect(canvas.button_pick_id)
canvas.mpl_disconnect(canvas.scroll_pick_id)
except:
pass
self.canvas = canvas
self.figure = figure
self.clearall()
def clear(self, *artists):
"""
self.clear(h1,h2,...)
Remove connections for artists h1, h2, ...
Use clearall() to reset all connections.
"""
for h in artists:
for a in self.events:
if h in self._actions[a]: del self._actions[a][h]
if h in self._artists: self._artists.remove(h)
if self._current.artist in artists: self._current = Selection()
if self._hasclick.artist in artists: self._hasclick = Selection()
if self._haskey.artist in artists: self._haskey = Selection()
def clearall(self):
"""
Clear connections to all artists.
Use clear(h1,h2,...) to reset specific artists.
"""
# Don't monitor any actions
self._actions = {}
for action in self.events:
self._actions[action] = {}
# Need activity state
self._artists = []
self._current = Selection()
self._hasclick = Selection()
self._haskey = Selection()
def disconnect(self):
"""
In case we need to disconnect from the canvas...
"""
for cid in self._connections: canvas.mpl_disconnect(cid)
self._connections = []
def __del__(self):
self.disconnect()
def __call__(self,trigger,artist,action):
"""Register a callback for an artist to a particular trigger event.
usage:
self.connect(eventname,artist,action)
where:
eventname is a string
artist is the particular graph object to respond to the event
action(event,**kw) is called when the event is triggered
The action callback is associated with particular artists.
Different artists will have different kwargs. See documentation
on the contains() method for each artist. One common properties
are ind for the index of the item under the cursor, which is
returned by Line2D and by collections.
The following events are supported:
enter: mouse cursor moves into the artist or to a new index
leave: mouse cursor leaves the artist
click: mouse button pressed on the artist
drag:
Re: [matplotlib-devel] mpl.math namespace [was: Polygon examples broken]
On Sat, Jul 21, 2007 at 08:51:19AM -1000, Eric Firing wrote: > John Hunter wrote: > [...] > > functions or array functions here, eg math.sqrt vs numpy.sqrt? Also, > > a few of your symbols clash with python builtins (min, max, abs) which > > is best avoided. Finally, how would you feel about allowing these > > symbols in the module namespace, but w/o the import * semantics, eg, > > for these symbols we do > > > > from mpl.math import exp, sin, pi, sin, cos, ... > > There is no point in this; better to import these directly from numpy, > if that is what is wanted. oops... missed that detail. Yes of course in we are explicitly importing a name be explicit about where it is coming from. > But sometimes we actually want a masked > array version. > > For many of these things there are up to 5 different possible sources: > > (builtin, if not math or cmath) > math > cmath > numpy > numpy.ma > maskedarray > > Sometimes functions from the different sources do the same thing, but > usually at different speeds, and sometimes they don't do the same thing > at all. In most cases we want, or at least can manage with, either the > numpy version or one of the masked versions, presently accessed via > numpy.numerix.npyma, which is imported via > > import numpy.numerix.npyma as ma > > The recently introduced policy of simply being very explicit *does* > work; when looking at an expression one always knows which functions > are being invoked. Like Paul, I recoil a bit at the clunky appearance, > but apparently unlike Paul, I find the explicitness helpful--especially > since I am very conscious of the need to use masked versions in some places. I'm surprised by the poor performance of numpy scalars reported elsewhere. Given that one is forced to be explicit about the source of the function and given that there is no good solution, I guess using numpy.sin, etc. is best. Here's some timings of various possibilities on my machine: 0.20 import from math outside the function call 0.22 use math.sin and math.pi inside the function call 0.53 import from math inside the function call 0.67 import from numpy outside the function call 0.70 use numpy.sin and numpy.pi inside the function call 1.14 import from numpy inside the function call - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] sample canvas object code
On Sat, Jul 21, 2007 at 02:39:52PM -0500, John Hunter wrote:
> On 7/21/07, Paul Kienzle <[EMAIL PROTECTED]> wrote:
> > Hi,
> >
> > I'm attaching the canvas object code I've been playing with.
> >
> > The API is still incomplete, but in the spirit of release early,
> > release often, I'll put it out there for people to comment on.
>
> Hey Paul this is really cool stuff. There is a minor bug -- the onAdd
> callback in bindertest.py on line 26 should be onAddend I think.
onAppend. That's a brown paper bagger :-(
> Also, I wanted to know if you've looked that the copy_region/blit
> stuff we have.
I'm aware of the blit stuff but haven't looked in detail. So far I
don't need it because my graphs are simple. Later when I define
widgets operating on meshes I will look more closely.
> BTW, poly_editor was broken but I just fixed it so you can check it
> out of svn if you want to take a look.
Yup, it works now! Even when it was broken it was still a good source
of examples.
> Right now I don't have any answers or comments to the questions you
> raise in the code, eg on keyboard vs mouse focus handling -- you are
> much deeper in this stuff than I am -- so I'll it's probably best if
> you just keep thinking through these things as you go.
I'll be away for a weeks but will continue when I return. Working
with it when I return.
I already know that I need to use keyboard focus handling. My real
application can move objects around on the screen with the keyboard
for finer control, and this will only work if the keyboard focus stays
with the object even as it moves from the mouse.
> As for your traits question, you are absolutely right about the need
> for a common callback framework. I have been cleaning up the
> transformations in mpl1 and the callbacks and properties on the
> affines are tremendously useful (eg xlim is just a property based view
> into the affine, and one can connect to events on affine changes). I
> don't have a GUI backend layer yet in which one can begin playing
> around with interaction, but I am close, with a few more changes, to
> having a serviceable first cut at the transformations, artist
> hierarchy, and renderer layer.
I'm looking forward to seeing it.
> FYI, every artist does have a callback mechanism built in which you
> can easily extend to support additional events (right now I have been
> adding them on as as needed basis -- what traits does so nicely is
> that they are there for every traited instance).
>
> Eg to connect to the Axes xlim:
>
> ax.callbacks.connect('xlim_changed', func)
>
> and func will be called with the signature func(ax). Eg see
> examples/shared_axis_across_figures.py which utilizes the callbacks to
> couple xlim across figure instances.
How much control is there over the which callbacks are called, what order
they are called in, and when effects show up on the screen?
My first implementation sends the event to the artist, and if the artist
returns false it goes to the axes, then the figure. This is much weaker
than the Tk/BLT canvas model, which allows the programmer to control the
order, and also has class-based dispatch.
Also, I'm nervous about this from a performance perspective --- I don't want
others to have a slower graphics engine just because I need callbacks
for what I'm doing.
Has anyone done profiling to see where the current bottlenecks are?
I know we will be looking into this; the user experience was so
awkward with four plotting panels in an wx.aui frame that we went
back to a straight wx.lib.plot backend.
- Paul
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] mathtext baseline
Hi,
I really love mathtext! I wrote a simple formula parser
and now I can label my graphs with easy to read chemical
names (I've attached it below for the curious).
The problem is that the baseline is wandering. On my machine
the following has the 'h' too low and the 'io' too high:
import pylab
ax = pylab.subplot(111)
pylab.text(0.5,0.5,r'$\rm{Thiol}$', va='bottom')
pylab.show()
I'm using wxAgg on OS X. I know I've installed freetype, but
beyond that I have no idea what font it is using.
Do others experience the same problem?
Any idea where I can start when debugging this?
- Paul
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Mathtext improvements (merging into trunk)
On Thu, Aug 02, 2007 at 10:31:04AM -0400, Michael Droettboom wrote:
> I don't know if we ever reached consensus on how to specify math text
> vs. regular text. I agree with Eric that it's down to two options:
> using a new kw argument (probably format="math" to be most future-proof)
> or Math('string'). I don't think I have enough "historical perspective"
> to really make the call but I do have a concern about the second option
> that it may be confusing depending on how "Math" is imported. (It may
> have to be pylab.Math in some instances but not in others.) But I don't
> have a strong objection.
>
> Any last objections to going with the new keyword argument?
I'm guessing that this discussion is already closed, but I would still
like to propose another option, just like the original: specify the
format in the string itself by requiring a leading '$'.
For example:
text(x, y, r'$\sin(x)$')
or for those functions not starting with math:
text(x, y, r'$$phase $[0,2\pi)$')
This is a variant on Math(r'$\sin(x)$') which is a bit more compact.
As has been pointed out elsewhere, whether or not the string contains
tex markup is a property of the string, not a property of the function
that use the string. Note that the format keyword will be required for
all functions which have string inputs, and may cause problems if there
are multiple string inputs to the function. legend() in particular may
be a problem.
- Paul
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Cannot set nonpositive limits with log transform
On Wed, Aug 15, 2007 at 09:57:21AM -0400, Darren Dale wrote:
> On Tuesday 14 August 2007 07:35:43 pm Darren Dale wrote:
> > I'm developing an application for work and need to plot some spectra on a
> > logscale. I can recreate my problem with embedding_in_qt4, by replacing
> > MyDynamicMplCanvas.compute_initial_figure with this:
> >
> > def compute_initial_figure(self):
> > self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')
> > self.axes.set_yscale('log')
> >
> > [...]
> > File
> > "/usr/lib64/python2.5/site-packages/matplotlib-0.90.1_r3709-py2.5-linux-x86
> >_64.egg/matplotlib/axes.py", line 1664, in set_ylim
> > raise ValueError('Cannot set nonpositive limits with log transform')
> > ValueError: Cannot set nonpositive limits with log transform
> >
> > I get that error even if I modify the update figure function so there is no
> > possibility of zeros occuring in the data
>
> I have tracked this back through axes.cla(), which is called when axes._hold
> is False, to axis.cla(). axis.cla() resets the locators, but the transforms
> are still set to mtrans.LOG10. Since plot is called by loglog, and semilog*,
> it shouldn't be using any methods that modify locators. If cla() resets the
> transforms, then the behavior of plot will be different, preserving log
> transforms when hold is True, but changing to linear transforms when hold is
> False.
>
> I wonder if cla() is trying to do too much. Maybe the initial setting of
> locators should be moved out of cla(), which is called by Axes.__init__, and
> into Axis.__init__. Then calls to cla() will preserve the scaling, and the
> behavior of plot() will be consistent, regardless of the whether hold is
> enabled or not.
The other option is to do something sensible when axes limits are
negative on the log scale. We switch back and forth between linear and log
while zooming/panning. Since it is difficult to keep the limits positive
when using the linear scale we would love to have the plot handle bad
limits. I don't have a patch yet, but I don't mind if you beat me to it 8-)
Ultimately we would like negative data to be represented using
an inverted logarithmic scale, but this is a more difficult project.
For now we are masking out any data <= 0.
- Paul
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] mathtext rotation
Hi all,
I replaced one of the text_rotation examples with r'$\rm{mathtext_{225}}$'
to see if rotation is supported for mathtext. It is not in the current
trunk downloaded today.
Before I look to deeply into this myself, is there anyone working on it
already? Is there anything I need to look out for when implementing it?
Thanks in advance...
- Paul
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] mathtext in wx widgets
Hi, It would be great to be able to display math markup in other parts of my application, such as labels, tables, lists and menus. Has anyone ever tried doing this for wx or gtk? Thanks in advance, - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] mathtext rotation
On Thu, Aug 30, 2007 at 02:19:47PM -0400, Michael Droettboom wrote:
> Paul Kienzle wrote:
> > Hi all,
> >
> > I replaced one of the text_rotation examples with r'$\rm{mathtext_{225}}$'
> > to see if rotation is supported for mathtext. It is not in the current
> > trunk downloaded today.
>
> It's only not supported in the bitmap (Agg and Gdk) backends. It works
> fine in the vector backends.
Okay. wxAgg works with $90^\circ$ rotations as well. This will work for
me short term (though $45^\circ$ is better).
> > Before I look to deeply into this myself, is there anyone working on it
> > already? Is there anything I need to look out for when implementing it?
>
> I've made a few excursions down that road --
>
> For bitmap font rendering, the entire math expression is first laid out
> in a greyscale bitmap buffer, which is cached and then transferred to
> the main plot bitmap. It was already that way when I got here, and I
> assume that's an important optimization (so the text doesn't have to be
> re-laid-out when the plot is zoomed/panned). I say "perhaps" because I
> have no data to back it up, and don't know if that came out of profiling
> or not.
>
> There are a few key low level pieces that are missing for rotation:
>
> - FT2Font.draw_glyph_to_bitmap does not support rotation. This would
> have to be added, or there may be a way to use
> set_text/draw_glyphs_to_bitmap which does support rotation. However,
> that would make rendering the entire expression to a single buffer much
> more difficult.
Adding rotation to draw_glyph_to_bitmap looks like the easier option...
>
> - The horizontal lines are all drawn as filled rectangles aligned to the
> pixel grid, directly into the font buffers. That will probably have to
> be pushed upward into the Agg layer to get good line drawing at
> arbitrary angles -- but that also makes caching the bitmap a little more
> difficult. So maybe it makes sense to implement our own Breshenham's
> algorithm in ft2font.cpp.
...but if we need to go into agg anyway, why not use Agg's font handling
capabilities directly?
>
> All this will be affected by John's proposed refactoring of the
> backends, of course, which has kind of kept me off of it in a "wait and
> see" kind of mode. Right now, each backend has a custom interface to
> communicate with mathtext -- whereas mathtext should simply be calling
> the same low-level methods on all backends to get its job done. That,
> of course, would make this buffer optimization harder (or at least it
> would have to be thought about differently).
I haven't followed the refactoring proposal close enough to know if it
makes more sense to implement mathtext via freetype in agg or to use
freetype directly like you are currently doing. Once that decision is
clear, we can certainly prototype the handling of rotated text in the Agg
backend.
Presumably this will have to be repeated for Cairo.
>
> Let me know if you decide to implement this and let me know if you have
> any questions about the code. Otherwise I'm happy to add it to my queue.
I can get by for now with limited text rotation, at least until the
backend refactoring has settled.
- Paul
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] mathtext in wx widgets
On Thu, Aug 30, 2007 at 01:56:36PM -0500, John Hunter wrote: > On 8/30/07, Michael Droettboom <[EMAIL PROTECTED]> wrote: > > > (And long term, as cool as matplotlib is, it would be nice to refactor > > this out as a separate library for apps that don't do any plotting...) > > I agree, the mathtext stuff is becoming really good, and will be > really good when we have a good set of fonts to work with. I can see > it being useful in lots of contexts, and more users in other contexts > will make it more useful for us down the road. The challenge is to separate the backends from matplotlib. If mathtext takes over all of the font handling then matplotlib won't need to include freetype. If matplotlib handles bitmap rotation, then mathtext won't need to include agg. Then mathtext need only take the format string and return a bounding box, a bitmap, or the PDF/PS/SVG instructions necessary to render the text. I don't know if PDF/PS/SVG can rotate the coordinate system prior to rendering. If not, then rotation will need to be moved into mathtext as well. - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] mathtext in wx widgets
On Fri, Aug 31, 2007 at 03:28:49PM -0400, Michael Droettboom wrote: > There is now preliminary support for getting a mathtext bitmap to > transfer to a GUI widget in SVN, along with a toy wxPython example in > examples/mathtext_wx.py. I've only tested this on > Linux/wxGTK2/wxPython-2.8. I'd appreciate help with testing (and > screenshots) on any other platforms you may care about. That's wonderful! I'm attaching a screen shot for wx 2.8 on OS/X. The rendering is kind of ugly, but I haven't looked into it. - Paul <>- This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] mathtext in wx widgets
On Fri, Aug 31, 2007 at 03:32:09PM -0400, Michael Droettboom wrote: > And placing bitmaps in menu items reportedly doesn't work at all on > wxCocoa. -- so maybe it's best to stay away from that altogether. The wxPython demo.py for menus has a smiley face bit map that displays just fine. Let me know if you want a screen shot. - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] backend_driver errors
In checking the mathtext rotation feature I found that the graph displayed fine, but python segfault'd shortly after displaying it. Most (all) examples are failing for me for svn r3778, even after rebuilding and reinstalling everything. Is there something in the last couple of weeks which might cause this? Running backend_drivers, the Agg plots are fine. None of the PS plots are viewable with Preview.app. I don't have an svg viewer handy. I'm running macpython 2.5 fat binary build on OS X 10.4 with wx 2.8. Anyone else having problems with it? - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] backend_driver errors
On Wed, Sep 05, 2007 at 01:40:02PM +0300, Jouni K. Seppänen wrote: > Paul Kienzle <[EMAIL PROTECTED]> writes: > > [segfaults] > > Is there something in the last couple of weeks which might cause this? > > Some changes in font handling caused segfaults for me, and it turned out > to be a bug in an old version of freetype: > > http://article.gmane.org/gmane.comp.python.matplotlib.general/10062 > > Try running python under gdb, or using strace/truss/ktrace to see what > is happening right before the segfault. Running gdb first: Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_INVALID_ADDRESS at address: 0x65c4a402 0x65c4a402 in ?? () (gdb) bt #0 0x65c4a402 in ?? () #1 0x0265c5e1 in FT_Glyph_Get_CBox (glyph=0x54463a3a, bbox_mode=1634552114, acbox=0x6567) at /Users/pkienzle/Packages/freetype-2.3.5/src/base/ftglyph.c:534 Previous frame inner to this frame (corrupt stack?) So the problem seems to be in freetype. The link above says: Looks like a freetype bug: the following code segfaults when linked against libfreetype.6.3.10 but not when linked against libfreetype.6.3.16. Freetype has some code to read dfont files, which apparently had a bug in the older version, and this is triggered by the new code that reads in all font files. I don't understand why it is referring to 6.3.16 when 2.3.5 was released in July 2007, unless 6.3.16 means May 16, 2006. - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] backend_driver errors
On Wed, Sep 05, 2007 at 07:13:27AM -0400, Michael Droettboom wrote:
> Jouni K. Seppänen wrote:
> > Paul Kienzle <[EMAIL PROTECTED]> writes:
> >
> > [segfaults]
> >> Is there something in the last couple of weeks which might cause this?
> >
> > Some changes in font handling caused segfaults for me, and it turned out
> > to be a bug in an old version of freetype:
> >
> > http://article.gmane.org/gmane.comp.python.matplotlib.general/10062
> >
> > Try running python under gdb, or using strace/truss/ktrace to see what
> > is happening right before the segfault.
>
> I'm not able to reproduce anything amiss on my Linux box.
I'm able to eliminate the problem by setting image=NULL after deleting it.
I did some mods to the refcount handling so that it consistently uses
XINC/XDEC for images and INC/DEC for glyphs.
I added in INCREF to get_glyph(); you don't seem to call it so it didn't
show up as an error without.
See attached patch. Let me know if I should post it to svn.
- Paul
Index: src/ft2font.cpp
===
--- src/ft2font.cpp (revision 3785)
+++ src/ft2font.cpp (working copy)
@@ -743,8 +743,7 @@
{
_VERBOSE("FT2Font::~FT2Font");
- if(image)
-Py::_XDECREF(image);
+ Py_XDECREF(image);
FT_Done_Face( face );
for (size_t i=0; i-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] examples errors
I went through the demo list again today. Here are some problems:
$ python fonts_demo.py
Traceback (most recent call last):
File "fonts_demo.py", line 31, in
font.set_name('Script MT')
AttributeError: 'FontProperties' object has no attribute 'set_name'
I'm getting segfaults for the following on wxagg for os x:
annotation_demo
polar_*
transoffset
The polar demos work for pdf but not agg from backend_driver.py
- Paul
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] backend_driver.py was: Re: examples errors
On Thu, Sep 06, 2007 at 08:14:19AM -0400, Michael Droettboom wrote: > On a broader note, I've been using backend_driver.py as my ersatz > "acceptance test suite." Not all of these examples are included in it, > of course. Is there good reason for that, or should I go ahead and add > these to backend_driver? As we're all well aware, matplotlib has an > unusually large configuration space, so any bit of testing automation > really helps. We could store a copy of the png output somewhere in the svn tree. Then, whenever we change something we can do a binary comparison on all the plots. It would avoid issues such as breakage of polar plots where the author of the changes didn't consider that it would affect polar plot output. Similarly for ps/pdf. Differences in fonts between platforms might be a problem in this scheme. - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] polar_demo output
polar_demo agg and polar_demo pdf/ps/svg show different results. In agg, the spiral is clipped to the polar axes. In pdf/ps/svg it is clipped to the rectangle containing the axes. Note: I don't use polar plots, so I'm mentioning this for completeness only. - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] svg fonts and mathtext
On Fri, Sep 07, 2007 at 12:09:01PM -0400, Michael Droettboom wrote:
> Paul Kienzle wrote:
> > I was going to check if this also fixed the dot on the 'i' in sin as
> > well as the equals sign,
>
> FWIW, it did for me in Inkscape.
And for me in Safari.
Note: Adobe SVGViewer doesn't see the embedded fonts, but it works if I
have the fonts installed. Oh, well!
> > but I get the following:
> >
> > File
> > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/mathtext.py",
> > line 616, in _get_info
> > raise ValueError('unrecognized symbol "%s"' % sym)
> > ValueError: unrecognized symbol "\sin"
>
> Strange. My recent bugfixes shouldn't have affected that file.
>
> That line number doesn't match up with what I have in svn trunk.
> Perhaps you somehow have reverted to an older version...?
Oops ... my error. I modified PYTHONPATH in bashrc but didn't
refresh my terminals.
- Paul
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] svg fonts and mathtext
On Fri, Sep 07, 2007 at 10:31:13AM -0400, Michael Droettboom wrote: > Paul Kienzle wrote: > > On Fri, Sep 07, 2007 at 06:40:55AM -0400, Michael Droettboom wrote: > >> I'd be curious to see a screenshot of what Safari looks like. It may be a > >> simple fix on our end. > > > > See attached. > > > >> As for file sizes, the SVG spec makes an "informational recommendation" to > >> allow gzip-compressed SVG files. So some tools support commpression > >> (Inkscape), and others don't (Firefox). Hopefully more will start > >> supporting that. > > > > Safari doesn't. IE 7 does. > > By IE7 you mean "IE7 on OS-X with Adobe SVG Plugin?" I've never used > that browser -- it doesn't have built-in SVG support, correct? Actually it is running on Parallels on Windows XP SP2. > > Note that IE 7.0.5730.11 doesn't render mathtext_demo.svg with the Adobe > > 3.03 SVGViewer plugin. Instead it reports bad CSS selector. I looked > > around > > for a bit, but couldn't find an alternative viewer. Other svg files work. > > In general, I'm not too concerned about supporting a long abandoned tool > like the Adobe SVG viewer. Long abandoned it maybe, but I don't see any real alternatives for IE. I suppose one could use a java-based implementation and write a full-featured web app, but a browser plugin is a lot more convenient. - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] svg fonts and mathtext
On Fri, Sep 07, 2007 at 10:58:47AM -0400, Michael Droettboom wrote:
> Paul Kienzle wrote:
> > On Fri, Sep 07, 2007 at 06:40:55AM -0400, Michael Droettboom wrote:
> >> I'd be curious to see a screenshot of what Safari looks like. It may be a
> >> simple fix on our end.
> >
> > See attached.
>
> It turns out this "difference" (I'm not calling it a bug) is visible in
> Inkscape as well.
>
> There seems to be some disagreement about the 'Z' operator on SVG paths
> (which is supposed to close the current path segment). In Firefox, 'Z'
> doesn't move the reference point for subsequent relative operations,
> whereas in Inkscape (and presumably Safari) it does. So the delta
> problem is because the inner triangle was being drawn offset outside of
> the outer triangle. The workaround in matplotlib is to never do a
> relative operation after the 'Z' operator (r3808) and avoid exercising
> this difference.
>
> Unfortunately, the SVG 1.1 and 1.2 specs don't appear to directly
> address this issue (at least it isn't very explicit):
>
> http://www.w3.org/TR/SVG/paths.html
>
> So it's hard to say who's "to blame" here, but perhaps the spec should
> be clarified.
I was going to check if this also fixed the dot on the 'i' in sin as
well as the equals sign, but I get the following:
File
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib/mathtext.py",
line 616, in _get_info
raise ValueError('unrecognized symbol "%s"' % sym)
ValueError: unrecognized symbol "\sin"
- Paul
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] svg fonts and mathtext
On Fri, Sep 07, 2007 at 03:09:10PM -0400, Michael Droettboom wrote: > Paul Kienzle wrote: > > On Fri, Sep 07, 2007 at 12:09:01PM -0400, Michael Droettboom wrote: > >> Paul Kienzle wrote: > > Note: Adobe SVGViewer doesn't see the embedded fonts, but it works if I > > have the fonts installed. Oh, well! > > With the embedded fonts, you mean the text just doesn't show up at all? It looks the same as the version without embedded fonts, which is that it chooses some incorrect default font with the wrong character codes as I showed earlier. I thought unicode was supposed to give unique codes to the characters so that even if the font was wrong, at least you would get the correct glyph from the font. Or does this only happen at a higher level? > Do you know if the SVG output from Cairo works with Adobe? They use a > similar (but not identical) approach to embedding the character outlines. I'm not set up to run Cairo, but I can check if someone sends me an svg. - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] svg fonts and mathtext
On Fri, Sep 07, 2007 at 04:04:28PM -0400, Michael Droettboom wrote: > Paul Kienzle wrote: > > It looks the same as the version without embedded fonts, which is that it > > chooses some incorrect default font with the wrong character codes as I > > showed earlier. > > That's very surprising, since when the characters are embedded, there's > no notion of characters ( elements) in the file at all -- it just > uses references to paths in the file that have non-meaningful names like > c_a2. Too many variations --- yes embedded fonts work fine on Adobe SVGViewer. > >> Do you know if the SVG output from Cairo works with Adobe? They use a > >> similar (but not identical) approach to embedding the character outlines. > > > > I'm not set up to run Cairo, but I can check if someone sends me an svg. > > Attached (gzipped). The mathtext comes through in red on Safari, Adobe and Firefox. Is this intended? - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] Windows pdf generation
Hi,
We are having trouble with PDF generation on Windows (see below).
Python 2.4.3 - Enthought Edition 1.1.0
freetype 2.5.3 (GnuWin32 package)
Anyone experienced similar problems?
Meanwhile I'm modifying ttconv to include the font name in the error message.
- Paul
Traceback (most recent call last):
File "_tmp_alignment_test.py", line 87, in ?
savefig("alignment_test_pdf", dpi=150)
File "c:\python24\Lib\site-packages\matplotlib\pyplot.py", line 274, in
savefig
return fig.savefig(*args, **kwargs)
File "c:\python24\Lib\site-packages\matplotlib\figure.py", line 770, in
savefig
self.canvas.print_figure(*args, **kwargs)
File "c:\python24\Lib\site-packages\matplotlib\backend_bases.py", line 1195,
in print_figure
orientation=orientation,
File "c:\python24\Lib\site-packages\matplotlib\backends\backend_pdf.py", line
1943, in print_pdf
file.close()
File "c:\python24\Lib\site-packages\matplotlib\backends\backend_pdf.py", line
406, in close
self.writeFonts()
File "c:\python24\Lib\site-packages\matplotlib\backends\backend_pdf.py", line
475, in writeFonts
fontdictObject = self.embedTTF(realpath, chars[1])
File "c:\python24\Lib\site-packages\matplotlib\backends\backend_pdf.py", line
918, in embedTTF
return embedTTFType3(font, characters, descriptor)
File "c:\python24\Lib\site-packages\matplotlib\backends\backend_pdf.py", line
732, in embedTTFType3
rawcharprocs = ttconv.get_pdf_charprocs(filename, glyph_ids)
RuntimeError: TrueType font may be corrupt (reason 2)
-
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2005.
http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] pdf output
A further comment on the windows PDF problems. PDF output generated by matplotlib on Windows and on OS X is readable in Preview.app on OS X but is not readable in Acrobat 8.1.0 or 7.0.5 on Windows. Adobe 7.0.5 produces the message "There were too many arguments". At this point I have no idea how to proceed, but I will at least post the correct to ttconv. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] pdf font problem
I've resolved part of the PDF font problem on windows --- ttconv was not opening the font file with "rb". I'll send a patch later as soon as I figure out why acrobat is saying "too many arguments" when opening the resulting pdf file. Preview.app on OS X opens the files without difficulty. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] pdf output
I'm not sure yet how to fix the problem, but in the sample I sent
earlier if I change:
5 0 obj
<< /Length 11 0 R >>
endobj
to
5 0 obj
<< /Length 1239 >>
endobj
then both gv and acroread can process the file without error.
- Paul
On Tue, Sep 11, 2007 at 08:49:05AM -0400, Michael Droettboom wrote:
> This seems to be a cross platform bug and unrelated to fonts -- at least
> I am able to reproduce it on Linux.
>
> There was a small typo in the recently added support for non-rectangular
> clip paths. Fixed in r3829.
>
> (Jouni -- you may want to review this and verify that my change is correct.)
>
> Cheers,
> Mike
>
> Paul Kienzle wrote:
> > On Mon, Sep 10, 2007 at 04:19:24PM -0400, Michael Droettboom wrote:
> >> Can you set "pdf.compression : 0" and send me a copy of the troublesome
> >> PDF (probably best off list if it's a large file.)?
> >
> > I used the following:
> >
> > import pylab
> > pylab.rc('pdf',compression=0)
> > plyab.plot([1,2,3],[1,2,3])
> > pylab.savefig('simple.pdf')
> >
> > See attached.
> >
> >> Do you know what set of fonts are getting embedded? If their not in the
> >> mpl set, it's possible they haven't been tested.
> >
> > Should be the standard set, but I haven't verified.
> >
> > - Paul
>
> --
> Michael Droettboom
> Operations and Engineering Division
> Space Telescope Science Institute
> Operated by AURA for NASA
-
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2005.
http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] pdf output
On Tue, Sep 11, 2007 at 10:57:18AM -0400, Paul Kienzle wrote: > I'm not sure yet how to fix the problem, but in the sample I sent > earlier if I change: > > 5 0 obj > << /Length 11 0 R >> > endobj > > to > > 5 0 obj > << /Length 1239 >> > endobj > > then both gv and acroread can process the file without error. > > - Paul If I change every instance beginStream in backend_pdf.py to use None rather than a reserved object for the length of the stream then acroread/gv can process the resulting pdf files. I'm guessing this will be less efficient for the writer since it has to keep the entire stream in memory in order to compute its length prior to writing it. The alternative would be to reserve space, write the stream, rewind to write the length then seek forward to the end, but that won't work if e.g., the pdf is sent to a pipe. Let me know if I should post the changes. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] pdf output
On Tue, Sep 11, 2007 at 12:31:25PM -0400, Michael Droettboom wrote: > Did r3829 not work for you? (Or did you miss that in my earlier post?) > > I don't think anything related to Lengths has changed recently, and it > did work at one point... The current svn works --- I must have missed a build step when testing. Thanks, - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Reconfiguring transforms
On Wed, Sep 12, 2007 at 01:11:54PM -0500, John Hunter wrote: > On 9/12/07, Michael Droettboom <[EMAIL PROTECTED]> wrote: > > > So, I feel like I'm going in a bit of a circle here, and I might need a > > reality check. I thought I'd better check in and see where you guys > > (who've thought about this a lot longer than I have) see this going. A > > statement of objectives of this part of the task would be helpful. > > (e.g. what's the biggest problem with how transforms work now, and what > > model would be a better fit). John, I know you've mentioned some to me > > before, e.g. the LazyValue concept is quirky and relies on C and the PDF > > stateful transforms model is close, but not quite what we need, etc. I > > feel I have a better sense of the overall code structure now, but you > > guys may have a better "gut" sense of what will fit best. > > Here is a brief summary of what I see some of the problems to be with > the existing approach to transformations, and what I would like to see > improved in a refactoring. The three major objectives are clarity, > extensibility and efficiency. > > Clarity: > > The existing transformation framework, written in C++ and > making extensive use of deferred evaluation of binary operation > trees and values by reference, is difficult for most developers to > understand (and hence enhance). Additionally, since all the heavy > lifting is done in C++, python developers who are not versed in C++ > have an additional barrier to making contributions. Indeed! > Extensibilty: > > We would like to make it fairly easy for users to add additional > non-linear transformations. The current framework requires adding a > new function at the C++ layer, and hacking into axes.py to support > additional functions. We would like the existing nonlinear > transformations (log and polar) to be part of a general > infrastructure where users could supply their own nonlinear > functions which map (possibly nonseparable) (xhat, yhat) -> > separable (x, y). There are two parts to this: one pretty easy and > one pretty hard. > > The easy part is supporting a transformation which has a separation > callable that takes, eg an Nx2 array and returns and Nx2 array. For > log, this will simply be log(XY), for polar, it will be > r*cos(X[:,0]), r*sin(X[:,1]). Presumably we will want to take > advantage of masked arrays to support invalid transformations, eg > log of nonpositive data. > > The harder part is to support axis, tick and label layout > generically. Currently we do this by special casing log and polar, > either with special tick locators and formatters (log) or special > derived Axes (polar). Another hard part is grids. More generally, a straight line in x,y becomes curved in x',y'. Ideally, a sequence of points plotted on a straight line should lie directly on the transformed line. This would make the caps on the polar_bar demo follow the arcs of the grid. The extreme case is map projections, where for some projections, a straight line will not even be connected. Another issue is zooming and panning. For amusement, try it with polar_demo. > Efficiency: > > There are three parts to the efficiency question: the efficiency of > the transformation itself, the efficiency with which transformation > data structures are updated in the presence of viewlim changes > (panning and zooming, window resizing) and the efficiency in getting > transformed data to the backends. My guess is that the new design > may be slower or not dramatically faster for the first two (which > are not the bottleneck in most cases anyhow) but you might get > sigificant savings on the 3rd. Changing the internal representation of things like collections so that the transform can be done using numpy vectors will help a lot. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] py2exe wisdom
As I was building a py2exe distribution of matplotlib, I noticed the function get_py2exe_datafiles() in __init__.py that is not noted on the FAQ. Before I update the FAQ, can you all tell me your best practices recommendations for wrapping matplotlib? In particular, is there a way I can store the matplotlib data directly in the exe so that install is simply a matter of copying an exe file rather than a whole directory? Technically this should be feasible --- freetype can load fonts from memory or directly from the zip file given the proper driver, and the various images should be similarly readable. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] py2exe wisdom
On Tue, Oct 02, 2007 at 10:42:13AM -0400, Paul Kienzle wrote:
> As I was building a py2exe distribution of matplotlib, I noticed the
> function get_py2exe_datafiles() in __init__.py that is not noted on
> the FAQ. Before I update the FAQ, can you all tell me your best
> practices recommendations for wrapping matplotlib?
>
> In particular, is there a way I can store the matplotlib data directly
> in the exe so that install is simply a matter of copying an exe file
> rather than a whole directory?
>
> Technically this should be feasible --- freetype can load fonts
> from memory or directly from the zip file given the proper driver,
> and the various images should be similarly readable.
For the record, here is what I'm using to wrap matplotlib in py2exe.
Since I'm using the wx backend I've excluded Tkinter.
Since numerix uses __import__, py2exe wasn't clever enough to find the
numerix extensions, and had to be listed explicitly. Similarly
for backends.
I'm not picking up the 14Mb of timezone info that I don't need. Maybe
want packages = ['pytz'] if your applications need it.
I haven't addressed mpl-data yet.
- Paul
myapp.py
import pylab
pylab.plot(range(10),range(10))
pylab.show()
setup.py
from distutils.core import setup
import sys, os, py2exe
# data_files: List of datafiles that need to be explicitly included
# e.g., [('target/relative/path', ['file','list'])]
# excludes: List of modules to exclude (takes precedence over includes)
# dll_excludes: List of dlls to exclude
# includes: List of modules to include
# packages: List of packages to include
data_files = []
excludes = [ 'numarray', 'Numeric', 'Tkinter', ]
dll_excludes = [] # dlls to exclude
includes = [ 'matplotlib', 'wx', 'numpy', ]
packages = [] # May want 'wx' in packages if creating a generic environment
# Explicit package rules
if 'matplotlib' in includes:
import matplotlib
data_files += matplotlib.get_py2exe_datafiles()
includes += ['matplotlib.numerix.'+pkg for pkg in
['ma','mlab','fft','linear_algebra','npyma','random_array']]
includes += ['matplotlib.backends.backend_'+pkg for pkg in
['wx','wxagg','pdf','ps','svg','agg','agg2','emf']]
# Don't include anything explicitly excluded
includes = [x for x in includes if x not in excludes]
# Include the C/C++ runtime (there should be a way of putting these beside
# the python dll in the executable, but for now I put them in the executable
# directory. Note: the C++ runtime might be in the wx package instead of the
# python directory.
pythonpath = os.path.dirname(sys.executable)
c_runtime = pythonpath+"/MSVCR71.DLL"
cpp_runtime = pythonpath+"/MSVCP71.DLL"
data_files += [('.',[c_runtime,cpp_runtime])]
# End of configuration
py2exe_opts = dict(includes=includes, excludes=excludes,
skip_archive=0, compressed=1,
dll_excludes=dll_excludes, packages=packages,
bundle_files=1, optimize=2)
setup(
options = dict(py2exe=py2exe_opts),
windows= ['myapp.py'], # Could be console=, depending on your app
data_files = data_files,
#zipfile = None, # Bundle library.zip with the executable
)
-
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems? Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Inches?
On Sat, Nov 03, 2007 at 05:43:55PM +0100, Olivier Verdier wrote: > This is much worse than I thought. The "inch" unit is used in many places in > matplotlib. In particular in `figure` and `savefig`. Please, please consider > allowing other units. Let me emphasise this once more: in Europe, and, I > believe in most places around the world, one NEVER uses inches. Neither in > engineering nor, i think, in typography. For most people "inch" is basically > an unusual measure of how big screens are. I'm not kidding. Same for dpi, > it's a specific measurement of a resolution but nobody thinks of it as a > number of pixels per inches. > I have nothing against an internal use of inches inside matplotlib but > please consider allowing other units for all kinds of interfaces with the > user! > > The best choice in my opinion would be to have a unit preference in the > .matplotlibrc file. This unit could be, say, `inch` or `cm` (or mm). Then > any length would be expressed using this unit of length. That seems simple > enough, doesn't it? You have to be careful about the use of global flags which change the behaviour of a library --- they make it very difficult to write applications that work on all users machines. Consider an application where you have two graphs on the same page, and you want the axes to be aligned. The only way to do this reliably is to set the margin size. If you write code assuming mm and the users machine uses inches, the results will not be pretty. One solution is to attach units to all your values. With a set of base units that supports multiplication by scalars, this could be something like: figure(figsize=(100*mm,50*mm)) A sensible default such as printer points is needed if no units are specified. The reason you need to carry around the units is that you may want the size to scale with the font. For example, you may want to provide for 6 digits in the tic labels, so the margin should be ten times the width of a single digit (allowing for sign and spaces). Currently margins and legend boxes scale with the size of the plot, which is not ideal. Latex uses these units: mm Millimetres cm Centimetres in Inches pt Points (1in = 72.27pt) pc Picas (1pc = 12pt) em The width of the letter M in the current font ex The height of the letter x in the current font - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] speed
On Fri, Nov 09, 2007 at 01:39:10PM -0600, John Hunter wrote: > On Nov 9, 2007 1:12 PM, Michael Droettboom <[EMAIL PROTECTED]> wrote: > > > I've committed my changes on the transforms branch so you can play with > > it -- I'm holding off on changing the trunk due to the pending release. > > But if everyone agrees on the way to expose this, it would be nice to > > merge this over to trunk before the release. > > Am I right in assuming that the only thing we lose in this approach is > faceting (which Eric hates but others may care about)? Since it is > orders of magnitudes faster, we could have a pcolor_faceted which > pcolor calls the old function if shading='faceted'. Of course the two > functions would return different types (image vs patch collection) > which is potentially a bit confusing We could play with adding > faceting to images It is important for us that the entire cell have the same colour. Is this what you get with shading='flat'? Sometimes shading='faceted' is useful. You should be able to do this faster by simply blasting an array of lines over top of shading='flat' than by drawing each individual quadrilateral. Note that I found 'faceted' to be much nicer when the lines are drawn with transparency. Without transparency, a large array turns the entire image black --- not very useful. - Paul - This SF.net email is sponsored by: Splunk Inc. Still grepping through log files to find problems? Stop. Now Search log events and configuration files using AJAX and a browser. Download your FREE copy of Splunk now >> http://get.splunk.com/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] wx draw_idle
Hi,
The attached patch has a couple of changes to the wx backend that I
want people to test before I commit.
1) implement draw_idle. Rather than using the wx IdleEvent which seemed
to be triggered too often I used a timer which is delayed and possibly
reset if a new draw request comes within a certain time period (5 ms),
or if there are pending wx events. The scheme isn't perfect since wx
doesn't see all the native events, but it seems to work well enough.
2) Don't draw bitmap on the screen if the graph isn't shown. Otherwise
a plot inside of a wx aui notebook bleeds through even if the graph
notebook is not on top.
3) Don't regenerate entire plot for each PaintEvent. Instead, only
draw the graph if this is the first time the window is exposed, otherwise
work from the bitmap. I've only tested this for wxagg on the mac. I don't
know if it breaks wx, or if anyone cares about wx anymore.
Let me know if it works for you.
- Paul
Index: backend_wx.py
===
--- backend_wx.py (revision 4696)
+++ backend_wx.py (working copy)
@@ -753,6 +753,10 @@
self._isConfigured = False
self._printQued = []
+# Need to render the window properly if this is the first time
+# it is being shown since it has changed.
+self._isRendered = False
+
if wx.VERSION_STRING >= '2.5':
# Event handlers 2.5
self.Bind(wx.EVT_SIZE, self._onSize)
@@ -789,6 +793,13 @@
self.Printer_Init()
+# Create an timer for handling draw_idle requests
+# If there are events pending when the timer is
+# complete, reset the timer and continue. The
+# alternative approach, binding to wx.EVT_IDLE,
+# doesn't behave as nicely.
+self.idletimer = wx.CallLater(1,self._onDrawIdle)
+
def Destroy(self, *args, **kwargs):
wx.Panel.Destroy(self, *args, **kwargs)
@@ -943,17 +954,36 @@
self.gui_repaint()
-def draw(self, repaint=True):
+def draw_idle(self, *args, **kwargs):
"""
+Render after a delay if no other render requests have been made.
+"""
+DEBUG_MSG("draw_idle()", 1, self)
+self.idletimer.Restart(5, *args, **kwargs) # Delay by 5 ms
+
+def _onDrawIdle(self, *args, **kwargs):
+if False and wx.GetApp().Pending():
+self.idletimer.Restart(5, *args, **kwargs)
+else:
+self.draw(*args, **kwargs)
+
+def draw(self, drawDC=None):
+"""
Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified.
"""
DEBUG_MSG("draw()", 1, self)
-self.renderer = RendererWx(self.bitmap, self.figure.dpi)
-self.figure.draw(self.renderer)
-if repaint:
-self.gui_repaint()
+# Only draw if window is shown, otherwise graph will bleed through
+# on the notebook style AUI widgets.
+if self.IsShownOnScreen():
+self._isRendered = True
+self.renderer = RendererWx(self.bitmap, self.figure.dpi)
+self.figure.draw(self.renderer)
+self.gui_repaint(drawDC=drawDC)
+else:
+self._isRendered = False
+
def _get_imagesave_wildcards(self):
'return the wildcard string for the filesave dialog'
default_filetype = self.get_default_filetype()
@@ -1050,6 +1080,10 @@
# Restore everything to normal
self.bitmap = origBitmap
+# Note: draw is required here since bits of state about the
+# last renderer are strewn about the artist draw methods. Do
+# not remove the draw without first verifying that these have
+# been cleaned up.
self.draw()
self.Refresh()
@@ -1077,10 +,15 @@
DEBUG_MSG("_onPaint()", 1, self)
if not self._isRealized:
self.realize()
-# Render to the bitmap
-self.draw(repaint=False)
-# Update the display using a PaintDC
-self.gui_repaint(drawDC=wx.PaintDC(self))
+
+# Need to draw the graph the first time it is shown otherwise
+# it is a black canvas. After that we can use the rendered
+# bitmap for updates.
+if self._isRendered:
+self.gui_repaint(drawDC=wx.PaintDC(self))
+else:
+self.draw(drawDC=wx.PaintDC(self))
+
evt.Skip()
def _onSize(self, evt):
Index: backend_wxagg.py
===
--- backend_wxagg.py(revision 4696)
+++ backend_wxagg.py(working copy)
@@ -53,16 +53,21 @@
size.
"""
-def draw(self, repaint=True):
+def draw(self, drawDC=None):
"""
Render the figure using agg.
"""
DEBUG_MSG("draw()", 1, self)
-FigureCanvasAgg.draw(self)
-self.bitmap = _convert_agg_to_wx_b
Re: [matplotlib-devel] wx draw_idle
On Tue, Dec 11, 2007 at 10:22:12AM -0800, Christopher Barker wrote: > Paul Kienzle wrote: > > or if there are pending wx events. The scheme isn't perfect since wx > > doesn't see all the native events, but it seems to work well enough. > > I'm confused here -- what events are missed, and why? What do you mean > by a "native" event? Intermediate mouse positions, for example, seem to be consumed. Also, it doesn't seem to recognize pending resize events. Try an experiment such as resizing examples/pcolor_log.py, with N large enough to make redraws slow to see what I mean (N=200 does it for me). I tried changing the _onSize event handler to use draw_idle rather than draw to improve the resize experience but I shut it off because the drawing area turns black and I couldn't figure out how to set it to the figure background colour. It helped slow graphs a little since I could see what the resulting window would look like, but the black was jarring for quick graphs. Any thoughts on implementing preemptive plotting? This would mean putting tests like the following inside potentially expensive loops: if self.isabort(): break where isabort is a method in class artist which delegates to the canvas: return self.figure.canvas.isabort() if self.figure else False For the wx canvas, isabort() would be something like: wx.Yield() # Allow UI events to be processed return self._draw_idle_requested # abort drawing if UI triggered redraw > > 2) Don't draw bitmap on the screen if the graph isn't shown. Otherwise > > a plot inside of a wx aui notebook bleeds through even if the graph > > notebook is not on top. > > hmmm odd -- this does sound right, but shouldn't wx only be re-drawing > in a Paint event anyway? I haven't traced through the wx.aui code so I don't know what is going on. I do know that I have problems if I don't check IsWindowShown before blitting the bitmap onto the screen. > > 3) Don't regenerate entire plot for each PaintEvent. Instead, only > > draw the graph if this is the first time the window is exposed, otherwise > > work from the bitmap. > > This is odd to me too -- I haven't dug into the wx back-end, but it > seems the Paint Event should only trigger a blit of the bitmap to the > screen anyway. It should, but the bitmap may not be initialized when the paint event occurs. This happens when the window is first created (since there is no associated size event) and now when switching aui notebook windows (since I don't render the bitmap if the window isn't shown). - Paul - SF.Net email is sponsored by: Check out the new SourceForge.net Marketplace. It's the best place to buy or sell services for just about anything Open Source. http://sourceforge.net/services/buy/index.php ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] scroll wheel on wx
Hi,
I have a patch which implements the scroll wheel on wx using the
wx mouse wheel event.
Rather than a simple up/down mouse event wx uses:
delta: intervals per click
rotation: number of clicks
rate: number of lines per click
I convert this to:
step = rotation*delta/rate
I've added the step attribute to the mpl MouseEvent in addition to the
usual up/down button (up if step >= 0, down otherwise).
I removed the mpl_connect from the scroll event to pick. I don't know
why it was there.
I tested the patch on OS X WxAgg examples/image_slice_viewer.
Let me know if it is okay to post to svn, or if we are still in feature
freeze.
- Paul
Index: backend_bases.py
===
--- backend_bases.py(revision 4699)
+++ backend_bases.py(working copy)
@@ -776,6 +776,7 @@
inaxes = None # the Axes instance if mouse us over axes
xdata = None # x coord of mouse in data coords
ydata = None # y coord of mouse in data coords
+step = None # for scroll events, the number of steps
"""
x = None # x position - pixels from left of canvas
@@ -784,9 +785,10 @@
inaxes = None # the Axes instance if mouse us over axes
xdata = None # x coord of mouse in data coords
ydata = None # y coord of mouse in data coords
+step = None # for scroll events, the number of steps
def __init__(self, name, canvas, x, y, button=None, key=None,
- guiEvent=None):
+ step=None, guiEvent=None):
"""
x, y in figure coords, 0,0 = bottom, left
button pressed None, 1, 2, 3
@@ -794,6 +796,7 @@
LocationEvent.__init__(self, name, canvas, x, y, guiEvent=guiEvent)
self.button = button
self.key = key
+self.step = step
class PickEvent(Event):
"""
@@ -872,7 +875,7 @@
self._key= None # the key pressed
self._lastx, self._lasty = None, None
self.button_pick_id = self.mpl_connect('button_press_event',self.pick)
-self.scroll_pick_id = self.mpl_connect('scroll_event',self.pick)
+#self.scroll_pick_id = self.mpl_connect('scroll_event',self.pick)
if False:
## highlight the artists that are hit
@@ -1001,15 +1004,17 @@
event = PickEvent(s, self, mouseevent, artist, **kwargs)
self.callbacks.process(s, event)
-def scroll_event(self, x, y, button, guiEvent=None):
+def scroll_event(self, x, y, step, guiEvent=None):
"""
Backend derived classes should call this function on any
scroll wheel event. x,y are the canvas coords: 0,0 is lower,
left. button and key are as defined in MouseEvent
"""
+button = 'up' if step >= 0 else 'down'
self._button = button
s = 'scroll_event'
-mouseevent = MouseEvent(s, self, x, y, button, self._key,
guiEvent=guiEvent)
+mouseevent = MouseEvent(s, self, x, y, button, self._key,
+ step=step, guiEvent=guiEvent)
self.callbacks.process(s, mouseevent)
Index: backends/backend_gtk.py
===
--- backends/backend_gtk.py (revision 4699)
+++ backends/backend_gtk.py (working copy)
@@ -179,10 +179,10 @@
# flipy so y=0 is bottom of canvas
y = self.allocation.height - event.y
if event.direction==gdk.SCROLL_UP:
-direction = 'up'
+step = 1
else:
-direction = 'down'
-FigureCanvasBase.scroll_event(self, x, y, direction)
+step = -1
+FigureCanvasBase.scroll_event(self, x, y, step)
return False # finish event propagation?
def button_press_event(self, widget, event):
Index: backends/backend_wx.py
===
--- backends/backend_wx.py (revision 4699)
+++ backends/backend_wx.py (working copy)
@@ -1174,9 +1174,23 @@
FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=evt)
def _onMouseWheel(self, evt):
-# TODO: implement mouse wheel handler
-pass
+"""Translate mouse wheel events into matplotlib events"""
+# Determine mouse location
+x = evt.GetX()
+y = self.figure.bbox.height() - evt.GetY()
+# Convert delta/rotation/rate into a floating point step size
+delta = evt.GetWheelDelta()
+rotation = evt.GetWheelRotation()
+rate = evt.GetLinesPerAction()
+#print "delta,rotation,rate",delta,rotation,rate
+step = rate*float(rotation)/delta
+
+# Convert to mpl event
+# Note: If Skip(True) then OS X generates two events per click
+evt.Skip(False)
+self.scroll_event(x, y, step, guiEvent=evt)
+
def _onMotion(self, evt):
"""Start measuring o
Re: [matplotlib-devel] New flags in IPython, of interest to matplotlib users
I'm curious about the term 'threading backend'. Recently I posted a question about how to handle slow plots, suggesting that the backend canvas have an isabort() method so that the renderer can stop what it is doing and post the current bitmap as it stands. This is to support interactive operations such as panning and resizing on large data collections. Do you mean something similar when you say 'threading backend', and is it already supported in IPython? - Paul On Wed, Dec 12, 2007 at 01:36:01AM -0700, Fernando Perez wrote: > Hi all, > > This was posted to the ipython-dev list, but since it's specifically > for MPL, I figured the cross-list spam would be forgiven. > > In IPython SVN, I just added the ability to manually control the pylab > threading backend choice directly from the command line. So for > example if by default you have: > > tlon[~]> ipython -pylab --nobanner > > In [1]: matplotlib.rcParams['backend'] > Out[1]: 'TkAgg' > > You can now do this as well: > > tlon[~]> ipython -wthread -pylab --nobanner > > In [1]: matplotlib.rcParams['backend'] > Out[1]: 'WXAgg' > > In [2]: > Closing threads... Done. > tlon[~]> ipython -gthread -pylab --nobanner > > In [1]: matplotlib.rcParams['backend'] > Out[1]: 'GTKAgg' > > The feature is fairly simplistic: the -Xthread flags map automatically > to the XAgg backends in MPL, with no more fine-grained choice than > that. We can later look into allowing explicit backend selection if > you really scream for it, but I'd rather keep this simple. This means > that if you don't have the *Agg builds of the GUI backends, you'll > still need to do the backend selection by hand as before (i.e. by > modifying your mpl config file). > > This has often been requested and I'd needed it myself on multiple > occasions, so it's finally in. > > Cheers, > > f > > - > SF.Net email is sponsored by: > Check out the new SourceForge.net Marketplace. > It's the best place to buy or sell services for > just about anything Open Source. > http://sourceforge.net/services/buy/index.php > ___ > Matplotlib-devel mailing list > [email protected] > https://lists.sourceforge.net/lists/listinfo/matplotlib-devel - SF.Net email is sponsored by: Check out the new SourceForge.net Marketplace. It's the best place to buy or sell services for just about anything Open Source. http://sourceforge.net/services/buy/index.php ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Qt4 backend improvements
On Sun, Jan 27, 2008 at 11:43:16AM -0500, Darren Dale wrote: > He also asked if it would be a good idea to render multiple figures into a > tab > widget instead of creating multiple windows. Its an interesting idea, but > since the size of each figure may vary, it would mean each figure would have > to be rendered into a scrollable area. That might be a useful thing to do in > general, because we could then render figures that are larger than the > screen, but then we would need a new way to change the size of the canvas > because it wouldn't be coupled with the size of the window like it is now. > Maybe this is too disruptive a change. In most cases the window containing a figure will be resizable, and the graph will adjust itself accordingly. Rendering onto a scrollable canvas wouldn't be very useful because you see the data without seeing the axes, which is probably not what you want. What is more of a concern is whether you want to see two figures at once (side by side) or whether you want to focus in on one figure to the exclusion of the others. Even for the same dataset, you will want to switch between these modes of viewing. This would seem to require a notion of 'figure groups' in the pylab interface to control which window the figure would be created in, combined with eclipse-like 'tearable tabs' so you can rearrange the figures however you want. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] New plot type--submission questions
On Thu, Jan 31, 2008 at 08:38:35AM +0100, Rob Hetland wrote: > > I was just working with a student to do this. It is straightforward > (using norms, as Eric suggests), but not short. I think it would be > good to include wrappers for creating these norms to MPL. > > The advantage is then it works for everything: pcolor, scatter, etc. Couldn't you also do this by providing a short colourmap instead of fiddling the norms? - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] backend_driver results in separate directories
Hi,
I have a patch to post the results of examples/backend_driver.py to
a backend specific directory, after first clearing the directory.
Shall I commit?
- Paul
Index: backend_driver.py
===
--- backend_driver.py (revision 4942)
+++ backend_driver.py (working copy)
@@ -131,6 +131,16 @@
_backend = 'cairo'
else:
_backend = backend
+
+# Clear the destination directory for the examples
+path = backend
+if os.path.exists(path):
+import glob
+for fname in os.listdir(path):
+os.unlink(os.path.join(path,fname))
+else:
+os.mkdir(backend)
+
for fname in files:
if fname in exclude:
print '\tSkipping %s, known to fail on backend: %s'%backend
@@ -138,7 +148,7 @@
print ('\tdriving %-40s' % (fname)),
basename, ext = os.path.splitext(fname)
-outfile = basename + '_%s'%backend
+outfile = os.path.join(path,basename)
tmpfile_name = '_tmp_%s.py' % basename
tmpfile = file(tmpfile_name, 'w')
-
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] ginput: blocking call for mouse input
On Tue, Feb 05, 2008 at 03:58:08PM -0600, John Hunter wrote: > On Feb 2, 2008 8:48 AM, Gael Varoquaux <[EMAIL PROTECTED]> wrote: > > > Here is the new patch. I added visual feedback when accumulating points. > > I hope the docstrings are clear. > > Great -- thanks again. I applied this patch and created a new example > ginput_demo.py > > Tested on GTKAgg and TkAgg on my system, and looks good so far. This failed for me in wx. I posted a patch r4943 which moves flush_events from Figure to Canvas, and removes the Yield in gui_repaint which caused an exception in wx. The showfig callback in FigureManagerWx had an unreferenced global variable figwin which I removed. It wasn't obvious to me why this was broken, or how long it has been broken, but the ginput example works for me now. Setting the timeout to 0.01s for the busy loop in ginput seems excessive. Since it is waiting for human interaction, generally 0.1 seconds is good enough. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] backend_driver results in separate directories
On Tue, Feb 05, 2008 at 01:05:55PM -1000, Eric Firing wrote: > Paul Kienzle wrote: > > Hi, > > > > I have a patch to post the results of examples/backend_driver.py to > > a backend specific directory, after first clearing the directory. > > Excellent idea. > > > > > Shall I commit? > > Yes. Done. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] ginput: blocking call for mouse input
On Tue, Feb 05, 2008 at 11:23:14PM +0100, Gael Varoquaux wrote: > On Tue, Feb 05, 2008 at 04:11:59PM -0600, John Hunter wrote: > > Also, my version of GaelInput has seemed to stop evolving. This > > version has the option to draw lines between clicks, which I use a > > lot. Also, the default timeout is 0 now, since you can always > > right-click to abort. > > You can still use this behavoir, using a timeout of zero, n = 0, and the > middle click to end (I use right_click to cancel points). I am not sure > what the default timeout should be. If you have strong opinions about it > being 0, that's fine with me. > > As far as n = 0 being the default, I think this is a bad idea. First of > all, it break matlab-compatibility for no good reasons, second in most > cases, IMHO, the naive programmer only wants one point, and puts some > logics afterwards. He will not read the doc, and wont understand why his > function is not returning after one click (so many people don't even know > how to read docstring, I am not kidding). > > As for the lines, having lines implies that there is a connection order > in your points, which is not always the case. I suggest thus adding a > optional (oof by default) keyword argument for this behavior. In my applications I select multiple points from a particular line, highlighting the point that will be selected as the mouse cursor moves. I put a text message on the plot explaining what to do which disappears when the selection is complete. Some other useful cases are selecting an x-range, a y-range or a box, with the appropriate shading for the selected region. This is still in Tcl/Tk+BLT; I haven't moved it over to Python yet. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] ginput: blocking call for mouse input
On Wed, Feb 06, 2008 at 12:38:32AM +0100, Gael Varoquaux wrote: > On Tue, Feb 05, 2008 at 06:30:53PM -0500, Paul Kienzle wrote: > > Setting the timeout to 0.01s for the busy loop in ginput seems excessive. > > Since it is waiting for human interaction, generally 0.1 seconds is good > > enough. > > I had gone for that originally, but it looked quite ugly when moving the > window around. This busy waiting is quite ugly, but I have found a way of > avoid it. IMHO it should be done in the toolkit's event loop, but it > seems that trying to do it this would add gobbles of code for little > gain. How about giving flush_events() an until=condition and timeout=n keywords so that flush_events becomes: if timeout > 0: set timer event which triggers out_of_time while get next event: process event if out_of_time or until(): break Looking through wx I don't see how to "get next event", my choices being run all events (MainLoop) or run pending events. I do see an "exit main loop" function, so for wx at least one could redirect the event handler for the window and run all the events, exiting the main loop when done, but that seems ugly. I'll look around some more and see if I can find the sleep until next event function in wx. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] ginput: blocking call for mouse input
On Wed, Feb 06, 2008 at 01:21:30AM +0100, Gael Varoquaux wrote: > On Tue, Feb 05, 2008 at 07:16:59PM -0500, Paul Kienzle wrote: > > I'll look around some more and see if I can find the sleep until next > > event function in wx. > > Yeah, sleep, I need more of that. Or maybe you can find wx.coffee ? Sleep not found, despite half the night trying. What follows three experiments I tried, but now I'm out of ideas. The last thing to do would be to follow your suggestion and move the busy loop from ginput to CanvasBase and let the individual backends override with a better solution if available. - Paul Attempted solutions for modal wx event processing: 1. Run a private event loop with a timer every 0.1s to see if the user has done selecting. This works, but it doesn't like it if the window is closed before completion. I didn't test for it, but super-fast clicking should let the user sometimes select an extra point, so not a great solution. def event_loop(self, done=lambda:False, timeout=0): 'run the eventloop until done or timeout' print "Running private event loop" loop = wx.EventLoop() # stop after timeout period def donewaiting(*args,**kw): print "Done waiting" loop.Exit() if timeout > 0: print "Starting timer" outtimer = wx.Timer(self, id=MODAL_TIMEOUT_TIMER) outtimer.Start(timeout*1000, oneShot=True) self.Bind(wx.EVT_TIMER, donewaiting, outtimer) # check if done every 0.1 s def checkdone(*args,**kw): if done(): loop.Exit() steptimer = wx.Timer(self, id=MODAL_STEP_TIMER) steptimer.Start(100, oneShot=False) self.Bind(wx.EVT_TIMER, checkdone, steptimer) loop.Run() steptimer.Stop() return 2. What seems like it should work is to use an event handler which checks after processing each event whether or not this completes the condition and so we can exit the loop. However, ProcessEvent never seems to be called. Reading elsewhere I see that ProcessEvent is not a virtual function in wx, so presumably we can't override it in a subclass of wx.EvtHandler. # Redirect input events to new handler class ModalHandler(wx.EvtHandler): def ProcessEvent(self, evt): print "Processing event" if done(): loop.Exit() return False # True if processed print "Pushing handler" handler = ModalHandler() self.PushEventHandler(handler) print "enabled",handler.GetEvtHandlerEnabled() print "handler->next",handler.GetNextHandler() print "self->previous",self.GetPreviousHandler() loop.Run() self.PopEventHandler(False) print "Done!" 3. Revising two somewhat, I send all events for the canvas through my own event handler. To make sure I see each one I bind each window event to my own dispatcher as well as to the underlying window. I then use this handler rather than self in the canvas __init__. This fails because either the window handler is not called or it is called twice, depending on whether PushEventHandler and ProcessEvent are called. It also fails if the window is closed unexpectedly. class ModalHandler(wx.EvtHandler): def __init__(self, window): print "Creating handler" wx.EvtHandler.__init__(self) self.done = lambda:False window.PushEventHandler(self) self.window = window self.timer = wx.Timer() self.Bind(wx.EVT_TIMER, self.OnTimeout, self.timer) self.loop = wx.EventLoop() def _dispatch(self, evt): """Ick! ProcessEvent is not virtual, so we can't override directly!""" #print "Processing event" self.window.ProcessEvent(evt) if self.done(): self.loop.Exit() print "Returning event" return True def EndModal(self): """Force the loop to exit""" self.done = lambda:True def Bind(self,evt,action,*args,**kw): # Force all events through ProcessEvent. This is the first binding. # ProcessEvent will dispatch the event to the window itself, so be # sure to tell the window what to do with the event. This is the # second binding. if wx.VERSION_STRING >= '2.5': # Event handlers 2.5 print "Binding 2.5" wx.EvtHandler.Bind(self.window,evt,action,*args,**kw) wx.EvtHandler.Bind(self,evt,self._dispatch) else: print "Binding 2.4" evt(self,self.ProcessEvent) evt(self.window,*args,**kw) def OnTimeout(self): print "ti
Re: [matplotlib-devel] ginput: blocking call for mouse input
On Wed, Feb 06, 2008 at 01:21:30AM +0100, Gael Varoquaux wrote: > On Tue, Feb 05, 2008 at 07:16:59PM -0500, Paul Kienzle wrote: > > How about giving flush_events() an until=condition and timeout=n keywords > > so that flush_events becomes: > > > if timeout > 0: set timer event which triggers out_of_time > > while get next event: > >process event > >if out_of_time or until(): break > > I'd say this is exactly the way to do it. The problem is that under GTK > is seems fairly easy to do, under Tk it seems feasible, but under Qt and > under Wx I have no clue how to do this. We can always fallback to > busy-waiting for these toolkits. There are two ways to do this in wx. One is to use eventloop.Dispatch() which waits until the next available event: def _onTimeout(self,evt): 'event loop timer completed' self._event_loop_running = False def event_loop(self, done=lambda:False, timeout=0): 'run the event loop until done or timeout' timer = wx.Timer(self) self._event_loop_running = True if timeout > 0: timer.Start(timeout*1000, oneShot=True) self.Bind(wx.EVT_TIMER, self._onTimeout, timer) loop = wx.EventLoop() while self._event_loop_running and loop.Dispatch() and not done(): #print "Processing event" pass self._event_loop_running = False timer.Stop() The other is to trigger a loop.Exit() from the click callback. Rather than passing a stop condition to the event_loop method, the user would call start_event_loop to start collecting events, and stop_event_loop in the event callback when the terminating condition is reached. In the ginput example, this is just calling self.fig.canvas.stop_event_loop() rather than self.done = True in the callback. The code for this is: def __init__ ... self._event_loop = wx.EventLoop() ... def start_event_loop(self, timeout=0): timer = wx.Timer(self) if timeout > 0: timer.Start(timeout*1000, oneShot=True) self.Bind(wx.EVT_TIMER, self.stop_event_loop, timer) self._event_loop.Run() timer.Stop() def stop_event_loop(self, event=None): if self._event_loop.IsRunning(): self._event_loop.Exit() Note that we need to also check for the window closing while the event loop is running, which we can do using the following at the beginning of start_event_loop: root = self.GetTopLevelParent() root.Bind(wx.EVT_CLOSE, self.stop_event_loop) This will unfortunately kill any window kill event that the application defined. We may also want to give the application direct access to the timer for the purpose of creating animations independent of the toolkit. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] ginput: blocking call for mouse input
On Fri, Feb 08, 2008 at 08:15:20AM +0100, Gael Varoquaux wrote: > On Thu, Feb 07, 2008 at 11:31:11AM -0500, Paul Kienzle wrote: > > There are two ways to do this in wx. > > > One is to use eventloop.Dispatch() which waits until the next available > > event: > > > [...] > > > The other is to trigger a loop.Exit() from the click callback. > > > [...] > > Very nice. I am impressed. We need to find a way of doing the same in > other toolkits. Way can however change the function call flush_event to > give it an "until" callback (and maybe rename it to > "wait_interactively"), and move the busy waiting code in the > backend-dependant part of the code. That way we can remove it backend > after backend. Having played with both "flush_until" and "start/stop" I have to say I prefer the start/stop interface. It removes the need for users to share a 'done' variable between the callback and the caller and the need to create a dummy lambda:done function. Also, it is a better match to the semantics of wx/gtk/qt (see below). I don't like the names start_event_loop/stop_event_loop, but couldn't think of anything better. How about: gui_wait/end_wait? - Paul - Proposed generic implementation based on flush_event and sleep, to be put into CanvasBase: def gui_wait(self, timeout=0): """Run the event loop.""" if timeout == 0: timeout = npy.inf timestep = 0.01 counter = 0 self._waiting = True while self._waiting and counter*timestep < timeout: self.flush_events() time.sleep(timestep) counter += 1 def end_wait(self): """Stop the event loop.""" self._waiting = False Suggested implementation for backend_gtk (untested!!!): def gui_wait(self, timeout=0): """Run the gtk event loop.""" # TODO: call self.end_wait() on window close self._waiting = True if timeout > 0: timer = gtk.gobject.timeout_add(timeout,self._onTimer) gtk.main() self._waiting = False gobject.source_remove(timer) def _onTimer(self): self.end_wait() return False def end_wait(self): """Stop the gtk event loop.""" if self._waiting: gtk.main_quit() - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] A good, interactive plotting package
On Wed, Feb 13, 2008 at 08:24:35AM -0600, John Hunter wrote: > As I mentioned in my earlier post, when we migrate to traits > for matplotlib artist properties, we will get a pretty rich > interactive UI configuration layer. Any sense of when this might happen? Is there anybody outside of enthought who are deploying applications based on TraitsUI for Windows/Mac/Linux? I would love to hear about successful examples before committing to more dependencies in our own applications. What's going to happen with Qt/Gtk/Tkinter backends? We are already using wx so this isn't an issue for us, but last time I looked TraitsUI only had wx support. A specific concern we had when investigating Traits a couple of years ago was long start up times. The lack of clear boundaries between traits and other parts of enthought was a further concern, since it would make deployment more difficult. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] picking bug in SVN with old masked array
On Tue, Feb 19, 2008 at 10:55:14AM -0500, Michael Droettboom wrote: > 2) The picking code for a line assumes non-masked arrays. Since the > Line class already keeps around a "compressed" version of the data for > drawing, it is easy enough to use that instead of the raw data. I didn't provide any masked array checks in any of the contains methods that I wrote. Do any of these need to be fixed? I won't have a lot of time over the next few months, and I will be slow to fix them. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] font troubles
Hi,
In learning to make a nice plot for a small window on a web page,
I had to go through a number of contortions to get the layout correct.
Graph layout should be based on em and ex spacing rather than
portion of the viewable area. The attached file computes the
portions as best it can based on the font size (I don't know if
em and ex are readily available). It still isn't right. In
particular, the legend box width can't be controlled properly,
or the distance between legend and one graph edge since there
is one number for each of axespad and pad regardless of aspect ratio.
I propose allowing all dimensions to carry units with them:
point, pixel, font, axis, figure or data
The x and y dims may have different units. Even for the same
units, the x and y will be different because of aspect ratio.
I would suggest allowing string values such as:
'10pt', '14px', '1ch', '0.01ax', '0.01fig', '35d'
or pairs:
(10,'pt'), (14,'px'), ...
The OOP trick of 10*pt, 14*px, etc. is cute, but the names need
to be much longer for this to work.
The transform= kw on some entries would no longer be necessary.
I won't have time to code this for a long time, but I wanted
to get it out there while it is fresh in my mind, and give
people a chance to comment on it.
A further note: small/medium/large aren't quite what I wanted
for relative font sizes. It would be nice to be able to specify
0.9x/1x/1.1x instead.
- Paul
import numpy
# Note: I'm using Figure and Canvas directly rather than pylab since
# pylab is not thread safe, but my app is.
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as Canvas
# Use relative fonts rather than absolute fonts
# These are all the fields required to control the text size
from matplotlib import rcParams
rcParams['font.size']=10
rcParams['xtick.labelsize'] = 'small'
rcParams['ytick.labelsize'] = 'small'
rcParams['legend.fontsize'] = 'small'
rcParams['axes.labelsize'] = 'medium'
rcParams['axes.titlesize'] = 'medium'
rcParams['legend.numpoints'] = 1
def plotbins(x,yset,title=None,filename=None):
# Compute margin sizes in figure units from size relative to font
fontsize = rcParams['font.size']/72. # fontsize in inches
w,h= 5, 2.5 # figure dims in inches
dw,dh = [fontsize/s for s in (w,h)] # fontsize wrt figure
#l,r,t,b= 0.75/w, .25/w, .5/h, .5/h # margins in inches
l,r,t,b = 4*dw,1*dw,2*dh,2.5*dh # margins wrt to fontsize
aw,ah = w*(1-(l+r)),h*(1-(t+b)) # axes dims in inches
adw,adh = [fontsize/s for s in (aw,ah)] # fontsize wrt axes
# Create figure and axes
fig = Figure(figsize=(w,h),dpi=72)
ax = fig.gca()
ax.set_position([l, b, 1-(l+r), 1-(t+b)])
ax.set_title(title)
ax.set_xlabel('Bin Number')
ax.set_ylabel('Counts')
# Put some text on the graph
# Note: alpha blending on background doesn't seem to work
ax.text(1-0.5*adw, 0.5*adh, 'cumulative histogram',
transform=ax.transAxes, ha='right', va='bottom',
fontsize='small', backgroundcolor=(0.7,0.8,0,0.1))
ax.hold(True)
legend = []
for ylabel,y in yset.items():
ax.plot(x,y,'-+')
legend.append(ylabel)
if len(legend) > 0:
# Set legend properties based on font size
# This doesn't really work because the padding and axespadding
# is affected by aspect ratio. Padding in particular relative
# to the legend box makes the spacing before and after depend
# on the number of lines, but it is the best I can do within
# the context of the transform.
ax.legend(legend, loc='best',
pad=0.75/len(legend), # padding is wrt legend box
axespad=0.5*adh,# axespad is wrt axes
labelsep=0.2*adh, # labelsep is wrt axes
handletextsep=0.5*adw) # handle text is wrt axes
canvas = Canvas(fig)
canvas.print_figure(filename)
x = numpy.arange(10)
yset = dict((label,numpy.cumsum(numpy.random.randint(20,size=10)))
for label in ['apples','oranges','bananas','grapes'])
# Show plots with different font sizes
rcParams['font.size']=9
plotbins(x,yset,title='random fruits 9pt',filename='bins9.png')
rcParams['font.size']=14
plotbins(x,yset,title='random fruits 14pt',filename='bins14.png')
-
This SF.net email is sponsored by the 2008 JavaOne(SM) Conference
Don't miss this year's exciting event. There's still time to save $100.
Use priority code J8TL2D2.
http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] superscript and font size
Hi, The superscripts in mpl don't seem to be placed at the correct height for small fonts. The y-tics on the attached plot shows this. The effect is similar in svg and pdf backends. I'm using 0.91.2 because the latest svn version gives me a KeyError for ufunc isfinite. - Paul <>- This SF.net email is sponsored by the 2008 JavaOne(SM) Conference Don't miss this year's exciting event. There's still time to save $100. Use priority code J8TL2D2. http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] superscript and font size
On Mon, Apr 28, 2008 at 09:51:54AM -0400, Michael Droettboom wrote: > Paul Kienzle wrote: > > > > Thanks. It looks much better in png, but pdf has the subscript raised much > > higher, > That was a DPI-related bug, that is hopefully now fixed in SVN. > > and svg isn't rendering fonts at all (see attached). Yes. > Thanks. The SVG was broken in SVN March 26 trying to workaround an > Inkscape copy/paste bug. I think it is fixed now so it works in Mozilla > and Inkscape simultaneously. But please let me know if you see anything > fishy -- there seems to be a great deal of variability between SVG viewers. Works in Safari 3.1.1, Inkscape 0.45 and FF 2.0.0.14 > Are you seeing this bug with 0.91.2 release, or just the 0.91.2 SVN > branch? I'd be surprised by the former (and I can't reproduce it there). 0.91.2 SVG does indeed work (with the old superscript position of course). - Paul - This SF.net email is sponsored by the 2008 JavaOne(SM) Conference Don't miss this year's exciting event. There's still time to save $100. Use priority code J8TL2D2. http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] Scatter plot legend
On Fri, May 09, 2008 at 10:57:09AM -0500, Paul Novak wrote: > Hello, > > I'm still interested in having a polygon symbol in the legend for a > scatter plot. I've made some changes to the suggestion of Manuel Metz to > make the legend symbol look better (the code-fragment from legend.py is > below). But when resizing the window, the symbol gets stretched and > placed in a bad location; it appears that the symbol is stretched and > scaled in the same manner as the legend box as a whole, while I think it > would look better if the symbol maintained the same size and aspect > ratio, but merely moved to the appropriate location within the resized > legend. > > I would like to add this functionality, but I need some help to > understand the required transformations or scaling to make it look good. > Perhaps someone with a better understanding could provide some help? Even better would be to let the legend be whatever size it needs to be independent of the scale of the axes. I posted earlier on this regarding units. Sorry, I won't have time to implement this myself. - Paul - This SF.net email is sponsored by the 2008 JavaOne(SM) Conference Don't miss this year's exciting event. There's still time to save $100. Use priority code J8TL2D2. http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] future of mpl documentation
On Thu, May 22, 2008 at 02:44:43PM -0400, Darren Dale wrote: > Here is the docstring for the texmanager module: I saw this package for math markup mentioned in the docutils FAQ: http://docutils.sourceforge.net/sandbox/jensj/latex_math/ It should allow you to include latex markup in the docstrings. Has anyone tried it? - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] future of mpl documentation
On Thu, May 22, 2008 at 06:12:15PM -0400, Darren Dale wrote:
> http://dale.chess.cornell.edu/~darren/temp/XPaXS/reflectivity.xml#matrix-method
>
> There is a "show source" link on the left that shows the original ReST wource
> for the current page, here is the math markup:
>
> :math:`sin(x_n^2)`
>
> .. math::
>
>\int_{-\infty}^{\infty}\frac{e^{i\phi}}{1+x^2\frac{e^{i\phi}}{1+x^2}}
>
> The latex file also renders the equations nicely.
I didn't notice since Safari 3.1.1 renders it as:
sin(xn2)
-ei1+x2ei1+x2
where is the write symbol, but all symbols are the same size and no
spacing
or other layout.
It looks okay in Firefox 2.0.0.14 (though it did complain about missing the
mathml
fonts).
IE 7 displays the xml tree.
- Paul
-
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] matplotlib developers needed
Hi, We are developing an application for analysing and displaying neutron scattering data in Python, and a big part of this requires good graphics. We are looking for a user interface developer with a science background to help us. Some of this effort will be to improve the matplotlib backend. If you know any developers who would be interested in such a project, please direct them to our job announcement: http://reflectometry.org/danse/software-job.html Thanks in advance, - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] future of mpl documentation
On Thu, May 22, 2008 at 08:45:02PM -0500, John Hunter wrote: > On Thu, May 22, 2008 at 6:08 PM, Paul Kienzle <[EMAIL PROTECTED]> wrote: > > > It looks okay in Firefox 2.0.0.14 (though it did complain about missing the > > mathml > > fonts). > > > > IE 7 displays the xml tree. > > I don't mind using latex for math where is really helps but I think we > should try to keep it to a minimum, since it appears mathml in the > browsers is poorly supported. I also want to keep the docstrings as > human readable as possible. I know that in some cases latex *adds* to > the human readability, but in other cases it detracts, so we want to > balance the elegance of the final pdflatex generated PDF output with > the reality that many will be seeing the docs either in plain text or > improperly rendered HTML. If it can be done easily enough with ascii > math art, we should prefer that. Yes it is nice to keep things readable for the help system. One possibility is running the docstrings through a preprocessor as part of the install process. This can remove extraneous reST markup, and using tex2mail, convert latex formulae to ascii (I haven't tried it yet, but that's what it claims to do). This also lets you plug in attribute documentation at compile time rather than doing runtime hacks. However, the problem I was referring to above is that IE7 is not rendering the xml, even for pages which did not have mathml. This might be something simple like making sure files use .html rather than .xml. Darren has taken the temp pages down so I can't try that. - Paul - This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse012070mrt/direct/01/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
[matplotlib-devel] colormap menu
Hi,
I created a menu for selecting colormaps from a context menu on the
graph. The attached code cmapmenu.py contains a runnable example.
I've only implemented support for wx.
In general, I would like to be able to add context menu operations
to individual artists on the plot, and will be doing so for my
own applications. Is this something that could live in the
matplotlib backends? Are there users of Qt, Gtk, Tk, ... who
are willing to add support for them?
- Paul
# This program is public domain
"""
Defines CMapMenu, a wx submenu containing colormaps.
=== Example ===
The following defines a context menu with mapper::
import wx
import cmapmenu
...
def onContextMenu(self,event):
popup = wx.Menu()
item = popup.Append(wx.ID_ANY,'&Save image', 'Save image as PNG')
wx.EVT_MENU(self, item.GetId(), self.onSaveImage)
item = popup.Append(wx.ID_ANY,'&Grid on/off', 'Toggle grid lines')
wx.EVT_MENU(self, item.GetId(), self.onGridToggle)
item = popup.AppendMenu(wx.ID_ANY, "Colourmaps",
CMapMenu(self, self.mapper, self.canvas))
The assumption is that mapper and canvas are attributes of the panel for
which the context menu is defined. When the new colour map is selected,
the mapper will be reset and the figure redrawn.
Sometimes you will want to do more than just update the mapper for the
current canvas. You may for example want to record the new colormap name
in the application settings file so that it will be there when the
application is reloaded. To do this, call CMapMenu(callback=self.OnColormap).
This will call the method OnColormap with the parameter name giving the
name of the colormap.
"""
__all__ = ['CMapMenu']
import sys
import wx
import numpy
from matplotlib import cm
def colorbar_bitmap(colormap,length,thickness=10,orientation='horizontal'):
"""
Convert a colormap to a bitmap showing a colorbar for the colormap.
Orientation can be vertical or horizontal (only looks at the first letter).
"""
# Make an RGBA array from the colormap, either horizontally or vertically.
V = colormap(numpy.linspace(0,1,length),bytes=True)
if orientation[0].lower() == 'h':
V = numpy.tile(V,(thickness,1))
bitmap = wx.BitmapFromBufferRGBA(length,thickness,V)
elif orientation[0].lower() == 'v':
V = numpy.tile(V,(1,thickness))
bitmap = wx.BitmapFromBufferRGBA(thickness,length,V)
else:
raise ValueError,"expected orientation [V]ertical or [H]orizontal"
return bitmap
def all_colormaps():
"""
Iterate over the available colormaps
"""
maps = [name
for name in cm.datad.keys()
if not name.endswith("_r")]
maps.sort()
return maps
def grouped_colormaps():
"""
Colormaps grouped by source.
"""
mlab = ['autumn','winter','spring','summer',
'gray','bone','copper','pink',
'cool','hot',
'hsv','jet','spectral',
#'binary', # Seems to be a reverse of gray
'prism','flag']
mlab_r = [m+'_r' for m in mlab]
brewer = ['Accent','Dark2',
'Spectral',
'Paired',
'Blues','Greens','Greys','Oranges','Purples','Reds',
'Pastel1','Pastel2',
'Set1','Set2','Set3',
'BrBG','BuGn','BuPu','GnBu',
'OrRd',
'PiYG','PRGn','PuBu','PuBuGn',
'PuOr','PuRd',
'RdBu','RdGy','RdPu',
'RdYlBu','RdYlGn',
'YlGn','YlGnBu','YlOrBr','YlOrRd',
]
brewer_r = [m+'_r' for m in brewer]
gist = ['gist_ncar','gist_rainbow',
'gist_stern','gist_earth',
'gist_gray','gist_heat',
#'gist_yarg', # Seems to be a reverse of gray
]
gist_r = [m+'_r' for m in gist]
return gist + [None] + mlab + [None] + brewer
def event_callback(callback, **kw):
"""
Add keyword arguments to the event callback.
"""
return lambda evt: callback(evt,**kw)
class CMapMenu(wx.Menu):
"""
Menu tree binding to a list of colormaps.
"""
def __init__(self, window,
mapper=None, canvas=None, callback=None):
"""
Define a context menu for selecting colormaps.
Need a window to use as the event handler.
If mapper is defined, it will be updated with the new colormap.
If canvas is defined, it will update on idle.
"""
wx.Menu.__init__(self)
# OS X needs 16x16 icons; Windows and Linux can be longer
bar_length = 32 if not sys.platform in ['darwin'] else 16
bar_height = 16
self.mapper,self.canvas,self.callback = mapper,canvas,callback
self.selected = None
self.mapid = {}
for name in grouped_colormaps():
if name is None:
self.AppendSeparator()
else:
item = wx.Menu
Re: [matplotlib-devel] patch for adding manual label location selection to clabel
On Thu, Jul 17, 2008 at 08:50:03AM +0200, Manuel Metz wrote: > Just because the discussion about clabel started, I want to post a short > snipplet of code that I found useful. It was some sort of hack to get a > nicer float formating for contours: contour lines represented confidence > levels of 1, 2.5, 5 and 10 per cent, and I wanted a labeling exactly as > I have written it here now. So, fmt='%.1f\%%' would have resulted in > 1.0% 2.5% 5.0% ... but I wanted 1% 2.5% 5% ... The %g format produces "nice" numbers. For example: >>> print " ".join(["%g%%"%v for v in [1.0,2.5,5.01,10.03]]) 1% 2.5% 5% 10.03% - Paul - This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] patch for adding manual label location selection to clabel
On Thu, Jul 17, 2008 at 09:46:16AM +0200, David M. Kaplan wrote: > I don't think the blocking code will be that hard to maintain. It > basically just depends on events, callback functions and time.sleep. If > those are cross-platform, then it shouldn't be a problem. But only time > will tell. My ability and desire to test on multiple platforms is > limited - I use ubuntu/gnome-gtk/linux 100%. In addition to your patch you can put start/stop_event_loop methods into the the canvas. That way backends can specialize their implementation so they don't need a busy loop while waiting for the event. Then you can replace the termination notice in BlockingInput: -self.done = True +self.fig.canvas.stop_event_loop() and move the busy loop to the backend: # wait for n clicks -counter = 0 -while not self.done: -self.fig.canvas.flush_events() -time.sleep(0.01) - -# check for a timeout -counter += 1 -if timeout > 0 and counter > timeout/0.01: -print "ginput timeout"; -break; +self.fig.canvas.start_event_loop(timeout=timeout) In backend_bases.py I have a generic interactive version based on sleep: class FigureCanvasBase: ... def start_event_loop(self, timeout=0): """ Run the event loop. This call blocks until an event callback triggers stop_event_loop() or the timeout interval is exceeded. """ if timeout == 0: timeout = npy.inf timestep = 0.01 counter = 0 self._looping = True while self._looping and counter*timestep < timeout: self.flush_events() time.sleep(timestep) counter += 1 def stop_event_loop(self): """ Stop the event loop. The function which started the event loop can now run to completion. """ self._looping = False In the wx canvas this is specialized as: class FigureCanvasWx(FigureCanvasBase, wx.Panel): ... def start_event_loop(self, timeout=0): """ Run the event loop. This call blocks until an event callback triggers stop_event_loop() or the timeout interval is exceeded. """ root = self.GetTopLevelParent() bind(root, wx.EVT_CLOSE, self.stop_event_loop) id = wx.NewId() timer = wx.Timer(self, id=id) if timeout > 0: timer.Start(timeout*1000, oneShot=True) bind(self, wx.EVT_TIMER, self.stop_event_loop, id=id) self._event_loop.Run() timer.Stop() def stop_event_loop(self, event=None): """ Stop the event loop. The function which started the event loop can now run to completion. """ if self._event_loop.IsRunning(): self._event_loop.Exit() # Event binding code changed after version 2.5 if wx.VERSION_STRING >= '2.5': def bind(actor,event,action,**kw): actor.Bind(event,action,**kw) else: def bind(actor,event,action,id=None): if id is not None: event(actor, id, action) else: event(actor,action) - This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] patch for adding manual label location selection to clabel
On Thu, Jul 17, 2008 at 09:44:48PM +0200, David M. Kaplan wrote: > Another option would be to create a start_event_loop function like Paul > suggested and overload that function in those backends that aren't > interactive so that it returns an error, but this requires writing one > such function for each non-interactive backend. Either create a deeper hierarchy: FigureCanvasBase: def start_event_loop(self, ...): raise NotImplemented FigureCanvasInteractive: def start_event_loop(self, ...): generic interactive using time.sleep MyInteractiveBackend(FigureCanvasInteractive): def start_event_loop(self, ...): specialized interactive code using GUI or a mix-in class: FigureCanvasBase: def start_event_loop(self, ...): raise NotImplemented FigureCanvasEventLoopMixin: def start_event_loop(self, ...): generic interactive using time.sleep MyInteractiveBackend(FigureCanvasBase,FigureCanvasEventLoopMixin): ... no start_event_loop since using the generic mixin ... I prefer the latter, particularly since it won't be needed once the existing interactive backends are implemented. > Also, is there any case > where an event loop would be useful for a graphically non-interactive > backend? If so, this would again mean that this problem would be easier > to deal with once in the Blocking* classes. No reason to. While you could prompt for graph coordinates at the command line on a call to ginput, you could also simply prompt for the coordinates without bothering with ginput. - Paul - This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] patch for adding manual label location selection to clabel
On Fri, Jul 18, 2008 at 11:27:50AM +0200, David M. Kaplan wrote:
> Hi,
>
> On Thu, 2008-07-17 at 16:55 -0400, Paul Kienzle wrote:
> >FigureCanvasBase:
> >def start_event_loop(self, ...):
> >raise NotImplemented
> >FigureCanvasEventLoopMixin:
> >def start_event_loop(self, ...):
> >generic interactive using time.sleep
> >MyInteractiveBackend(FigureCanvasBase,FigureCanvasEventLoopMixin):
> >... no start_event_loop since using the generic mixin ...
> >
>
> So just to make sure that I understand this, "MyInteractiveBackend"
> would be any backend canvas class for whom we want to implement the
> standard generic mixin. For example, the class FigureCanvasGTK would
> inherit FigureCanvasEventLoopMixin until we get around to writing
> something specific for GTK. On the other hand, FigureCanvasWx wouldn't
> inherit the mixin, but would use the WX specific code you sent
> yesterday. And FigureCanvasPs wouldn't get anything at all. Am I
> getting this?
Yes.
> If so, then I will go ahead and make the appropriate modifications.
> Looking at the list of backends, I think it suffices to inherit the
> mixin for the following backends: cairo, cocoagg, fltkagg?, gdk?, gtk,
> qt4, qt, tkagg (wx covered with its own code). All other interactive
> backends should inherit from these. The ones with the question marks I
> am not really sure about, but will assume true unless told otherwise.
$ grep -l button_press_event backends/*.py
backends/backend_cocoaagg.py
backends/backend_fltkagg.py
backends/backend_gtk.py
backends/backend_qt.py
backends/backend_qt4.py
backends/backend_template.py
backends/backend_tkagg.py
backends/backend_wx.py
> I agree with Gael that warning is probably sufficient. This will allow
> code running in the background to pass over interactive commands such as
> ginput. This may be better than an immediate error, but could cause
> problems later in the script when data is expected, but one gets [].
If exceptions aren't used, then non-interactive backends should
return [], and all calls to ginput should be checked:
x = ginput(3,timeout=2)
if len(x) < 3:
print "ginput only returned %d inputs"%(len(x))
Since users aren't going to remember to do this, it is better to
raise an exception so that they at least know later why their code
is breaking.
The current code has another problem in that timeouts will return
a partial list. This could be handle by raising RuntimeError in
ginput:
class BlockingInput:
...
def __call__(...):
...
if n > 0 and len(self.clicks) < n:
raise RuntimeError("Timeout when selecting inputs")
return self.clicks
If you want to get fancy and return the partial list of clicks,
this can be done with our own exception class:
--blocking_input.py--
class InputError(Exception):
def __init__(self, message, points):
self.message = message
self.points = points
class BlockingInput:
...
def __call__(...):
...
if n > 0 and len(self.clicks) < n:
raise InputError("Not enough inputs",self.clicks)
return self.clicks
Importing an extra symbol to catch the error would be ugly. I
suggest hiding it in the functions that need it instead:
--pyplot.py--
def ginput(*args, **kwargs):
...
ginput.InputError = matplotlib.blocking_input.InputError
This allows the pylab user to write:
try:
x = ginput(3,timeout=2)
except ginput.InputError,e:
print "ginput only returned %d inputs"%(len(e.points))
- Paul
-
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/
___
Matplotlib-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] patch for adding manual label location selection to clabel
On Fri, Jul 18, 2008 at 09:17:02PM +0200, David M. Kaplan wrote: > For ginput, there are a number of ways that an impartial list could be > returned and this is often a desired outcome (for example, I often > decide after the fact that I want fewer points than I initially > thought). Can't you use ginput(0) for these cases? It doesn't work on Mac with no middle mouse button to terminate the sequence, but that is a separate issue. > Perhaps as a compromise we could set the default timeout to > -1 so the user needs to actually choose a timeout (presumably indicating > he/she accepts the consequences). But allowing the user to manually > decide to select fewer points using the second mouse button has proved > quite useful to me and the user would still need to test in this case. > We could warn if not enough points are returned, but an error seems too > much to me. The cases I'm thinking about (e.g., select fit range) have a specific number of points. Other cases (e.g., select shape outline) have an indefinite number of points. I can't think of case off hand where I would want e.g., six or fewer points. That said, I can always wrap the function in my own interface for my scripts. - Paul - This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
Re: [matplotlib-devel] units support
On Mon, Jul 21, 2008 at 04:42:39PM -0700, Ted Drain wrote: > The public layer would just do conversions and then pass through to the > private layer. Any code in the public layer would have to concern itself > with possible different types (numpy vs lists, units vs floats, color names > vs rgb). Any code written in the private layer could be assured of having > some specific input types and would be much easier to write. Keep in mind that public units need to be tied to font in order to get nice looking results. I commented on this earlier: http://www.nabble.com/font-troubles-td16601826.html#a16601826 I'm not sure all the necessary information to transform to pixels will be available at the time the units are parsed, and we may need to carry them into the private layer. > Of course this would be a lot work and would require refactoring axis and > maybe some of the collections. In theory it should be possible, but only > you guys can decide if it's actually worthwhile or not. One of the things I miss from Tcl/Tk is the ability to use units on values. The link above shows that you can simulate units from outside, but the code is ugly. - Paul - This SF.Net email is sponsored by the Moblin Your Move Developer's challenge Build the coolest Linux based applications with Moblin SDK & win great prizes Grand prize is a trip for two to an Open Source event anywhere in the world http://moblin-contest.org/redirect.php?banner_id=100&url=/ ___ Matplotlib-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
