You can subscribe to this list here.
| 2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(115) |
Aug
(120) |
Sep
(137) |
Oct
(170) |
Nov
(461) |
Dec
(263) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2008 |
Jan
(120) |
Feb
(74) |
Mar
(35) |
Apr
(74) |
May
(245) |
Jun
(356) |
Jul
(240) |
Aug
(115) |
Sep
(78) |
Oct
(225) |
Nov
(98) |
Dec
(271) |
| 2009 |
Jan
(132) |
Feb
(84) |
Mar
(74) |
Apr
(56) |
May
(90) |
Jun
(79) |
Jul
(83) |
Aug
(296) |
Sep
(214) |
Oct
(76) |
Nov
(82) |
Dec
(66) |
| 2010 |
Jan
(46) |
Feb
(58) |
Mar
(51) |
Apr
(77) |
May
(58) |
Jun
(126) |
Jul
(128) |
Aug
(64) |
Sep
(50) |
Oct
(44) |
Nov
(48) |
Dec
(54) |
| 2011 |
Jan
(68) |
Feb
(52) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <jd...@us...> - 2008-07-24 13:30:56
|
Revision: 5836
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5836&view=rev
Author: jdh2358
Date: 2008-07-24 13:30:53 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
Merged revisions 5834 via svnmerge from
https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v0_91_maint
........
r5834 | jdh2358 | 2008-07-24 08:15:23 -0500 (Thu, 24 Jul 2008) | 1 line
deprecated mlab2 functions from mlab
........
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/blocking_input.py
trunk/matplotlib/lib/matplotlib/contour.py
trunk/matplotlib/lib/matplotlib/mlab.py
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-5833
+ /branches/v0_91_maint:1-5835
Modified: trunk/matplotlib/lib/matplotlib/blocking_input.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/blocking_input.py 2008-07-24 13:21:17 UTC (rev 5835)
+++ trunk/matplotlib/lib/matplotlib/blocking_input.py 2008-07-24 13:30:53 UTC (rev 5836)
@@ -274,11 +274,22 @@
lw = cs.get_label_width(cs.labelLevelList[lmin],
cs.labelFmt, cs.labelFontSizeList[lmin])
+ """
+ # requires python 2.5
# Figure out label rotation.
rotation,nlc = cs.calc_label_rot_and_inline(
slc, imin, lw, lc if self.inline else [],
self.inline_spacing )
+ """
+ # Figure out label rotation.
+ if self.inline: lcarg = lc
+ else: lcarg = []
+ rotation,nlc = cs.calc_label_rot_and_inline(
+ slc, imin, lw, lcarg,
+ self.inline_spacing )
+
+
cs.add_label(xmin,ymin,rotation,cs.labelLevelList[lmin],
cs.labelCValueList[lmin])
Modified: trunk/matplotlib/lib/matplotlib/contour.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/contour.py 2008-07-24 13:21:17 UTC (rev 5835)
+++ trunk/matplotlib/lib/matplotlib/contour.py 2008-07-24 13:30:53 UTC (rev 5836)
@@ -329,15 +329,15 @@
return x, y, dind
- def calc_label_rot_and_inline( self, slc, ind, lw, lc=[], spacing=5 ):
+ def calc_label_rot_and_inline( self, slc, ind, lw, lc=None, spacing=5 ):
"""
This function calculates the appropriate label rotation given
the linecontour coordinates in screen units, the index of the
label location and the label width.
It will also break contour and calculate inlining if *lc* is
- not empty. *spacing* is the space around the label in pixels
- to leave empty.
+ not empty (lc defaults to the empty list if None). *spacing*
+ is the space around the label in pixels to leave empty.
Do both of these tasks at once to avoid calling cbook.path_length
multiple times, which is relatively costly.
@@ -348,6 +348,7 @@
determine rotation and then to break contour if desired.
"""
+ if lc is None: lc = []
# Half the label width
hlw = lw/2.0
@@ -483,8 +484,10 @@
if self.print_label(slc,lw):
x,y,ind = self.locate_label(slc, lw)
+ if inline: lcarg = lc
+ else: lcarg = []
rotation,new=self.calc_label_rot_and_inline(
- slc0, ind, lw, lc if inline else [],
+ slc0, ind, lw, lcarg,
inline_spacing )
# Actually add the label
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-07-24 13:21:17 UTC (rev 5835)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-07-24 13:30:53 UTC (rev 5836)
@@ -1771,181 +1771,51 @@
### end fperez numutils code
-### begin mlab2 functions
-# From MLab2: http://pdilib.sourceforge.net/MLab2.py
-readme = \
- """
-MLab2.py, release 1
-Created on February 2003 by Thomas Wendler as part of the Emotionis Project.
-This script is supposed to implement Matlab functions that were left out in
-numerix.mlab.py (part of Numeric Python).
-For further information on the Emotionis Project or on this script, please
-contact their authors:
-Rodrigo Benenson, rodrigob at elo dot utfsm dot cl
-Thomas Wendler, thomasw at elo dot utfsm dot cl
-Look at: http://pdilib.sf.net for new releases.
-"""
-## mlab2 functions numpified and checked 2007/08/04
-_eps_approx = 1e-13
-
-#from numpy import fix
-def fix(x):
- """
- Rounds towards zero.
- x_rounded = fix(x) rounds the elements of x to the nearest integers
- towards zero.
- For negative numbers is equivalent to ceil and for positive to floor.
- """
- warnings.warn("Use numpy.fix()", DeprecationWarning)
- return np.fix(x)
-
def rem(x,y):
"""
- Remainder after division.
- rem(x,y) is equivalent to x - y.*fix(x./y) in case y is not zero.
- By convention (but contrary to numpy), rem(x,0) returns None.
- This also differs from numpy.remainder, which uses floor instead of
- fix.
+ Deprecated - see numpy.remainder
"""
- x,y = np.asarray(x), np.asarray(y)
- if np.any(y == 0):
- return None
- return x - y * np.fix(x/y)
+ raise NotImplementedError('Deprecated - see numpy.remainder')
-
def norm(x,y=2):
"""
- This function is deprecated - use numpy.linalg.norm instead.
-
- Norm of a matrix or a vector. Functions similar to the Matlab (TM)
- function of the same name.
-
- Call signature::
-
- norm(x,y=2)
-
- This function behaves differently for vectors and matrices. For vectors,
- it returns the y'th norm of x (i.e. (sum(abs(x)**y))**(1.0/y).
-
- For matrices, if y=2, then it returns the largest singular value
- of X, namely max(linalg.svd(x)). If y=1, returns the largest
- column sum of x (i.e., max(sum(abs(x),axis=0)) ). If y=inf,
- returns the largest row sum. If y='fro', returns the Frobenius
- norm, sqrt(sum(diag(dot(x.transpose(),x)))).
+ Deprecated - see numpy.linalg.norm
"""
- warnings.warn( "Use numpy.linalg.norm instead", DeprecationWarning )
+ raise NotImplementedError('Deprecated - see numpy.linalg.norm')
- x = np.asarray(x)
- if x.ndim == 2:
- if y==2:
- return np.max(np.linalg.svd(x)[1])
- elif y==1:
- return np.max(np.sum(np.absolute((x)), axis=0))
- elif y=='inf':
- return np.max(np.sum(np.absolute((np.transpose(x))), axis=0))
- elif y=='fro':
- xx = np.dot(x.transpose(), x)
- return np.sqrt(np.sum(np.diag(xx), axis=0))
- else:
- raise ValueError('Second argument not permitted for matrices')
- else:
- xa = np.absolute(x)
- if y == 'inf':
- return np.max(xa)
- elif y == '-inf':
- return np.min(xa)
- else:
- return np.power(np.sum(np.power(xa,y)),1/float(y))
-
-
def orth(A):
"""
- Orthogonalization procedure similar to Matlab (TM) function of the same
- name.
-
- Call signature::
-
- Q = orth(A)
-
- Returns an orthonormal basis with the range of A. Q is an orthonormal
- matrix (i.e., dot( Q.transpose(), Q ) is an identity matrix) and the
- columns of Q span the same space as the columns of A.
+ Deprecated - needs clean room implementation
"""
+ raise NotImplementedError('Deprecated - needs clean room implementation')
- A = np.asarray(A)
- U,S,V = np.linalg.svd(A)
-
- m,n = A.shape
- if m > 1:
- s = S
- elif m == 1:
- s = S[0]
- else:
- s = 0
-
- tol = max(m,n) * np.max(s) * _eps_approx
- r = np.sum(s > tol)
- Q = np.take(U,range(r),1)
-
- return Q
-
def rank(x):
"""
- Returns the rank of a matrix.
- The rank is understood here as the an estimation of the number of
- linearly independent rows or columns (depending on the size of the
- matrix).
- Note that numerix.mlab.rank() is not equivalent to Matlab's rank.
- This function is!
+ Deprecated - see numpy.rank
"""
- x = np.asarray(x)
- s = np.linalg.svd(x, compute_uv=False)
- maxabs = np.max(np.absolute(s))
- maxdim = max(x.shape)
- tol = maxabs * maxdim * _eps_approx
- return np.sum(s > tol)
+ raise NotImplementedError('Deprecated - see numpy.rank')
def sqrtm(x):
"""
- Returns the square root of a square matrix.
- This means that s=sqrtm(x) implies dot(s,s) = x.
- Note that s and x are matrices.
+ Deprecated - needs clean room implementation
"""
- return mfuncC(np.sqrt, x)
+ raise NotImplementedError('Deprecated - needs clean room implementation')
def mfuncC(f, x):
"""
- mfuncC(f, x) : matrix function with possibly complex eigenvalues.
- Note: Numeric defines (v,u) = eig(x) => x*u.T = u.T * Diag(v)
- This function is needed by sqrtm and allows further functions.
+ Deprecated
"""
+ raise NotImplementedError('Deprecated - needs clean room implementation')
- x = np.asarray(x)
- (v,uT) = np.linalg.eig(x)
- V = np.diag(f(v+0j))
- # todo: warning: this is not exactly what matlab does
- # MATLAB "B/A is roughly the same as B*inv(A)"
- y = np.dot(uT, np.dot(V, np.linalg.inv(uT)))
- return approx_real(y)
-
def approx_real(x):
-
"""
- approx_real(x) : returns x.real if |x.imag| < |x.real| * _eps_approx.
- This function is needed by sqrtm and allows further functions.
+ Deprecated - needs clean room implementation
"""
- ai = np.absolute(x.imag)
- ar = np.absolute(x.real)
- if np.max(ai) <= np.max(ar) * _eps_approx:
- return x.real
- else:
- return x
+ raise NotImplementedError('Deprecated - needs clean room implementation')
-### end mlab2 functions
-
#helpers for loading, saving, manipulating and viewing numpy record arrays
def safe_isnan(x):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-07-24 13:21:19
|
Revision: 5835
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5835&view=rev
Author: jdh2358
Date: 2008-07-24 13:21:17 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
trying to get mlab2 changes merged
Property Changed:
----------------
trunk/matplotlib/
Property changes on: trunk/matplotlib
___________________________________________________________________
Modified: svnmerge-integrated
- /branches/v0_91_maint:1-5787
+ /branches/v0_91_maint:1-5833
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-07-24 13:15:25
|
Revision: 5834
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5834&view=rev
Author: jdh2358
Date: 2008-07-24 13:15:23 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
deprecated mlab2 functions from mlab
Modified Paths:
--------------
branches/v0_91_maint/lib/matplotlib/mlab.py
Modified: branches/v0_91_maint/lib/matplotlib/mlab.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/mlab.py 2008-07-24 13:03:26 UTC (rev 5833)
+++ branches/v0_91_maint/lib/matplotlib/mlab.py 2008-07-24 13:15:23 UTC (rev 5834)
@@ -1768,52 +1768,47 @@
def rem(x,y):
"""
- Deprecated -- see numpy.remainder
+ Deprecated - see numpy.remainder
"""
raise NotImplementedError('Deprecated - see numpy.remainder')
def norm(x,y=2):
"""
- Deprecated -- see numpy.linalg.norm
+ Deprecated - see numpy.linalg.norm
"""
raise NotImplementedError('Deprecated - see numpy.linalg.norm')
-
def orth(A):
"""
- Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you
- need this function
+ Deprecated - needs clean room implementation
"""
- raise NotImplementedError('Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you need this function')
+ raise NotImplementedError('Deprecated - needs clean room implementation')
def rank(x):
"""
- Deprecated -- see numpy.rank
+ Deprecated - see numpy.rank
"""
raise NotImplementedError('Deprecated - see numpy.rank')
def sqrtm(x):
"""
- Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you
- need this function
+ Deprecated - needs clean room implementation
"""
- raise NotImplementedError('Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you need this function')
+ raise NotImplementedError('Deprecated - needs clean room implementation')
def mfuncC(f, x):
"""
- Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you
- need this function
+ Deprecated
"""
- raise NotImplementedError('Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you need this function')
+ raise NotImplementedError('Deprecated - needs clean room implementation')
def approx_real(x):
"""
- Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you
- need this function
+ Deprecated - needs clean room implementation
"""
- raise NotImplementedError('Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you need this function')
+ raise NotImplementedError('Deprecated - needs clean room implementation')
#helpers for loading, saving, manipulating and viewing numpy record arrays
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-07-24 13:03:28
|
Revision: 5833
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5833&view=rev
Author: jdh2358
Date: 2008-07-24 13:03:26 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
deprecated mlab2 functions from mlab
Modified Paths:
--------------
branches/v0_91_maint/API_CHANGES
branches/v0_91_maint/lib/matplotlib/pylab.py
Modified: branches/v0_91_maint/API_CHANGES
===================================================================
--- branches/v0_91_maint/API_CHANGES 2008-07-24 12:58:19 UTC (rev 5832)
+++ branches/v0_91_maint/API_CHANGES 2008-07-24 13:03:26 UTC (rev 5833)
@@ -1,4 +1,4 @@
- Removed mlab2 functions from mlab
+ Deprecated all mlab2 functions in mlab
matplotlib.image.imread now no longer always returns RGBA -- if
the image is luminance or RGB, it will return a MxN or MxNx3 array
Modified: branches/v0_91_maint/lib/matplotlib/pylab.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/pylab.py 2008-07-24 12:58:19 UTC (rev 5832)
+++ branches/v0_91_maint/lib/matplotlib/pylab.py 2008-07-24 13:03:26 UTC (rev 5833)
@@ -233,7 +233,7 @@
from matplotlib.mlab import window_hanning, window_none,\
conv, detrend, detrend_mean, detrend_none, detrend_linear,\
polyfit, polyval, entropy, normpdf,\
- levypdf, find, trapz, prepca, fix, rem, norm, orth, rank,\
+ levypdf, find, trapz, prepca, rem, norm, orth, rank,\
sqrtm, prctile, center_matrix, rk4, exp_safe, amap,\
sum_flat, mean_flat, rms_flat, l1norm, l2norm, norm, frange,\
diagonal_matrix, base_repr, binary_repr, log2, ispower2,\
@@ -255,8 +255,8 @@
mfuncC, approx_real, rec_append_field, rec_drop_fields, rec_join, csv2rec, rec2csv
-
+
# old style--if True, override standard numpy with oldnumeric
if False:
from numpy.oldnumeric import array, zeros, shape, rank, size, fromstring,\
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-07-24 12:58:22
|
Revision: 5832
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5832&view=rev
Author: jdh2358
Date: 2008-07-24 12:58:19 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
removed mlab2 functions
Modified Paths:
--------------
branches/v0_91_maint/API_CHANGES
branches/v0_91_maint/lib/matplotlib/mlab.py
Modified: branches/v0_91_maint/API_CHANGES
===================================================================
--- branches/v0_91_maint/API_CHANGES 2008-07-24 10:02:13 UTC (rev 5831)
+++ branches/v0_91_maint/API_CHANGES 2008-07-24 12:58:19 UTC (rev 5832)
@@ -1,3 +1,5 @@
+ Removed mlab2 functions from mlab
+
matplotlib.image.imread now no longer always returns RGBA -- if
the image is luminance or RGB, it will return a MxN or MxNx3 array
if possible. Also uint8 is no longer always forced to float.
Modified: branches/v0_91_maint/lib/matplotlib/mlab.py
===================================================================
--- branches/v0_91_maint/lib/matplotlib/mlab.py 2008-07-24 10:02:13 UTC (rev 5831)
+++ branches/v0_91_maint/lib/matplotlib/mlab.py 2008-07-24 12:58:19 UTC (rev 5832)
@@ -1765,178 +1765,56 @@
### end fperez numutils code
-### begin mlab2 functions
-# From MLab2: http://pdilib.sourceforge.net/MLab2.py
-readme = \
- """
-MLab2.py, release 1
-Created on February 2003 by Thomas Wendler as part of the Emotionis Project.
-This script is supposed to implement Matlab functions that were left out in
-numerix.mlab.py (part of Numeric Python).
-For further information on the Emotionis Project or on this script, please
-contact their authors:
-Rodrigo Benenson, rodrigob at elo dot utfsm dot cl
-Thomas Wendler, thomasw at elo dot utfsm dot cl
-Look at: http://pdilib.sf.net for new releases.
-"""
-## mlab2 functions numpified and checked 2007/08/04
-_eps_approx = 1e-13
-
-#from numpy import fix
-def fix(x):
- """
- Rounds towards zero.
- x_rounded = fix(x) rounds the elements of x to the nearest integers
- towards zero.
- For negative numbers is equivalent to ceil and for positive to floor.
- """
- warnings.warn("Use numpy.fix()", DeprecationWarning)
- return np.fix(x)
-
def rem(x,y):
"""
- Remainder after division.
- rem(x,y) is equivalent to x - y.*fix(x./y) in case y is not zero.
- By convention (but contrary to numpy), rem(x,0) returns None.
- This also differs from numpy.remainder, which uses floor instead of
- fix.
+ Deprecated -- see numpy.remainder
"""
- x,y = np.asarray(x), np.asarray(y)
- if np.any(y == 0):
- return None
- return x - y * np.fix(x/y)
+ raise NotImplementedError('Deprecated - see numpy.remainder')
-
def norm(x,y=2):
"""
- Norm of a matrix or a vector according to Matlab.
- The description is taken from Matlab:
-
- For matrices...
- NORM(X) is the largest singular value of X, max(svd(X)).
- NORM(X,2) is the same as NORM(X).
- NORM(X,1) is the 1-norm of X, the largest column sum,
- = max(sum(abs((X)))).
- NORM(X,inf) is the infinity norm of X, the largest row sum,
- = max(sum(abs((X')))).
- NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))).
- NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'.
-
- For vectors...
- NORM(V,P) = sum(abs(V).^P)^(1/P).
- NORM(V) = norm(V,2).
- NORM(V,inf) = max(abs(V)).
- NORM(V,-inf) = min(abs(V)).
+ Deprecated -- see numpy.linalg.norm
"""
+ raise NotImplementedError('Deprecated - see numpy.linalg.norm')
- x = np.asarray(x)
- if x.ndim == 2:
- if y==2:
- return np.max(np.linalg.svd(x)[1])
- elif y==1:
- return np.max(np.sum(np.absolute((x)), axis=0))
- elif y=='inf':
- return np.max(np.sum(np.absolute((np.transpose(x))), axis=0))
- elif y=='fro':
- xx = np.dot(x.transpose(), x)
- return np.sqrt(np.sum(np.diag(xx), axis=0))
- else:
- raise ValueError('Second argument not permitted for matrices')
- else:
- xa = np.absolute(x)
- if y == 'inf':
- return np.max(xa)
- elif y == '-inf':
- return np.min(xa)
- else:
- return np.power(np.sum(np.power(xa,y)),1/float(y))
-
def orth(A):
"""
- Orthogonalization procedure by Matlab.
- The description is taken from its help:
-
- Q = ORTH(A) is an orthonormal basis for the range of A.
- That is, Q'*Q = I, the columns of Q span the same space as
- the columns of A, and the number of columns of Q is the
- rank of A.
+ Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you
+ need this function
"""
+ raise NotImplementedError('Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you need this function')
- A = np.asarray(A)
- U,S,V = np.linalg.svd(A)
-
- m,n = A.shape
- if m > 1:
- s = S
- elif m == 1:
- s = S[0]
- else:
- s = 0
-
- tol = max(m,n) * np.max(s) * _eps_approx
- r = np.sum(s > tol)
- Q = np.take(U,range(r),1)
-
- return Q
-
def rank(x):
"""
- Returns the rank of a matrix.
- The rank is understood here as the an estimation of the number of
- linearly independent rows or columns (depending on the size of the
- matrix).
- Note that numerix.mlab.rank() is not equivalent to Matlab's rank.
- This function is!
+ Deprecated -- see numpy.rank
"""
- x = np.asarray(x)
- s = np.linalg.svd(x, compute_uv=False)
- maxabs = np.max(np.absolute(s))
- maxdim = max(x.shape)
- tol = maxabs * maxdim * _eps_approx
- return np.sum(s > tol)
+ raise NotImplementedError('Deprecated - see numpy.rank')
def sqrtm(x):
"""
- Returns the square root of a square matrix.
- This means that s=sqrtm(x) implies dot(s,s) = x.
- Note that s and x are matrices.
+ Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you
+ need this function
"""
- return mfuncC(np.sqrt, x)
+ raise NotImplementedError('Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you need this function')
def mfuncC(f, x):
"""
- mfuncC(f, x) : matrix function with possibly complex eigenvalues.
- Note: Numeric defines (v,u) = eig(x) => x*u.T = u.T * Diag(v)
- This function is needed by sqrtm and allows further functions.
+ Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you
+ need this function
"""
+ raise NotImplementedError('Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you need this function')
- x = np.asarray(x)
- (v,uT) = np.linalg.eig(x)
- V = np.diag(f(v+0j))
- # todo: warning: this is not exactly what matlab does
- # MATLAB "B/A is roughly the same as B*inv(A)"
- y = np.dot(uT, np.dot(V, np.linalg.inv(uT)))
- return approx_real(y)
-
def approx_real(x):
-
"""
- approx_real(x) : returns x.real if |x.imag| < |x.real| * _eps_approx.
- This function is needed by sqrtm and allows further functions.
+ Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you
+ need this function
"""
- ai = np.absolute(x.imag)
- ar = np.absolute(x.real)
- if np.max(ai) <= np.max(ar) * _eps_approx:
- return x.real
- else:
- return x
+ raise NotImplementedError('Deprecated -- use http://pdilib.sourceforge.net/MLab2.py if you need this function')
-### end mlab2 functions
-
#helpers for loading, saving, manipulating and viewing numpy record arrays
def safe_isnan(x):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <dmk...@us...> - 2008-07-24 10:02:20
|
Revision: 5831
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5831&view=rev
Author: dmkaplan
Date: 2008-07-24 10:02:13 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
Moving "event loop" stuff from blocking_input.py to backends. For backends
without a GUI, the default is to throw a NotImplemented error. For backends
with a GUI, I have implemented a "start/stop_event_loop_default" that does
the default event loop using time.sleep. For WX, I have used the code
supplied by Paul Kienzle, but I have been unable to check it because that
backend currently doesn't work for me.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backend_bases.py
trunk/matplotlib/lib/matplotlib/backends/backend_cocoaagg.py
trunk/matplotlib/lib/matplotlib/backends/backend_fltkagg.py
trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py
trunk/matplotlib/lib/matplotlib/backends/backend_qt.py
trunk/matplotlib/lib/matplotlib/backends/backend_qt4.py
trunk/matplotlib/lib/matplotlib/backends/backend_tkagg.py
trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
trunk/matplotlib/lib/matplotlib/blocking_input.py
Modified: trunk/matplotlib/lib/matplotlib/backend_bases.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-07-24 08:50:43 UTC (rev 5830)
+++ trunk/matplotlib/lib/matplotlib/backend_bases.py 2008-07-24 10:02:13 UTC (rev 5831)
@@ -23,7 +23,7 @@
"""
from __future__ import division
-import os, warnings
+import os, warnings, time
import numpy as np
import matplotlib.cbook as cbook
@@ -1391,7 +1391,76 @@
"""
raise NotImplementedError
+ def start_event_loop(self,*args,**kwargs):
+ """
+ Start an event loop. This is used to start a blocking event
+ loop so that interactive functions, such as ginput and
+ waitforbuttonpress, can wait for events. This should not be
+ confused with the main GUI event loop, which is always running
+ and has nothing to do with this.
+ This is implemented only for backends with GUIs.
+ """
+ raise NotImplementedError
+
+ def stop_event_loop(self,*args,**kwargs):
+ """
+ Stop an event loop. This is used to stop a blocking event
+ loop so that interactive functions, such as ginput and
+ waitforbuttonpress, can wait for events.
+
+ This is implemented only for backends with GUIs.
+ """
+ raise NotImplementedError
+
+ def start_event_loop_default(self,timeout=0):
+ """
+ Start an event loop. This is used to start a blocking event
+ loop so that interactive functions, such as ginput and
+ waitforbuttonpress, can wait for events. This should not be
+ confused with the main GUI event loop, which is always running
+ and has nothing to do with this.
+
+ This function provides default event loop functionality based
+ on time.sleep that is meant to be used until event loop
+ functions for each of the GUI backends can be written. As
+ such, it throws a deprecated warning.
+
+ Call signature::
+
+ start_event_loop_default(self,timeout=0)
+
+ This call blocks until a callback function triggers
+ stop_event_loop() or *timeout* is reached. If *timeout* is
+ <=0, never timeout.
+ """
+ str = "Using default event loop until function specific"
+ str += " to this GUI is implemented"
+ warnings.warn(str,DeprecationWarning)
+
+ if timeout <= 0: timeout = np.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_default(self):
+ """
+ Stop an event loop. This is used to stop a blocking event
+ loop so that interactive functions, such as ginput and
+ waitforbuttonpress, can wait for events.
+
+ Call signature::
+
+ stop_event_loop_default(self)
+ """
+ self._looping = False
+
+
+
class FigureManagerBase:
"""
Helper class for matlab mode, wraps everything up into a neat bundle
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_cocoaagg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_cocoaagg.py 2008-07-24 08:50:43 UTC (rev 5830)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_cocoaagg.py 2008-07-24 10:02:13 UTC (rev 5831)
@@ -58,6 +58,16 @@
def blit(self, bbox):
pass
+ def start_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.start_event_loop_default(self,*args,**kwargs)
+ start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__
+
+ def stop_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.stop_event_loop_default(self,*args,**kwargs)
+ stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__
+
+
+
NibClassBuilder.extractClasses('Matplotlib.nib', mplBundle)
class MatplotlibController(NibClassBuilder.AutoBaseClass):
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_fltkagg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_fltkagg.py 2008-07-24 08:50:43 UTC (rev 5830)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_fltkagg.py 2008-07-24 10:02:13 UTC (rev 5831)
@@ -247,6 +247,14 @@
def widget(self):
return self.canvas
+ def start_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.start_event_loop_default(self,*args,**kwargs)
+ start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__
+
+ def stop_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.stop_event_loop_default(self,*args,**kwargs)
+ stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__
+
def destroy_figure(ptr,figman):
figman.window.hide()
Gcf.destroy(figman._num)
@@ -491,7 +499,7 @@
default_filetype = base.canvas.get_default_filetype()
sorted_filetypes = filetypes.items()
sorted_filetypes.sort()
-
+
selected_filter = 0
filters = []
for i, (ext, name) in enumerate(sorted_filetypes):
@@ -518,7 +526,7 @@
lastDir = os.path.dirname(fname)
file_chooser.directory(lastDir)
format = sorted_filetypes[file_chooser.filter_value()][0]
-
+
try:
base.canvas.print_figure(fname, format=format)
except IOError, msg:
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py 2008-07-24 08:50:43 UTC (rev 5830)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_gtk.py 2008-07-24 10:02:13 UTC (rev 5831)
@@ -396,7 +396,14 @@
gtk.gdk.flush()
gtk.gdk.threads_leave()
+ def start_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.start_event_loop_default(self,*args,**kwargs)
+ start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__
+ def stop_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.stop_event_loop_default(self,*args,**kwargs)
+ stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__
+
class FigureManagerGTK(FigureManagerBase):
"""
Public attributes
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_qt.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_qt.py 2008-07-24 08:50:43 UTC (rev 5830)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_qt.py 2008-07-24 10:02:13 UTC (rev 5831)
@@ -177,6 +177,14 @@
def flush_events(self):
qt.qApp.processEvents()
+ def start_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.start_event_loop_default(self,*args,**kwargs)
+ start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__
+
+ def stop_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.stop_event_loop_default(self,*args,**kwargs)
+ stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__
+
class FigureManagerQT( FigureManagerBase ):
"""
Public attributes
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_qt4.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_qt4.py 2008-07-24 08:50:43 UTC (rev 5830)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_qt4.py 2008-07-24 10:02:13 UTC (rev 5831)
@@ -181,6 +181,14 @@
def flush_events(self):
Qt.qApp.processEvents()
+ def start_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.start_event_loop_default(self,*args,**kwargs)
+ start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__
+
+ def stop_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.stop_event_loop_default(self,*args,**kwargs)
+ stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__
+
class FigureManagerQT( FigureManagerBase ):
"""
Public attributes
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_tkagg.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_tkagg.py 2008-07-24 08:50:43 UTC (rev 5830)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_tkagg.py 2008-07-24 10:02:13 UTC (rev 5831)
@@ -287,6 +287,14 @@
def flush_events(self):
self._master.update()
+ def start_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.start_event_loop_default(self,*args,**kwargs)
+ start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__
+
+ def stop_event_loop(self,*args,**kwargs):
+ FigureCanvasBase.stop_event_loop_default(self,*args,**kwargs)
+ stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__
+
class FigureManagerTkAgg(FigureManagerBase):
"""
Public attributes
Modified: trunk/matplotlib/lib/matplotlib/backends/backend_wx.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2008-07-24 08:50:43 UTC (rev 5830)
+++ trunk/matplotlib/lib/matplotlib/backends/backend_wx.py 2008-07-24 10:02:13 UTC (rev 5831)
@@ -1185,7 +1185,57 @@
if figManager is not None:
figManager.canvas.draw()
+ def start_event_loop(self, timeout=0):
+ """
+ Start an event loop. This is used to start a blocking event
+ loop so that interactive functions, such as ginput and
+ waitforbuttonpress, can wait for events. This should not be
+ confused with the main GUI event loop, which is always running
+ and has nothing to do with this.
+ Call signature::
+
+ start_event_loop(self,timeout=0)
+
+ This call blocks until a callback function triggers
+ stop_event_loop() or *timeout* is reached. If *timeout* is
+ <=0, never timeout.
+ """
+ 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 an event loop. This is used to stop a blocking event
+ loop so that interactive functions, such as ginput and
+ waitforbuttonpress, can wait for events.
+
+ Call signature::
+
+ stop_event_loop_default(self)
+ """
+ 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)
+
def show():
"""
Current implementation assumes that matplotlib is executed in a PyCrust
Modified: trunk/matplotlib/lib/matplotlib/blocking_input.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/blocking_input.py 2008-07-24 08:50:43 UTC (rev 5830)
+++ trunk/matplotlib/lib/matplotlib/blocking_input.py 2008-07-24 10:02:13 UTC (rev 5831)
@@ -50,7 +50,7 @@
# Check if we have enough events already
if len(self.events) >= self.n and self.n > 0:
- self.done = True
+ self.fig.canvas.stop_event_loop()
def post_event(self):
"""For baseclass, do nothing but collect events"""
@@ -90,7 +90,6 @@
self.n = n
self.events = []
- self.done = False
self.callbacks = []
# Ensure that the figure is shown
@@ -101,17 +100,8 @@
self.callbacks.append( self.fig.canvas.mpl_connect(n, self.on_event) )
try:
- # 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 "Timeout reached";
- break;
+ # Start event loop
+ self.fig.canvas.start_event_loop(timeout=timeout)
finally: # Run even on exception like ctrl-c
# Disconnect the callbacks
self.cleanup()
@@ -175,7 +165,7 @@
# consistent with matlab and sometimes quite useful, but will
# require the user to test how many points were actually
# returned before using data.
- self.done = True
+ self.fig.canvas.stop_event_loop()
def button3( self, event ):
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <dmk...@us...> - 2008-07-24 08:50:47
|
Revision: 5830
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5830&view=rev
Author: dmkaplan
Date: 2008-07-24 08:50:43 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
Committing rewrite of clabel inlining and label rotation code. Also, renaming
ContourLabeler attributes to something like .labelAttribute. A few of the old
attribute names have been maintained (in addition to new versions) for
backward compatibility, but these should be remove in +1 releases.
Added appropriate comments to CHANGELOG and API_CHANGES.
Modified Paths:
--------------
trunk/matplotlib/API_CHANGES
trunk/matplotlib/CHANGELOG
trunk/matplotlib/lib/matplotlib/blocking_input.py
trunk/matplotlib/lib/matplotlib/contour.py
Modified: trunk/matplotlib/API_CHANGES
===================================================================
--- trunk/matplotlib/API_CHANGES 2008-07-24 08:06:45 UTC (rev 5829)
+++ trunk/matplotlib/API_CHANGES 2008-07-24 08:50:43 UTC (rev 5830)
@@ -8,6 +8,12 @@
Axes.patch, Axes.axesFrame renamed Axes.frame, Axes.get_frame, which
returns Axes.patch, is deprecated. Examples and users guide updated
+* Changes in the ContourLabeler attributes (clabel function) so that they
+ all have a form like .labelAttribute. The three attributes that are most
+ likely to be used by end users, .cl, .cl_xy and .cl_cvalues have been
+ maintained for the moment (in addition to their renamed versions), but they
+ are depricated and will eventually be removed.
+
Changes for 0.98.1
==================
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-07-24 08:06:45 UTC (rev 5829)
+++ trunk/matplotlib/CHANGELOG 2008-07-24 08:50:43 UTC (rev 5830)
@@ -1,3 +1,6 @@
+2008-07-24 Rewrite of a significant portion of the clabel code (class
+ ContourLabeler) to improve inlining. - DMK
+
2008-07-22 Added Barbs polygon collection (similar to Quiver) for plotting
wind barbs. Added corresponding helpers to Axes and pyplot as
well. (examples/pylab_examples/barb_demo.py shows it off.) - RMM
@@ -4,7 +7,7 @@
2008-07-21 Added scikits.delaunay as matplotlib.delaunay. Added griddata
function in matplotlib.mlab, with example (griddata_demo.py) in
- pylab_examples. griddata function will use mpl_toolkits._natgrid
+ pylab_examples. griddata function will use mpl_toolkits._natgrid
if installed (haven't yet created the toolkit). - JSW
2008-07-21 Re-introduced offset_copy that works in the context of the
Modified: trunk/matplotlib/lib/matplotlib/blocking_input.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/blocking_input.py 2008-07-24 08:06:45 UTC (rev 5829)
+++ trunk/matplotlib/lib/matplotlib/blocking_input.py 2008-07-24 08:50:43 UTC (rev 5830)
@@ -19,8 +19,9 @@
import time
import numpy as np
+
from matplotlib import path, verbose
-from cbook import is_sequence_of_strings
+from matplotlib.cbook import is_sequence_of_strings
class BlockingInput(object):
"""
@@ -267,47 +268,39 @@
if event.inaxes == cs.ax:
conmin,segmin,imin,xmin,ymin = cs.find_nearest_contour(
- event.x, event.y, cs.label_indices)[:5]
+ event.x, event.y, cs.labelIndiceList)[:5]
# Get index of nearest level in subset of levels used for labeling
- lmin = cs.label_indices.index(conmin)
+ lmin = cs.labelIndiceList.index(conmin)
+ # Coordinates of contour
paths = cs.collections[conmin].get_paths()
lc = paths[segmin].vertices
- # Figure out label rotation. This is very cludgy.
- # Ideally, there would be one method in ContourLabeler
- # that would figure out the best rotation for a label at a
- # point, but the way automatic label rotation is done is
- # quite mysterious to me and doesn't seem easy to
- # generalize to non-automatic label placement. The method
- # used below is not very robust! It basically looks one
- # point before and one point after label location on
- # contour and takes mean of angles of two vectors formed.
- # This produces "acceptable" results, but not nearly as
- # nice as automatic method.
- ll = lc[max(0,imin-1):imin+2] # Get points around point
- dd = np.diff(ll,axis=0)
- rotation = np.mean( np.arctan2(dd[:,1], dd[:,0]) ) * 180 / np.pi
- if rotation > 90:
- rotation = rotation -180
- if rotation < -90:
- rotation = 180 + rotation
+ # In pixel/screen space
+ slc = cs.ax.transData.transform(lc)
- cs.add_label(xmin,ymin,rotation,cs.label_levels[lmin],
- cs.label_cvalues[lmin])
+ # Get label width for rotating labels and breaking contours
+ lw = cs.get_label_width(cs.labelLevelList[lmin],
+ cs.labelFmt, cs.labelFontSizeList[lmin])
+ # Figure out label rotation.
+ rotation,nlc = cs.calc_label_rot_and_inline(
+ slc, imin, lw, lc if self.inline else [],
+ self.inline_spacing )
+
+ cs.add_label(xmin,ymin,rotation,cs.labelLevelList[lmin],
+ cs.labelCValueList[lmin])
+
if self.inline:
- # Get label width for breaking contours
- lw = cs.get_label_width(cs.label_levels[lmin],
- cs.fmt, cs.fslist[lmin])
- # Break contour
- new=cs.break_linecontour(lc,rotation,lw,imin)
- if len(new[0]):
- paths[segmin] = path.Path(new[0])
- if len(new[1]):
- paths.extend([path.Path(new[1])])
+ # Remove old, not looping over paths so we can do this up front
+ paths.pop(segmin)
+ # Add paths if not empty or single point
+ for n in nlc:
+ if len(n)>1:
+ paths.append( path.Path(n) )
+
self.fig.canvas.draw()
else: # Remove event if not valid
BlockingInput.pop(self)
@@ -320,14 +313,21 @@
broken contour - once humpty-dumpty is broken, he can't be put
back together. In inline mode, this does nothing.
"""
+ # Remove this last event - not too important for clabel use
+ # since clabel normally doesn't have a maximum number of
+ # events, but best for cleanliness sake.
+ BlockingInput.pop(self)
+
if self.inline:
pass
else:
self.cs.pop_label()
self.cs.ax.figure.canvas.draw()
- def __call__(self,inline,n=-1,timeout=-1):
+ def __call__(self,inline,inline_spacing=5,n=-1,timeout=-1):
self.inline=inline
+ self.inline_spacing=inline_spacing
+
BlockingMouseInput.__call__(self,n=n,timeout=timeout,
show_clicks=False)
Modified: trunk/matplotlib/lib/matplotlib/contour.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/contour.py 2008-07-24 08:06:45 UTC (rev 5829)
+++ trunk/matplotlib/lib/matplotlib/contour.py 2008-07-24 08:50:43 UTC (rev 5830)
@@ -69,6 +69,12 @@
controls whether the underlying contour is removed or
not. Default is *True*.
+ *inline_spacing*:
+ space in pixels to leave on each side of label when
+ placing inline. Defaults to 5. This spacing will be
+ exact for labels at locations where the contour is
+ straight, less so for labels on curved contours.
+
*fmt*:
a format string for the label. Default is '%1.3f'
Alternatively, this can be a dictionary matching contour
@@ -108,11 +114,12 @@
fontsize = kwargs.get('fontsize', None)
inline = kwargs.get('inline', 1)
- self.fmt = kwargs.get('fmt', '%1.3f')
+ inline_spacing = kwargs.get('inline_spacing', 5)
+ self.labelFmt = kwargs.get('fmt', '%1.3f')
_colors = kwargs.get('colors', None)
# Detect if manual selection is desired and remove from argument list
- self.manual_select=kwargs.get('manual',False)
+ self.labelManual=kwargs.get('manual',False)
if len(args) == 0:
levels = self.levels
@@ -131,52 +138,59 @@
raise ValueError(msg)
else:
raise TypeError("Illegal arguments to clabel, see help(clabel)")
- self.label_levels = levels
- self.label_indices = indices
+ self.labelLevelList = levels
+ self.labelIndiceList = indices
- self.fp = font_manager.FontProperties()
+ self.labelFontProps = font_manager.FontProperties()
if fontsize == None:
- font_size = int(self.fp.get_size_in_points())
+ font_size = int(self.labelFontProps.get_size_in_points())
else:
if type(fontsize) not in [int, float, str]:
raise TypeError("Font size must be an integer number.")
# Can't it be floating point, as indicated in line above?
else:
if type(fontsize) == str:
- font_size = int(self.fp.get_size_in_points())
+ font_size = int(self.labelFontProps.get_size_in_points())
else:
- self.fp.set_size(fontsize)
+ self.labelFontProps.set_size(fontsize)
font_size = fontsize
- self.fslist = [font_size] * len(levels)
+ self.labelFontSizeList = [font_size] * len(levels)
if _colors == None:
- self.label_mappable = self
- self.label_cvalues = np.take(self.cvalues, self.label_indices)
+ self.labelMappable = self
+ self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
else:
- cmap = colors.ListedColormap(_colors, N=len(self.label_levels))
- self.label_cvalues = range(len(self.label_levels))
- self.label_mappable = cm.ScalarMappable(cmap = cmap,
- norm = colors.NoNorm())
+ cmap = colors.ListedColormap(_colors, N=len(self.labelLevelList))
+ self.labelCValueList = range(len(self.labelLevelList))
+ self.labelMappable = cm.ScalarMappable(cmap = cmap,
+ norm = colors.NoNorm())
- #self.cl = [] # Initialized in ContourSet.__init__
- #self.cl_cvalues = [] # same
- self.cl_xy = []
+ #self.labelTexts = [] # Initialized in ContourSet.__init__
+ #self.labelCValues = [] # same
+ self.labelXYs = []
- if self.manual_select:
+ if self.labelManual:
print 'Select label locations manually using first mouse button.'
print 'End manual selection with second mouse button.'
if not inline:
print 'Remove last label by clicking third mouse button.'
blocking_contour_labeler = BlockingContourLabeler(self)
- blocking_contour_labeler(inline)
+ blocking_contour_labeler(inline,inline_spacing)
else:
- self.labels(inline)
+ self.labels(inline,inline_spacing)
- self.label_list = cbook.silent_list('text.Text', self.cl)
- return self.label_list
+ # Hold on to some old attribute names. These are depricated and will
+ # be moved in the near future (sometime after 2008-08-01), but keeping
+ # for now for backwards compatibility
+ self.cl = self.labelTexts
+ self.cl_xy = self.labelXYs
+ self.cl_cvalues = self.labelCValues
+ self.labelTextsList = cbook.silent_list('text.Text', self.labelTexts)
+ return self.labelTextsList
+
def print_label(self, linecontour,labelwidth):
"if contours are too short, don't plot a label"
lcsize = len(linecontour)
@@ -196,9 +210,9 @@
def too_close(self, x,y, lw):
"if there's a label already nearby, find a better place"
- if self.cl_xy != []:
+ if self.labelXYs != []:
dist = [np.sqrt((x-loc[0]) ** 2 + (y-loc[1]) ** 2)
- for loc in self.cl_xy]
+ for loc in self.labelXYs]
for d in dist:
if d < 1.2*lw:
return 1
@@ -237,12 +251,35 @@
return lw
+ def get_real_label_width( self, lev, fmt, fsize ):
+ """
+ This computes actual onscreen label width.
+ This uses some black magic to determine onscreen extent of non-drawn
+ label. This magic may not be very robust.
+ """
+ # Find middle of axes
+ xx = np.mean( np.asarray(self.ax.axis()).reshape(2,2), axis=1 )
+ # Temporarily create text object
+ t = text.Text( xx[0], xx[1] )
+ self.set_label_props( t, self.get_text(lev,fmt), 'k' )
+
+ # Some black magic to get onscreen extent
+ # NOTE: This will only work for already drawn figures, as the canvas
+ # does not have a renderer otherwise. This is the reason this function
+ # can't be integrated into the rest of the code.
+ bbox = t.get_window_extent(renderer=self.ax.figure.canvas.renderer)
+
+ # difference in pixel extent of image
+ lw = np.diff(bbox.corners()[0::2,0])[0]
+
+ return lw
+
def set_label_props(self, label, text, color):
"set the label properties - color, fontsize, text"
label.set_text(text)
label.set_color(color)
- label.set_fontproperties(self.fp)
+ label.set_fontproperties(self.labelFontProps)
label.set_clip_box(self.ax.bbox)
def get_text(self, lev, fmt):
@@ -255,85 +292,6 @@
else:
return fmt%lev
- def break_linecontour(self, linecontour, rot, labelwidth, ind):
- "break a contour in two contours at the location of the label"
- lcsize = len(linecontour)
- hlw = int(labelwidth/2)
-
- #length of label in screen coords
- ylabel = abs(hlw * np.sin(rot*np.pi/180))
- xlabel = abs(hlw * np.cos(rot*np.pi/180))
-
- trans = self.ax.transData
-
- slc = trans.transform(linecontour)
- x,y = slc[ind]
- xx=slc[:,0].copy()
- yy=slc[:,1].copy()
-
- #indices which are under the label
- inds, = np.nonzero(((xx < x+xlabel) & (xx > x-xlabel)) &
- ((yy < y+ylabel) & (yy > y-ylabel)))
-
- if len(inds) >0:
- #if the label happens to be over the beginning of the
- #contour, the entire contour is removed, i.e.
- #indices to be removed are
- #inds= [0,1,2,3,305,306,307]
- #should rewrite this in a better way
- linds, = np.nonzero(inds[1:]- inds[:-1] != 1)
- if inds[0] == 0 and len(linds) != 0:
- ii = inds[linds[0]]
- lc1 =linecontour[ii+1:inds[ii+1]]
- lc2 = []
-
- else:
- lc1=linecontour[:inds[0]]
- lc2= linecontour[inds[-1]+1:]
-
- else:
- lc1=linecontour[:ind]
- lc2 = linecontour[ind+1:]
-
-
- if rot <0:
- new_x1, new_y1 = x-xlabel, y+ylabel
- new_x2, new_y2 = x+xlabel, y-ylabel
- else:
- new_x1, new_y1 = x-xlabel, y-ylabel
- new_x2, new_y2 = x+xlabel, y+ylabel
-
- inverse = trans.inverted()
- new_x1d, new_y1d = inverse.transform_point((new_x1, new_y1))
- new_x2d, new_y2d = inverse.transform_point((new_x2, new_y2))
- new_xy1 = np.array(((new_x1d, new_y1d),))
- new_xy2 = np.array(((new_x2d, new_y2d),))
-
-
- if rot > 0:
- if (len(lc1) > 0 and (lc1[-1][0] <= new_x1d)
- and (lc1[-1][1] <= new_y1d)):
- lc1 = np.concatenate((lc1, new_xy1))
- #lc1.append((new_x1d, new_y1d))
-
- if (len(lc2) > 0 and (lc2[0][0] >= new_x2d)
- and (lc2[0][1] >= new_y2d)):
- lc2 = np.concatenate((new_xy2, lc2))
- #lc2.insert(0, (new_x2d, new_y2d))
- else:
- if (len(lc1) > 0 and ((lc1[-1][0] <= new_x1d)
- and (lc1[-1][1] >= new_y1d))):
- lc1 = np.concatenate((lc1, new_xy1))
- #lc1.append((new_x1d, new_y1d))
-
- if (len(lc2) > 0 and ((lc2[0][0] >= new_x2d)
- and (lc2[0][1] <= new_y2d))):
- lc2 = np.concatenate((new_xy2, lc2))
- #lc2.insert(0, (new_x2d, new_y2d))
-
- return [lc1,lc2]
-
-
def locate_label(self, linecontour, labelwidth):
"""find a good place to plot a label (relatively flat
part of the contour) and the angle of rotation for the
@@ -362,12 +320,6 @@
dist = np.add.reduce(([(abs(s)[i]/L[i]) for i in range(xsize)]),-1)
x,y,ind = self.get_label_coords(dist, XX, YY, ysize, labelwidth)
#print 'ind, x, y', ind, x, y
- angle = np.arctan2(ylast - yfirst, xlast - xfirst).ravel()
- rotation = angle[ind]*180/np.pi
- if rotation > 90:
- rotation = rotation -180
- if rotation < -90:
- rotation = 180 + rotation
# There must be a more efficient way...
lc = [tuple(l) for l in linecontour]
@@ -375,72 +327,181 @@
#print 'dind', dind
#dind = list(linecontour).index((x,y))
- return x,y, rotation, dind
+ return x, y, dind
+ def calc_label_rot_and_inline( self, slc, ind, lw, lc=[], spacing=5 ):
+ """
+ This function calculates the appropriate label rotation given
+ the linecontour coordinates in screen units, the index of the
+ label location and the label width.
+
+ It will also break contour and calculate inlining if *lc* is
+ not empty. *spacing* is the space around the label in pixels
+ to leave empty.
+
+ Do both of these tasks at once to avoid calling cbook.path_length
+ multiple times, which is relatively costly.
+
+ The method used here involves calculating the path length
+ along the contour in pixel coordinates and then looking
+ approximately label width / 2 away from central point to
+ determine rotation and then to break contour if desired.
+ """
+
+ # Half the label width
+ hlw = lw/2.0
+
+ # Check if closed and, if so, rotate contour so label is at edge
+ closed = cbook.is_closed_polygon(slc)
+ if closed:
+ slc = np.r_[ slc[ind:-1], slc[:ind+1] ]
+
+ if len(lc): # Rotate lc also if not empty
+ lc = np.r_[ lc[ind:-1], lc[:ind+1] ]
+
+ ind = 0
+
+ # Path length in pixel space
+ pl = cbook.path_length(slc)
+ pl = pl-pl[ind]
+
+ # Use linear interpolation to get points around label
+ xi = np.array( [ -hlw, hlw ] )
+ if closed: # Look at end also for closed contours
+ dp = np.array([pl[-1],0])
+ else:
+ dp = np.zeros_like(xi)
+
+ ll = cbook.less_simple_linear_interpolation( pl, slc, dp+xi,
+ extrap=True )
+
+ # get vector in pixel space coordinates from one point to other
+ dd = np.diff( ll, axis=0 ).ravel()
+
+ # Get angle of vector - must be calculated in pixel space for
+ # text rotation to work correctly
+ if np.all(dd==0): # Must deal with case of zero length label
+ rotation = 0.0
+ else:
+ rotation = np.arctan2(dd[1], dd[0]) * 180.0 / np.pi
+
+ # Fix angle so text is never upside-down
+ if rotation > 90:
+ rotation = rotation - 180.0
+ if rotation < -90:
+ rotation = 180.0 + rotation
+
+ # Break contour if desired
+ nlc = []
+ if len(lc):
+ # Expand range by spacing
+ xi = dp + xi + np.array([-spacing,spacing])
+
+ # Get indices near points of interest
+ I = cbook.less_simple_linear_interpolation(
+ pl, np.arange(len(pl)), xi, extrap=False )
+
+ # If those indices aren't beyond contour edge, find x,y
+ if (not np.isnan(I[0])) and int(I[0])<>I[0]:
+ xy1 = cbook.less_simple_linear_interpolation(
+ pl, lc, [ xi[0] ] )
+
+ if (not np.isnan(I[1])) and int(I[1])<>I[1]:
+ xy2 = cbook.less_simple_linear_interpolation(
+ pl, lc, [ xi[1] ] )
+
+ # Make integer
+ I = [ np.floor(I[0]), np.ceil(I[1]) ]
+
+ # Actually break contours
+ if closed:
+ # This will remove contour if shorter than label
+ if np.all(~np.isnan(I)):
+ nlc.append( np.r_[ xy2, lc[I[1]:I[0]+1], xy1 ] )
+ else:
+ # These will remove pieces of contour if they have length zero
+ if not np.isnan(I[0]):
+ nlc.append( np.r_[ lc[:I[0]+1], xy1 ] )
+ if not np.isnan(I[1]):
+ nlc.append( np.r_[ xy2, lc[I[1]:] ] )
+
+ # The current implementation removes contours completely
+ # covered by labels. Uncomment line below to keep
+ # original contour if this is the preferred behavoir.
+ #if not len(nlc): nlc = [ lc ]
+
+ return (rotation,nlc)
+
+
def add_label(self,x,y,rotation,lev,cvalue):
dx,dy = self.ax.transData.inverted().transform_point((x,y))
t = text.Text(dx, dy, rotation = rotation,
horizontalalignment='center',
verticalalignment='center')
- color = self.label_mappable.to_rgba(cvalue,alpha=self.alpha)
+ color = self.labelMappable.to_rgba(cvalue,alpha=self.alpha)
- _text = self.get_text(lev,self.fmt)
+ _text = self.get_text(lev,self.labelFmt)
self.set_label_props(t, _text, color)
- self.cl.append(t)
- self.cl_cvalues.append(cvalue)
- self.cl_xy.append((x,y))
+ self.labelTexts.append(t)
+ self.labelCValues.append(cvalue)
+ self.labelXYs.append((x,y))
# Add label to plot here - useful for manual mode label selection
self.ax.add_artist(t)
def pop_label(self,index=-1):
'''Defaults to removing last label, but any index can be supplied'''
- self.cl_cvalues.pop(index)
- t = self.cl.pop(index)
+ self.labelCValues.pop(index)
+ t = self.labelTexts.pop(index)
t.remove()
- def labels(self, inline):
+ def labels(self, inline, inline_spacing):
trans = self.ax.transData # A bit of shorthand
for icon, lev, fsize, cvalue in zip(
- self.label_indices, self.label_levels, self.fslist,
- self.label_cvalues ):
+ self.labelIndiceList, self.labelLevelList, self.labelFontSizeList,
+ self.labelCValueList ):
con = self.collections[icon]
- lw = self.get_label_width(lev, self.fmt, fsize)
+ lw = self.get_label_width(lev, self.labelFmt, fsize)
additions = []
paths = con.get_paths()
for segNum, linepath in enumerate(paths):
- linecontour = linepath.vertices
- # for closed contours add one more point to
- # avoid division by zero
- if np.all(linecontour[0] == linecontour[-1]):
- linecontour = np.concatenate((linecontour,
- linecontour[1][np.newaxis,:]))
- #linecontour.append(linecontour[1])
- # transfer all data points to screen coordinates
- slc = trans.transform(linecontour)
+ lc = linepath.vertices # Line contour
+ slc0 = trans.transform(lc) # Line contour in screen coords
+
+ # For closed polygons, add extra point to avoid division by
+ # zero in print_label and locate_label. Other than these
+ # functions, this is not necessary and should probably be
+ # eventually removed.
+ if cbook.is_closed_polygon( lc ):
+ slc = np.r_[ slc0, slc0[1:2,:] ]
+ else:
+ slc = slc0
+
if self.print_label(slc,lw):
- x,y, rotation, ind = self.locate_label(slc, lw)
+ x,y,ind = self.locate_label(slc, lw)
+ rotation,new=self.calc_label_rot_and_inline(
+ slc0, ind, lw, lc if inline else [],
+ inline_spacing )
+
# Actually add the label
self.add_label(x,y,rotation,lev,cvalue)
- # Use break_linecontour to split contours for inlining
+ # If inline, add new contours
if inline:
- new = self.break_linecontour(linecontour, rotation,
- lw, ind)
- if len(new[0]):
- paths[segNum] = path.Path(new[0])
- if len(new[1]):
- additions.append(path.Path(new[1]))
+ for n in new:
+ # Add path if not empty or single point
+ if len(n)>1: additions.append( path.Path(n) )
- # After looping over all segments on a contour, append
- # new paths to existing
- paths.extend(additions)
+ # After looping over all segments on a contour, remove old
+ # paths and add new ones if inlining
+ if inline:
+ del paths[:]
+ paths.extend(additions)
-
class ContourSet(cm.ScalarMappable, ContourLabeler):
"""
Create and store a set of contour lines or filled regions.
@@ -512,8 +573,8 @@
else:
self.collections = cbook.silent_list('collections.LineCollection')
# label lists must be initialized here
- self.cl = []
- self.cl_cvalues = []
+ self.labelTexts = []
+ self.labelCValues = []
kw = {'cmap': cmap}
if norm is not None:
@@ -574,9 +635,9 @@
for color, collection in zip(tcolors, self.collections):
collection.set_alpha(self.alpha)
collection.set_color(color)
- for label, cv in zip(self.cl, self.cl_cvalues):
+ for label, cv in zip(self.labelTexts, self.labelCValues):
label.set_alpha(self.alpha)
- label.set_color(self.label_mappable.to_rgba(cv))
+ label.set_color(self.labelMappable.to_rgba(cv))
# add label colors
cm.ScalarMappable.changed(self)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <dmk...@us...> - 2008-07-24 08:06:50
|
Revision: 5829
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5829&view=rev
Author: dmkaplan
Date: 2008-07-24 08:06:45 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
Slight documentation changes.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/cbook.py
Modified: trunk/matplotlib/lib/matplotlib/cbook.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cbook.py 2008-07-24 07:59:18 UTC (rev 5828)
+++ trunk/matplotlib/lib/matplotlib/cbook.py 2008-07-24 08:06:45 UTC (rev 5829)
@@ -1159,10 +1159,15 @@
def less_simple_linear_interpolation( x, y, xi, extrap=False ):
"""
This function provides simple (but somewhat less so than
- simple_linear_interpolation) linear interpolation. This is very
- inefficient linear interpolation meant to be used only for a small
- number of points in relatively non-intensive use cases.
+ simple_linear_interpolation) linear interpolation.
+ simple_linear_interpolation will give a list of point between a
+ start and an end, while this does true linear interpolation at an
+ arbitrary set of points.
+ This is very inefficient linear interpolation meant to be used
+ only for a small number of points in relatively non-intensive use
+ cases.
+
Call signature::
yi = less_simple_linear_interpolation(x,y,xi)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <dmk...@us...> - 2008-07-24 07:59:20
|
Revision: 5828
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5828&view=rev
Author: dmkaplan
Date: 2008-07-24 07:59:18 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
Changes to documentation of norm and orth functions and deprecation
warning for norm in favor of numpy version.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-07-24 02:28:20 UTC (rev 5827)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-07-24 07:59:18 UTC (rev 5828)
@@ -1816,25 +1816,25 @@
def norm(x,y=2):
"""
- Norm of a matrix or a vector according to Matlab.
- The description is taken from Matlab:
+ This function is deprecated - use numpy.linalg.norm instead.
- For matrices...
- NORM(X) is the largest singular value of X, max(svd(X)).
- NORM(X,2) is the same as NORM(X).
- NORM(X,1) is the 1-norm of X, the largest column sum,
- = max(sum(abs((X)))).
- NORM(X,inf) is the infinity norm of X, the largest row sum,
- = max(sum(abs((X')))).
- NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))).
- NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'.
+ Norm of a matrix or a vector. Functions similar to the Matlab (TM)
+ function of the same name.
- For vectors...
- NORM(V,P) = sum(abs(V).^P)^(1/P).
- NORM(V) = norm(V,2).
- NORM(V,inf) = max(abs(V)).
- NORM(V,-inf) = min(abs(V)).
+ Call signature::
+
+ norm(x,y=2)
+
+ This function behaves differently for vectors and matrices. For vectors,
+ it returns the y'th norm of x (i.e. (sum(abs(x)**y))**(1.0/y).
+
+ For matrices, if y=2, then it returns the largest singular value
+ of X, namely max(linalg.svd(x)). If y=1, returns the largest
+ column sum of x (i.e., max(sum(abs(x),axis=0)) ). If y=inf,
+ returns the largest row sum. If y='fro', returns the Frobenius
+ norm, sqrt(sum(diag(dot(x.transpose(),x)))).
"""
+ warnings.warn( "Use numpy.linalg.norm instead", DeprecationWarning )
x = np.asarray(x)
if x.ndim == 2:
@@ -1862,13 +1862,16 @@
def orth(A):
"""
- Orthogonalization procedure by Matlab.
- The description is taken from its help:
+ Orthogonalization procedure similar to Matlab (TM) function of the same
+ name.
- Q = ORTH(A) is an orthonormal basis for the range of A.
- That is, Q'*Q = I, the columns of Q span the same space as
- the columns of A, and the number of columns of Q is the
- rank of A.
+ Call signature::
+
+ Q = orth(A)
+
+ Returns an orthonormal basis with the range of A. Q is an orthonormal
+ matrix (i.e., dot( Q.transpose(), Q ) is an identity matrix) and the
+ columns of Q span the same space as the columns of A.
"""
A = np.asarray(A)
@@ -2086,9 +2089,9 @@
join record arrays r1 and r2 on key; key is a tuple of field
names. If r1 and r2 have equal values on all the keys in the key
tuple, then their fields will be merged into a new record array
- containing the intersection of the fields of r1 and r2.
+ containing the intersection of the fields of r1 and r2.
- r1 (also r2) must not have any duplicate keys.
+ r1 (also r2) must not have any duplicate keys.
The jointype keyword can be 'inner', 'outer', 'leftouter'.
To do a rightouter join just reverse r1 and r2.
@@ -2702,8 +2705,8 @@
griddata interpolates this surface at the points specified by (xi,yi)
to produce zi. xi and yi must describe a regular grid, can be
either 1D or 2D, but must be monotonically increasing.
-
- A masked array is returned if any grid points are outside convex
+
+ A masked array is returned if any grid points are outside convex
hull defined by input data (no extrapolation is done).
Uses natural neighbor interpolation based on Delaunay triangulation.
@@ -2712,7 +2715,7 @@
package is known to fail on some nearly pathological cases. For
this reason, a separate toolkit (mpl_tookits.natgrid) has been created
that provides a more robust algorithm fof triangulation and interpolation.
- This toolkit is based on the NCAR natgrid library, which contains code
+ This toolkit is based on the NCAR natgrid library, which contains code
that is not redistributable under a BSD-compatible license. When installed,
this function will use the mpl_toolkits.natgrid algorithm, otherwise it
will use the built-in matplotlib.delaunay package.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-07-24 02:28:22
|
Revision: 5827
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5827&view=rev
Author: ryanmay
Date: 2008-07-24 02:28:20 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
Update barb_demo.py to exercise more of the possible parameters for wind barb plots. Replace some confusing code for passing in the data with more explicit arrays. Also, make the data array for the arbitrary grid non-square so that proper dimensioning can be seen. Remove mysterious windows-styles line endings.
Modified Paths:
--------------
trunk/matplotlib/examples/pylab_examples/barb_demo.py
Modified: trunk/matplotlib/examples/pylab_examples/barb_demo.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/barb_demo.py 2008-07-24 02:02:01 UTC (rev 5826)
+++ trunk/matplotlib/examples/pylab_examples/barb_demo.py 2008-07-24 02:28:20 UTC (rev 5827)
@@ -3,31 +3,39 @@
'''
import matplotlib.pyplot as plt
import numpy as np
-
-x = np.linspace(-5, 5, 5)
-X,Y = np.meshgrid(x, x)
-U, V = 12*X, 12*Y
-
-data = [(-1.5,.5,-6,-6),
- (1,-1,-46,46),
- (-3,-1,11,-11),
- (1,1.5,80,80)]
-
-#Default parameters for arbitrary set of vectors
-ax = plt.subplot(2,2,1)
-ax.barbs(*zip(*data))
-
-#Default parameters, uniform grid
-ax = plt.subplot(2,2,2)
-ax.barbs(X, Y, U, V)
-
-#Change parameters for arbitrary set of vectors
-ax = plt.subplot(2,2,3)
-ax.barbs(flagcolor='r', barbcolor=['b','g'], barb_increments=dict(half=10,
- full=20, flag=100), *zip(*data))
-
-#Showing colormapping with uniform grid.
-ax = plt.subplot(2,2,4)
-ax.barbs(X, Y, U, V, np.sqrt(U*U + V*V), fill_empty=True, rounding=False)
+x = np.linspace(-5, 5, 5)
+X,Y = np.meshgrid(x, x)
+U, V = 12*X, 12*Y
+
+data = [(-1.5, .5, -6, -6),
+ (1, -1, -46, 46),
+ (-3, -1, 11, -11),
+ (1, 1.5, 80, 80),
+ (0.5, 0.25, 25, 15),
+ (-1.5, -0.5, -5, 40)]
+
+data = np.array(data, dtype=[('x', np.float32), ('y', np.float32),
+ ('u', np.float32), ('v', np.float32)])
+
+#Default parameters, uniform grid
+ax = plt.subplot(2,2,1)
+ax.barbs(X, Y, U, V)
+
+#Arbitrary set of vectors, make them longer and change the pivot point
+#(point around which they're rotated) to be the middle
+ax = plt.subplot(2,2,2)
+ax.barbs(data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle')
+
+#Showing colormapping with uniform grid. Fill the circle for an empty barb,
+#don't round the values, and change some of the size parameters
+ax = plt.subplot(2,2,3)
+ax.barbs(X, Y, U, V, np.sqrt(U*U + V*V), fill_empty=True, rounding=False,
+ sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
+
+#Change colors as well as the increments for parts of the barbs
+ax = plt.subplot(2,2,4)
+ax.barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r',
+ barbcolor=['b','g'], barb_increments=dict(half=10, full=20, flag=100))
+
plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-07-24 02:02:04
|
Revision: 5826
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5826&view=rev
Author: jdh2358
Date: 2008-07-24 02:02:01 +0000 (Thu, 24 Jul 2008)
Log Message:
-----------
restored broken barb demo
Modified Paths:
--------------
trunk/matplotlib/examples/pylab_examples/barb_demo.py
Modified: trunk/matplotlib/examples/pylab_examples/barb_demo.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/barb_demo.py 2008-07-23 17:09:15 UTC (rev 5825)
+++ trunk/matplotlib/examples/pylab_examples/barb_demo.py 2008-07-24 02:02:01 UTC (rev 5826)
@@ -0,0 +1,33 @@
+'''
+Demonstration of wind barb plots
+'''
+import matplotlib.pyplot as plt
+import numpy as np
+
+x = np.linspace(-5, 5, 5)
+X,Y = np.meshgrid(x, x)
+U, V = 12*X, 12*Y
+
+data = [(-1.5,.5,-6,-6),
+ (1,-1,-46,46),
+ (-3,-1,11,-11),
+ (1,1.5,80,80)]
+
+#Default parameters for arbitrary set of vectors
+ax = plt.subplot(2,2,1)
+ax.barbs(*zip(*data))
+
+#Default parameters, uniform grid
+ax = plt.subplot(2,2,2)
+ax.barbs(X, Y, U, V)
+
+#Change parameters for arbitrary set of vectors
+ax = plt.subplot(2,2,3)
+ax.barbs(flagcolor='r', barbcolor=['b','g'], barb_increments=dict(half=10,
+ full=20, flag=100), *zip(*data))
+
+#Showing colormapping with uniform grid.
+ax = plt.subplot(2,2,4)
+ax.barbs(X, Y, U, V, np.sqrt(U*U + V*V), fill_empty=True, rounding=False)
+
+plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-07-23 17:09:18
|
Revision: 5825
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5825&view=rev
Author: jdh2358
Date: 2008-07-23 17:09:15 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
restored interactive_bk var to backends init -- ipython shell uses it
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/backends/__init__.py
Modified: trunk/matplotlib/lib/matplotlib/backends/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/backends/__init__.py 2008-07-23 14:18:41 UTC (rev 5824)
+++ trunk/matplotlib/lib/matplotlib/backends/__init__.py 2008-07-23 17:09:15 UTC (rev 5825)
@@ -1,6 +1,8 @@
import matplotlib
+# ipython relies on interactive_bk being defined here
+from matplotlib.rcsetup import interactive_bk
__all__ = ['backend','show','draw_if_interactive',
'new_figure_manager', 'backend_version']
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <dmk...@us...> - 2008-07-23 14:18:45
|
Revision: 5824
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5824&view=rev
Author: dmkaplan
Date: 2008-07-23 14:18:41 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
Fix to is_scalar plus additional functions in cbook.py:
less_simple_linear_interpolation
isvector
vector_lengths
distances_along_curve
path_length
is_closed_polygon
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/cbook.py
Modified: trunk/matplotlib/lib/matplotlib/cbook.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cbook.py 2008-07-23 13:28:32 UTC (rev 5823)
+++ trunk/matplotlib/lib/matplotlib/cbook.py 2008-07-23 14:18:41 UTC (rev 5824)
@@ -287,7 +287,7 @@
def is_scalar(obj):
'return true if *obj* is not string like and is not iterable'
- return not is_string_like(obj) or not iterable(obj)
+ return not is_string_like(obj) and not iterable(obj)
def is_numlike(obj):
'return true if *obj* looks like a number'
@@ -1156,6 +1156,46 @@
return result
+def less_simple_linear_interpolation( x, y, xi, extrap=False ):
+ """
+ This function provides simple (but somewhat less so than
+ simple_linear_interpolation) linear interpolation. This is very
+ inefficient linear interpolation meant to be used only for a small
+ number of points in relatively non-intensive use cases.
+
+ Call signature::
+
+ yi = less_simple_linear_interpolation(x,y,xi)
+ """
+ if is_scalar(xi): xi = [xi]
+
+ x = np.asarray(x)
+ y = np.asarray(y)
+ xi = np.asarray(xi)
+
+ s = list(y.shape)
+ s[0] = len(xi)
+ yi = np.tile( np.nan, s )
+
+ for ii,xx in enumerate(xi):
+ bb = x == xx
+ if np.any(bb):
+ jj, = np.nonzero(bb)
+ yi[ii] = y[jj[0]]
+ elif xx<x[0]:
+ if extrap:
+ yi[ii] = y[0]
+ elif xx>x[-1]:
+ if extrap:
+ yi[ii] = y[-1]
+ else:
+ jj, = np.nonzero(x<xx)
+ jj = max(jj)
+
+ yi[ii] = y[jj] + (xx-x[jj])/(x[jj+1]-x[jj]) * (y[jj+1]-y[jj])
+
+ return yi
+
def recursive_remove(path):
if os.path.isdir(path):
for fname in glob.glob(os.path.join(path, '*')) + glob.glob(os.path.join(path, '.*')):
@@ -1294,7 +1334,76 @@
ic1 = breakpoints
return np.concatenate((ic0[:, np.newaxis], ic1[:, np.newaxis]), axis=1)
+def isvector(X):
+ """
+ Like the Matlab (TM) function with the same name, returns true if
+ the supplied numpy array or matrix looks like a vector, meaning it
+ has a one non-singleton axis (i.e., it can have multiple axes, but
+ all must have length 1, except for one of them).
+ If you just want to see if the array has 1 axis, use X.ndim==1
+
+ Call signature::
+ isvector(X)
+ """
+ return np.prod(X.shape)==np.max(X.shape)
+
+def vector_lengths( X, P=2., axis=None ):
+ """
+ Finds the length of a set of vectors in n dimensions. This is
+ like the mlab.norm function for vectors, but has the ability to
+ work over a particular axis of the supplied array or matrix.
+
+ Call signature::
+
+ vector_lengths( X, P=2., axis=None )
+
+ Computes (sum((x_i)^P))^(1/P) for each {x_i} being the elements of X along
+ the given axis. If *axis* is *None*, compute over all elements of X.
+ """
+ X = np.asarray(X)
+ return (np.sum(X**(P),axis=axis))**(1./P)
+
+def distances_along_curve( X ):
+ """
+ Computes the distance between a set of successive points in N dimensions.
+
+ Call signature::
+
+ distances_along_curve(X)
+
+ where X is an MxN array or matrix. The distances between successive rows
+ is computed. Distance is the standard Euclidean distance.
+ """
+ X = np.diff( X, axis=0 )
+ return vector_lengths(X,axis=1)
+
+def path_length(X):
+ """
+ Computes the distance travelled along a polygonal curve in N dimensions.
+
+ Call signature::
+
+ path_length(X)
+
+ where X is an MxN array or matrix. Returns an array of length M consisting
+ of the distance along the curve at each point (i.e., the rows of X).
+ """
+ X = distances_along_curve(X)
+ return np.concatenate( (np.zeros(1), np.cumsum(X)) )
+
+def is_closed_polygon(X):
+ """
+ Tests whether first and last object in a sequence are the same. These are
+ presumably coordinates on a polygonal curve, in which case this function
+ tests if that curve is closed.
+
+ Call signature::
+
+ is_closed_polygon(X)
+ """
+ return np.all(X[0] == X[-1])
+
# a dict to cross-map linestyle arguments
_linestyles = [('-', 'solid'),
('--', 'dashed'),
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-07-23 13:28:34
|
Revision: 5823
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5823&view=rev
Author: jdh2358
Date: 2008-07-23 13:28:32 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
converted barb demo to unix new lines
Modified Paths:
--------------
trunk/matplotlib/examples/pylab_examples/barb_demo.py
Modified: trunk/matplotlib/examples/pylab_examples/barb_demo.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/barb_demo.py 2008-07-23 13:16:28 UTC (rev 5822)
+++ trunk/matplotlib/examples/pylab_examples/barb_demo.py 2008-07-23 13:28:32 UTC (rev 5823)
@@ -1,33 +0,0 @@
-'''
-Demonstration of wind barb plots
-'''
-import matplotlib.pyplot as plt
-import numpy as np
-
-x = np.linspace(-5, 5, 5)
-X,Y = np.meshgrid(x, x)
-U, V = 12*X, 12*Y
-
-data = [(-1.5,.5,-6,-6),
- (1,-1,-46,46),
- (-3,-1,11,-11),
- (1,1.5,80,80)]
-
-#Default parameters for arbitrary set of vectors
-ax = plt.subplot(2,2,1)
-ax.barbs(*zip(*data))
-
-#Default parameters, uniform grid
-ax = plt.subplot(2,2,2)
-ax.barbs(X, Y, U, V)
-
-#Change parameters for arbitrary set of vectors
-ax = plt.subplot(2,2,3)
-ax.barbs(flagcolor='r', barbcolor=['b','g'], barb_increments=dict(half=10,
- full=20, flag=100), *zip(*data))
-
-#Showing colormapping with uniform grid.
-ax = plt.subplot(2,2,4)
-ax.barbs(X, Y, U, V, np.sqrt(U*U + V*V), fill_empty=True, rounding=False)
-
-plt.show()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jd...@us...> - 2008-07-23 13:16:30
|
Revision: 5822
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5822&view=rev
Author: jdh2358
Date: 2008-07-23 13:16:28 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
fixed is_scalar -- good catch david
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/cbook.py
Modified: trunk/matplotlib/lib/matplotlib/cbook.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cbook.py 2008-07-23 12:34:26 UTC (rev 5821)
+++ trunk/matplotlib/lib/matplotlib/cbook.py 2008-07-23 13:16:28 UTC (rev 5822)
@@ -287,7 +287,7 @@
def is_scalar(obj):
'return true if *obj* is not string like and is not iterable'
- return is_string_like(obj) or not iterable(obj)
+ return not is_string_like(obj) or not iterable(obj)
def is_numlike(obj):
'return true if *obj* looks like a number'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-07-23 12:34:28
|
Revision: 5821
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5821&view=rev
Author: jswhit
Date: 2008-07-23 12:34:26 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
added barbs method
Modified Paths:
--------------
trunk/toolkits/basemap/Changelog
Modified: trunk/toolkits/basemap/Changelog
===================================================================
--- trunk/toolkits/basemap/Changelog 2008-07-23 12:32:48 UTC (rev 5820)
+++ trunk/toolkits/basemap/Changelog 2008-07-23 12:34:26 UTC (rev 5821)
@@ -1,4 +1,5 @@
version 0.99.1 (not yet released)
+ * added "barbs" method to draw wind barbs on the map.
* added "tissot" method for generating Tissot's indicatrix
(see example plot_tissot.py).
* fixed processing of coastlines for gnomonic projection.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-07-23 12:32:50
|
Revision: 5820
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5820&view=rev
Author: jswhit
Date: 2008-07-23 12:32:48 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
add barbs method, barbs example.
Modified Paths:
--------------
trunk/toolkits/basemap/MANIFEST.in
trunk/toolkits/basemap/examples/README
trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
Added Paths:
-----------
trunk/toolkits/basemap/examples/barb_demo.py
Modified: trunk/toolkits/basemap/MANIFEST.in
===================================================================
--- trunk/toolkits/basemap/MANIFEST.in 2008-07-23 03:08:41 UTC (rev 5819)
+++ trunk/toolkits/basemap/MANIFEST.in 2008-07-23 12:32:48 UTC (rev 5820)
@@ -39,6 +39,7 @@
include examples/contour_demo.py
include examples/customticks.py
include examples/quiver_demo.py
+include examples/barbs_demo.py
include examples/nytolondon.py
include examples/ortho_demo.py
include examples/geos_demo.py
Modified: trunk/toolkits/basemap/examples/README
===================================================================
--- trunk/toolkits/basemap/examples/README 2008-07-23 03:08:41 UTC (rev 5819)
+++ trunk/toolkits/basemap/examples/README 2008-07-23 12:32:48 UTC (rev 5820)
@@ -36,6 +36,8 @@
quiver_demo.py shows how to plot wind vectors on a map.
+barbs_demo.py shows how to plot wind barbs on a map.
+
randompoints.py demonstrates the use of scatter to plot randomly distributed
points on the earth.
Added: trunk/toolkits/basemap/examples/barb_demo.py
===================================================================
--- trunk/toolkits/basemap/examples/barb_demo.py (rev 0)
+++ trunk/toolkits/basemap/examples/barb_demo.py 2008-07-23 12:32:48 UTC (rev 5820)
@@ -0,0 +1,55 @@
+from mpl_toolkits.basemap import Basemap
+import numpy as np
+import matplotlib.pyplot as plt
+
+# read in data.
+file = open('fcover.dat','r')
+ul=[];vl=[];pl=[]
+nlons=73; nlats=73
+dellat = 2.5; dellon = 5.
+for line in file.readlines():
+ l = line.replace('\n','').split()
+ ul.append(float(l[0]))
+ vl.append(float(l[1]))
+ pl.append(float(l[2]))
+u = np.reshape(np.array(ul,np.float32),(nlats,nlons))
+v = np.reshape(np.array(vl,np.float32),(nlats,nlons))
+p = np.reshape(np.array(pl,np.float32),(nlats,nlons))
+lats1 = -90.+dellat*np.arange(nlats)
+lons1 = -180.+dellon*np.arange(nlons)
+lons, lats = np.meshgrid(lons1, lats1)
+# convert from mps to knots.
+u = 1.944*u; v = 1.944*v
+
+# plot barbs in map projection coordinates.
+
+# stereogrpaphic projection.
+m = Basemap(width=10000000,height=10000000,lon_0=-90,lat_0=45.,lat_ts=45,
+ resolution='l',projection='stere')
+x,y = m(lons,lats)
+# transform from spherical to map projection coordinates (rotation
+# and interpolation).
+nxv = 25; nyv = 25
+udat, vdat, xv, yv = m.transform_vector(u,v,lons1,lats1,nxv,nyv,returnxy=True)
+# create a figure, add an axes.
+fig=plt.figure(figsize=(8,8))
+ax = fig.add_axes([0.1,0.1,0.7,0.7])
+# plot color-filled contours over map
+levs = np.arange(960,1051,4)
+cs1 = m.contour(x,y,p,levs,colors='k',linewidths=0.5)
+cs2 = m.contourf(x,y,p,levs)
+# plot barbs.
+m.barbs(xv,yv,udat,vdat,length=6,barbcolor='k',flagcolor='r',linewidth=0.5)
+# plot colorbar for pressure
+cax = plt.axes([0.875, 0.1, 0.05, 0.7]) # setup colorbar axes.
+plt.colorbar(cax=cax) # draw colorbar
+plt.axes(ax) # make the original axes current again
+# draw coastlines
+m.drawcoastlines()
+# draw parallels
+m.drawparallels(np.arange(0,81,20),labels=[1,1,0,0])
+# draw meridians
+m.drawmeridians(np.arange(-180,0,20),labels=[0,0,0,1])
+plt.title('Surface Wind Barbs and Pressure')
+plt.show()
+
Modified: trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py
===================================================================
--- trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-07-23 03:08:41 UTC (rev 5819)
+++ trunk/toolkits/basemap/lib/mpl_toolkits/basemap/__init__.py 2008-07-23 12:32:48 UTC (rev 5820)
@@ -2890,6 +2890,44 @@
self.set_axes_limits(ax=ax)
return ret
+ def barbs(self, x, y, u, v, *args, **kwargs):
+ """
+ Make a wind barb plot (u, v) with on the map.
+ (see matplotlib.pyplot.barbs documentation).
+
+ Extra keyword ``ax`` can be used to override the default axis instance.
+
+ Other \*args and \**kwargs passed on to matplotlib.pyplot.barbs
+ """
+ if not kwargs.has_key('ax') and self.ax is None:
+ try:
+ ax = plt.gca()
+ except:
+ import matplotlib.pyplot as plt
+ ax = plt.gca()
+ elif not kwargs.has_key('ax') and self.ax is not None:
+ ax = self.ax
+ else:
+ ax = kwargs.pop('ax')
+ # allow callers to override the hold state by passing hold=True|False
+ b = ax.ishold()
+ h = kwargs.pop('hold',None)
+ if h is not None:
+ ax.hold(h)
+ try:
+ ret = ax.barbs(x,y,u,v,*args,**kwargs)
+ try:
+ plt.draw_if_interactive()
+ except:
+ pass
+ except:
+ ax.hold(b)
+ raise
+ ax.hold(b)
+ # set axes limits to fit map region.
+ self.set_axes_limits(ax=ax)
+ return ret
+
def drawlsmask(self,rgba_land,rgba_ocean,lsmask=None,
lsmask_lons=None,lsmask_lats=None,lakes=False,**kwargs):
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-07-23 03:08:44
|
Revision: 5819
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5819&view=rev
Author: ryanmay
Date: 2008-07-23 03:08:41 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
Added Barbs polygon collection (similar to Quiver) for plotting wind barbs. Added corresponding helpers to Axes and pyplot as well. (examples/pylab_examples/barb_demo.py shows it off.)
Modified Paths:
--------------
trunk/matplotlib/CHANGELOG
trunk/matplotlib/boilerplate.py
trunk/matplotlib/examples/tests/backend_driver.py
trunk/matplotlib/lib/matplotlib/axes.py
trunk/matplotlib/lib/matplotlib/pyplot.py
trunk/matplotlib/lib/matplotlib/quiver.py
Added Paths:
-----------
trunk/matplotlib/examples/pylab_examples/barb_demo.py
Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG 2008-07-23 02:44:49 UTC (rev 5818)
+++ trunk/matplotlib/CHANGELOG 2008-07-23 03:08:41 UTC (rev 5819)
@@ -1,3 +1,7 @@
+2008-07-22 Added Barbs polygon collection (similar to Quiver) for plotting
+ wind barbs. Added corresponding helpers to Axes and pyplot as
+ well. (examples/pylab_examples/barb_demo.py shows it off.) - RMM
+
2008-07-21 Added scikits.delaunay as matplotlib.delaunay. Added griddata
function in matplotlib.mlab, with example (griddata_demo.py) in
pylab_examples. griddata function will use mpl_toolkits._natgrid
Modified: trunk/matplotlib/boilerplate.py
===================================================================
--- trunk/matplotlib/boilerplate.py 2008-07-23 02:44:49 UTC (rev 5818)
+++ trunk/matplotlib/boilerplate.py 2008-07-23 03:08:41 UTC (rev 5819)
@@ -86,6 +86,7 @@
'step',
'vlines',
'xcorr',
+ 'barbs',
)
_misccommands = (
Added: trunk/matplotlib/examples/pylab_examples/barb_demo.py
===================================================================
--- trunk/matplotlib/examples/pylab_examples/barb_demo.py (rev 0)
+++ trunk/matplotlib/examples/pylab_examples/barb_demo.py 2008-07-23 03:08:41 UTC (rev 5819)
@@ -0,0 +1,33 @@
+'''
+Demonstration of wind barb plots
+'''
+import matplotlib.pyplot as plt
+import numpy as np
+
+x = np.linspace(-5, 5, 5)
+X,Y = np.meshgrid(x, x)
+U, V = 12*X, 12*Y
+
+data = [(-1.5,.5,-6,-6),
+ (1,-1,-46,46),
+ (-3,-1,11,-11),
+ (1,1.5,80,80)]
+
+#Default parameters for arbitrary set of vectors
+ax = plt.subplot(2,2,1)
+ax.barbs(*zip(*data))
+
+#Default parameters, uniform grid
+ax = plt.subplot(2,2,2)
+ax.barbs(X, Y, U, V)
+
+#Change parameters for arbitrary set of vectors
+ax = plt.subplot(2,2,3)
+ax.barbs(flagcolor='r', barbcolor=['b','g'], barb_increments=dict(half=10,
+ full=20, flag=100), *zip(*data))
+
+#Showing colormapping with uniform grid.
+ax = plt.subplot(2,2,4)
+ax.barbs(X, Y, U, V, np.sqrt(U*U + V*V), fill_empty=True, rounding=False)
+
+plt.show()
Modified: trunk/matplotlib/examples/tests/backend_driver.py
===================================================================
--- trunk/matplotlib/examples/tests/backend_driver.py 2008-07-23 02:44:49 UTC (rev 5818)
+++ trunk/matplotlib/examples/tests/backend_driver.py 2008-07-23 03:08:41 UTC (rev 5819)
@@ -33,6 +33,7 @@
'axhspan_demo.py',
'bar_stacked.py',
'barchart_demo.py',
+ 'barb_demo.py',
'boxplot_demo.py',
'broken_barh.py',
'barh_demo.py',
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-07-23 02:44:49 UTC (rev 5818)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-07-23 03:08:41 UTC (rev 5819)
@@ -5224,6 +5224,15 @@
return q
quiver.__doc__ = mquiver.Quiver.quiver_doc
+ def barbs(self, *args, **kw):
+ if not self._hold: self.cla()
+ b = mquiver.Barbs(self, *args, **kw)
+ self.add_collection(b)
+ self.update_datalim(b.get_offsets())
+ self.autoscale_view()
+ return b
+ barbs.__doc__ = mquiver.Barbs.barbs_doc
+
def fill(self, *args, **kwargs):
"""
call signature::
Modified: trunk/matplotlib/lib/matplotlib/pyplot.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pyplot.py 2008-07-23 02:44:49 UTC (rev 5818)
+++ trunk/matplotlib/lib/matplotlib/pyplot.py 2008-07-23 03:08:41 UTC (rev 5819)
@@ -2342,6 +2342,28 @@
# This function was autogenerated by boilerplate.py. Do not edit as
# changes will be lost
+def barbs(*args, **kwargs):
+ # allow callers to override the hold state by passing hold=True|False
+ b = ishold()
+ h = kwargs.pop('hold', None)
+ if h is not None:
+ hold(h)
+ try:
+ ret = gca().barbs(*args, **kwargs)
+ draw_if_interactive()
+ except:
+ hold(b)
+ raise
+
+ hold(b)
+ return ret
+if Axes.barbs.__doc__ is not None:
+ barbs.__doc__ = dedent(Axes.barbs.__doc__) + """
+
+Additional kwargs: hold = [True|False] overrides default hold state"""
+
+# This function was autogenerated by boilerplate.py. Do not edit as
+# changes will be lost
def cla(*args, **kwargs):
ret = gca().cla(*args, **kwargs)
Modified: trunk/matplotlib/lib/matplotlib/quiver.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/quiver.py 2008-07-23 02:44:49 UTC (rev 5818)
+++ trunk/matplotlib/lib/matplotlib/quiver.py 2008-07-23 03:08:41 UTC (rev 5819)
@@ -1,9 +1,14 @@
"""
-Support for plotting fields of arrows.
+Support for plotting vector fields.
-Presently this contains a single class, Quiver, but it
-might make sense to consolidate other arrow plotting here.
+Presently this contains Quiver and Barb. Quiver plots an arrow in the
+direction of the vector, with the size of the arrow related to the
+magnitude of the vector.
+Barbs are like quiver in that they point along a vector, but
+the magnitude of the vector is given schematically by the presence of barbs
+or flags on the barb.
+
This will also become a home for things such as standard
deviation ellipses, which can and will be derived very easily from
the Quiver code.
@@ -17,6 +22,8 @@
import matplotlib.text as mtext
import matplotlib.artist as martist
import matplotlib.font_manager as font_manager
+from matplotlib.cbook import delete_masked_points
+from matplotlib.patches import CirclePolygon
import math
@@ -498,3 +505,388 @@
return X, Y
quiver_doc = _quiver_doc
+
+_barbs_doc = """
+Plot a 2-D field of barbs.
+
+call signatures::
+
+ barb(U, V, **kw)
+ barb(U, V, C, **kw)
+ barb(X, Y, U, V, **kw)
+ barb(X, Y, U, V, C, **kw)
+
+Arguments:
+
+ *X*, *Y*:
+ The x and y coordinates of the barb locations
+ (default is head of barb; see *pivot* kwarg)
+
+ *U*, *V*:
+ give the *x* and *y* components of the barb shaft
+
+ *C*:
+ an optional array used to map colors to the barbs
+
+All arguments may be 1-D or 2-D arrays or sequences. If *X* and *Y*
+are absent, they will be generated as a uniform grid. If *U* and *V*
+are 2-D arrays but *X* and *Y* are 1-D, and if len(*X*) and len(*Y*)
+match the column and row dimensions of *U*, then *X* and *Y* will be
+expanded with :func:`numpy.meshgrid`.
+
+*U*, *V*, *C* may be masked arrays, but masked *X*, *Y* are not
+supported at present.
+
+Keyword arguments:
+
+ *length*:
+ Length of the barb in points; the other parts of the barb
+ are scaled against this.
+ Default is 9
+
+ *pivot*: [ 'tip' | 'middle' ]
+ The part of the arrow that is at the grid point; the arrow
+ rotates about this point, hence the name *pivot*.
+ Default is 'tip'
+
+ *barbcolor*: [ color | color sequence ]
+ Specifies the color all parts of the barb except any flags.
+ This parameter is analagous to the *edgecolor* parameter
+ for polygons, which can be used instead. However this parameter
+ will override facecolor.
+
+ *flagcolor*: [ color | color sequence ]
+ Specifies the color of any flags on the barb.
+ This parameter is analagous to the *facecolor* parameter
+ for polygons, which can be used instead. However this parameter
+ will override facecolor. If this is not set (and *C* has not either)
+ then *flagcolor* will be set to match *barbcolor* so that the barb
+ has a uniform color. If *C* has been set, *flagcolor* has no effect.
+
+ *sizes*:
+ A dictionary of coefficients specifying the ratio of a given feature
+ to the length of the barb. Only those values one wishes to override
+ need to be included. These features include:
+ 'spacing' - space between features (flags, full/half barbs)
+ 'height' - height (distance from shaft to top) of a flag or full barb
+ 'width' - width of a flag, twice the width of a full barb
+ 'emptybarb' - radius of the circle used for low magnitudes
+
+ *fill_empty*:
+ A flag on whether the empty barbs (circles) that are drawn should be filled
+ with the flag color. If they are not filled, they will be drawn such that
+ no color is applied to the center.
+ Default is False
+
+ *rounding*:
+ A flag to indicate whether the vector magnitude should be rounded when
+ allocating barb components. If True, the magnitude is rounded to the
+ nearest multiple of the half-barb increment. If False, the magnitude
+ is simply truncated to the next lowest multiple.
+ Default is True
+
+ *barb_increments*:
+ A dictionary of increments specifying values to associate with different
+ parts of the barb. Only those values one wishes to override need to be
+ included.
+ 'half' - half barbs (Default is 5)
+ 'full' - full barbs (Default is 10)
+ 'flag' - flags (default is 50)
+
+Barbs are traditionally used in meteorology as a way to plot the speed
+and direction of wind observations, but can technically be used to plot
+any two dimensional vector quantity. As opposed to arrows, which give
+vector magnitude by the length of the arrow, the barbs give more quantitative
+information about the vector magnitude by putting slanted lines or a triangle
+for various increments in magnitude, as show schematically below:
+
+ /\ \
+ / \ \
+ / \ \ \
+/ \ \ \
+------------------------------
+
+The largest increment is given by a triangle (or "flag"). After those come full
+lines (barbs). The smallest increment is a half line. There is only, of
+course, ever at most 1 half line. If the magnitude is small and only needs a
+single half-line and no full lines or triangles, the half-line is offset from
+the end of the barb so that it can be easily distinguished from barbs with a
+single full line. The magnitude for the barb shown above would nominally be
+65, using the standard increments of 50, 10, and 5.
+
+linewidths and edgecolors can be used to customize the barb.
+Additional :class:`~matplotlib.collections.PolyCollection`
+keyword arguments:
+
+%(PolyCollection)s
+""" % martist.kwdocd
+
+class Barbs(collections.PolyCollection):
+ '''
+ Specialized PolyCollection for barbs.
+
+ The only API method is set_UVC(), which can be used
+ to change the size, orientation, and color of the
+ arrows. Locations are changed using the set_offsets() collection
+ method.Possibly this method will be useful in animations.
+
+ There is one internal function _find_tails() which finds exactly
+ what should be put on the barb given the vector magnitude. From there
+ _make_barbs() is used to find the vertices of the polygon to represent the
+ barb based on this information.
+ '''
+ #This may be an abuse of polygons here to render what is essentially maybe
+ #1 triangle and a series of lines. It works fine as far as I can tell
+ #however.
+ def __init__(self, ax, *args, **kw):
+ self._pivot = kw.pop('pivot', 'tip')
+ self._length = kw.pop('length', 7)
+ barbcolor = kw.pop('barbcolor', None)
+ flagcolor = kw.pop('flagcolor', None)
+ self.sizes = kw.pop('sizes', dict())
+ self.fill_empty = kw.pop('fill_empty', False)
+ self.barb_increments = kw.pop('barb_increments', dict())
+ self.rounding = kw.pop('rounding', True)
+
+ #Flagcolor and and barbcolor provide convenience parameters for setting
+ #the facecolor and edgecolor, respectively, of the barb polygon. We
+ #also work here to make the flag the same color as the rest of the barb
+ #by default
+ if None in (barbcolor, flagcolor):
+ kw['edgecolors'] = 'face'
+ if flagcolor:
+ kw['facecolors'] = flagcolor
+ elif barbcolor:
+ kw['facecolors'] = barbcolor
+ else:
+ #Set to facecolor passed in or default to black
+ kw.setdefault('facecolors', 'k')
+ else:
+ kw['edgecolors'] = barbcolor
+ kw['facecolors'] = flagcolor
+
+ #Parse out the data arrays from the various configurations supported
+ x, y, u, v, c = self._parse_args(*args)
+ self.x = x
+ self.y = y
+ xy = np.hstack((x[:,np.newaxis], y[:,np.newaxis]))
+
+ #Make a collection
+ barb_size = self._length**2 / 4 #Empirically determined
+ collections.PolyCollection.__init__(self, [], (barb_size,), offsets=xy,
+ transOffset=ax.transData, **kw)
+ self.set_transform(transforms.IdentityTransform())
+
+ self.set_UVC(u, v, c)
+
+ __init__.__doc__ = """
+ The constructor takes one required argument, an Axes
+ instance, followed by the args and kwargs described
+ by the following pylab interface documentation:
+ %s""" % _barbs_doc
+
+ def _find_tails(self, mag, rounding=True, half=5, full=10, flag=50):
+ '''Find how many of each of the tail pieces is necessary. Flag
+ specifies the increment for a flag, barb for a full barb, and half for
+ half a barb. Mag should be the magnitude of a vector (ie. >= 0).
+
+ This returns a tuple of:
+ (number of flags, number of barbs, half_flag, empty_flag)
+ half_flag is a boolean whether half of a barb is needed, since there
+ should only ever be one half on a given barb. Empty flag is an array
+ of flags to easily tell if a barb is empty (too low to plot any
+ barbs/flags.'''
+
+ #If rounding, round to the nearest multiple of half, the smallest
+ #increment
+ if rounding:
+ mag = half * (mag / half + 0.5).astype(np.int)
+
+ num_flags = np.floor(mag / flag).astype(np.int)
+ mag = np.mod(mag, flag)
+
+ num_barb = np.floor(mag / full).astype(np.int)
+ mag = np.mod(mag, full)
+
+ half_flag = mag >= half
+ empty_flag = ~(half_flag | (num_flags > 0) | (num_barb > 0))
+
+ return num_flags, num_barb, half_flag, empty_flag
+
+ def _make_barbs(self, u, v, nflags, nbarbs, half_barb, empty_flag, length,
+ pivot, sizes, fill_empty):
+ '''This function actually creates the wind barbs. u and v are
+ components of the vector in the x and y directions, respectively.
+ nflags, nbarbs, and half_barb, empty_flag are, respectively, the number
+ of flags, number of barbs, flag for half a barb, and flag for empty
+ barb, ostensibly obtained from _find_tails. length is the length of
+ the barb staff in points. pivot specifies the point on the barb around
+ which the entire barb should be rotated. Right now valid options are
+ 'head' and 'middle'. sizes is a dictionary of coefficients specifying
+ the ratio of a given feature to the length of the barb. These features
+ include:
+
+ spacing - space between features (flags, full/half barbs)
+ height - height (distance from shaft of top) of a flag or full barb
+ width - width of a flag, twice the width of a full barb
+ emptybarb - radius of the circle used for low magnitudes
+
+ This function returns list of arrays of vertices, defining a polygon for
+ each of the wind barbs. These polygons have been rotated to properly
+ align with the vector direction.'''
+
+ #These control the spacing and size of barb elements relative to the
+ #length of the shaft
+ spacing = length * sizes.get('spacing', 0.125)
+ full_height = length * sizes.get('height', 0.4)
+ full_width = length * sizes.get('width', 0.25)
+ empty_rad = length * sizes.get('emptybarb', 0.15)
+
+ #Controls y point where to pivot the barb.
+ pivot_points = dict(tip=0.0, middle=-length/2.)
+
+ endx = 0.0
+ endy = pivot_points[pivot.lower()]
+
+ #Get the appropriate angle for the vector components. The offset is due
+ #to the way the barb is initially drawn, going down the y-axis. This
+ #makes sense in a meteorological mode of thinking since there 0 degrees
+ #corresponds to north (the y-axis traditionally)
+ angles = -(ma.arctan2(v, u) + np.pi/2)
+
+ #Used for low magnitude. We just get the vertices, so if we make it
+ #out here, it can be reused. The center set here should put the
+ #center of the circle at the location(offset), rather than at the
+ #same point as the barb pivot; this seems more sensible.
+ circ = CirclePolygon((0,0), radius=empty_rad).get_verts()
+ if fill_empty:
+ empty_barb = circ
+ else:
+ #If we don't want the empty one filled, we make a degenerate polygon
+ #that wraps back over itself
+ empty_barb = np.concatenate((circ, circ[::-1]))
+
+ barb_list = []
+ for index, angle in np.ndenumerate(angles):
+ #If the vector magnitude is too weak to draw anything, plot an
+ #empty circle instead
+ if empty_flag[index]:
+ #We can skip the transform since the circle has no preferred
+ #orientation
+ barb_list.append(empty_barb)
+ continue
+
+ poly_verts = [(endx, endy)]
+ offset = length
+
+ #Add vertices for each flag
+ for i in range(nflags[index]):
+ #The spacing that works for the barbs is a little to much for
+ #the flags, but this only occurs when we have more than 1 flag.
+ if offset != length: offset += spacing / 2.
+ poly_verts.extend([[endx, endy + offset],
+ [endx + full_height, endy - full_width/2 + offset],
+ [endx, endy - full_width + offset]])
+
+ offset -= full_width + spacing
+
+ #Add vertices for each barb. These really are lines, but works
+ #great adding 3 vertices that basically pull the polygon out and
+ #back down the line
+ for i in range(nbarbs[index]):
+ poly_verts.extend([(endx, endy + offset),
+ (endx + full_height, endy + offset + full_width/2),
+ (endx, endy + offset)])
+
+ offset -= spacing
+
+ #Add the vertices for half a barb, if needed
+ if half_barb[index]:
+ #If the half barb is the first on the staff, traditionally it is
+ #offset from the end to make it easy to distinguish from a barb
+ #with a full one
+ if offset == length:
+ poly_verts.append((endx, endy + offset))
+ offset -= 1.5 * spacing
+ poly_verts.extend([(endx, endy + offset),
+ (endx + full_height/2, endy + offset + full_width/4),
+ (endx, endy + offset)])
+
+ #Rotate the barb according the angle. Making the barb first and then
+ #rotating it made the math for drawing the barb really easy. Also,
+ #the transform framework makes doing the rotation simple.
+ poly_verts = transforms.Affine2D().rotate(-angle).transform(
+ poly_verts)
+ barb_list.append(poly_verts)
+
+ return barb_list
+
+ #Taken shamelessly from Quiver
+ def _parse_args(self, *args):
+ X, Y, U, V, C = [None]*5
+ args = list(args)
+ if len(args) == 3 or len(args) == 5:
+ C = ma.asarray(args.pop(-1)).ravel()
+ V = ma.asarray(args.pop(-1))
+ U = ma.asarray(args.pop(-1))
+ nn = np.shape(U)
+ nc = nn[0]
+ nr = 1
+ if len(nn) > 1:
+ nr = nn[1]
+ if len(args) == 2: # remaining after removing U,V,C
+ X, Y = [np.array(a).ravel() for a in args]
+ if len(X) == nc and len(Y) == nr:
+ X, Y = [a.ravel() for a in np.meshgrid(X, Y)]
+ else:
+ indexgrid = np.meshgrid(np.arange(nc), np.arange(nr))
+ X, Y = [np.ravel(a) for a in indexgrid]
+ return X, Y, U, V, C
+
+ def set_UVC(self, U, V, C=None):
+ self.u = ma.asarray(U).ravel()
+ self.v = ma.asarray(V).ravel()
+ if C is not None:
+ c = ma.asarray(C).ravel()
+ x,y,u,v,c = delete_masked_points(self.x.ravel(), self.y.ravel(),
+ self.u, self.v, c)
+ else:
+ x,y,u,v = delete_masked_points(self.x.ravel(), self.y.ravel(),
+ self.u, self.v)
+
+ magnitude = np.sqrt(u*u + v*v)
+ flags, barbs, halves, empty = self._find_tails(magnitude,
+ self.rounding, **self.barb_increments)
+
+ #Get the vertices for each of the barbs
+
+ plot_barbs = self._make_barbs(u, v, flags, barbs, halves, empty,
+ self._length, self._pivot, self.sizes, self.fill_empty)
+ self.set_verts(plot_barbs)
+
+ #Set the color array
+ if C is not None:
+ self.set_array(c)
+
+ #Update the offsets in case the masked data changed
+ xy = np.hstack((x[:,np.newaxis], y[:,np.newaxis]))
+ self._offsets = xy
+
+ def set_offsets(self, xy):
+ '''
+ Set the offsets for the barb polygons. This saves the offets passed in
+ and actually sets version masked as appropriate for the existing U/V
+ data. *offsets* should be a sequence.
+
+ ACCEPTS: sequence of pairs of floats
+ '''
+ self.x = xy[:,0]
+ self.y = xy[:,1]
+ x,y,u,v = delete_masked_points(self.x.ravel(), self.y.ravel(), self.u,
+ self.v)
+ xy = np.hstack((x[:,np.newaxis], y[:,np.newaxis]))
+ collections.PolyCollection.set_offsets(self, xy)
+ set_offsets.__doc__ = collections.PolyCollection.set_offsets.__doc__
+
+ barbs_doc = _barbs_doc
+
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ry...@us...> - 2008-07-23 02:44:50
|
Revision: 5818
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5818&view=rev
Author: ryanmay
Date: 2008-07-23 02:44:49 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
Fix bug (typo) in Transform.transform_non_affine.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/transforms.py
Modified: trunk/matplotlib/lib/matplotlib/transforms.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/transforms.py 2008-07-23 01:18:27 UTC (rev 5817)
+++ trunk/matplotlib/lib/matplotlib/transforms.py 2008-07-23 02:44:49 UTC (rev 5818)
@@ -1052,7 +1052,7 @@
Accepts a numpy array of shape (N x :attr:`input_dims`) and
returns a numpy array of shape (N x :attr:`output_dims`).
"""
- return self.transform(points)
+ return self.transform(values)
def get_affine(self):
"""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-07-23 01:18:30
|
Revision: 5817
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5817&view=rev
Author: jswhit
Date: 2008-07-23 01:18:27 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
fix typo.
Modified Paths:
--------------
trunk/toolkits/natgrid/lib/mpl_toolkits/natgrid/__init__.py
Modified: trunk/toolkits/natgrid/lib/mpl_toolkits/natgrid/__init__.py
===================================================================
--- trunk/toolkits/natgrid/lib/mpl_toolkits/natgrid/__init__.py 2008-07-23 01:15:52 UTC (rev 5816)
+++ trunk/toolkits/natgrid/lib/mpl_toolkits/natgrid/__init__.py 2008-07-23 01:18:27 UTC (rev 5817)
@@ -1,4 +1,4 @@
__version__ = 0.1
-__docstring__ = """
+__doc__ = """
Python interface to NCAR natgrid library. If installed, used
by matplotlib griddata function."""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-07-23 01:15:54
|
Revision: 5816
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5816&view=rev
Author: jswhit
Date: 2008-07-23 01:15:52 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
add __version__
Modified Paths:
--------------
trunk/toolkits/natgrid/lib/mpl_toolkits/natgrid/__init__.py
Modified: trunk/toolkits/natgrid/lib/mpl_toolkits/natgrid/__init__.py
===================================================================
--- trunk/toolkits/natgrid/lib/mpl_toolkits/natgrid/__init__.py 2008-07-23 01:15:22 UTC (rev 5815)
+++ trunk/toolkits/natgrid/lib/mpl_toolkits/natgrid/__init__.py 2008-07-23 01:15:52 UTC (rev 5816)
@@ -0,0 +1,4 @@
+__version__ = 0.1
+__docstring__ = """
+Python interface to NCAR natgrid library. If installed, used
+by matplotlib griddata function."""
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-07-23 01:15:24
|
Revision: 5815
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5815&view=rev
Author: jswhit
Date: 2008-07-23 01:15:22 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
implement some of JDH's suggestions for griddata.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/delaunay/__init__.py
trunk/matplotlib/lib/matplotlib/mlab.py
Modified: trunk/matplotlib/lib/matplotlib/delaunay/__init__.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/delaunay/__init__.py 2008-07-23 00:24:55 UTC (rev 5814)
+++ trunk/matplotlib/lib/matplotlib/delaunay/__init__.py 2008-07-23 01:15:22 UTC (rev 5815)
@@ -8,3 +8,4 @@
from matplotlib._delaunay import delaunay
from triangulate import *
from interpolate import *
+__version__ = "0.1"
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-07-23 00:24:55 UTC (rev 5814)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-07-23 01:15:22 UTC (rev 5815)
@@ -89,6 +89,7 @@
import numpy as np
+from matplotlib import verbose
import matplotlib.nxutils as nxutils
import matplotlib.cbook as cbook
@@ -2715,13 +2716,23 @@
that is not redistributable under a BSD-compatible license. When installed,
this function will use the mpl_toolkits.natgrid algorithm, otherwise it
will use the built-in matplotlib.delaunay package.
+
+ The natgrid matplotlib toolkit can be checked out through SVN with the
+ following command:
+
+ svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/toolkits/natgrid natgrid
"""
try:
- from mpl_toolkits.natgrid import _natgrid
+ from mpl_toolkits.natgrid import _natgrid, __version__
_use_natgrid = True
except ImportError:
import matplotlib.delaunay as delaunay
+ from matplotlib.delaunay import __version__
_use_natgrid = False
+ if _use_natgrid:
+ verbose.report('using natgrid version %s' % __version__)
+ else:
+ verbose.report('using delaunay version %s' % __version__)
if xi.ndim != yi.ndim:
raise TypeError("inputs xi and yi must have same number of dimensions (1 or 2)")
if xi.ndim != 1 and xi.ndim != 2:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <js...@us...> - 2008-07-23 00:24:58
|
Revision: 5814
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5814&view=rev
Author: jswhit
Date: 2008-07-23 00:24:55 +0000 (Wed, 23 Jul 2008)
Log Message:
-----------
add griddata to pylab, add griddata docstrings to mlab and pylab module docstrings.
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/mlab.py
trunk/matplotlib/lib/matplotlib/pylab.py
Modified: trunk/matplotlib/lib/matplotlib/mlab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/mlab.py 2008-07-22 19:47:04 UTC (rev 5813)
+++ trunk/matplotlib/lib/matplotlib/mlab.py 2008-07-23 00:24:55 UTC (rev 5814)
@@ -14,6 +14,8 @@
* find - Return the indices where some condition is true;
numpy.nonzero is similar but more general.
+ * griddata - interpolate irregularly distributed data to a
+ regular grid.
* prctile - find the percentiles of a sequence
@@ -90,12 +92,6 @@
import matplotlib.nxutils as nxutils
import matplotlib.cbook as cbook
-try:
- from mpl_toolkits.natgrid import _natgrid
- _use_natgrid = True
-except ImportError:
- import matplotlib.delaunay as delaunay
- _use_natgrid = False
# set is a new builtin function in 2.4; delete the following when
# support for 2.3 is dropped.
@@ -2720,6 +2716,12 @@
this function will use the mpl_toolkits.natgrid algorithm, otherwise it
will use the built-in matplotlib.delaunay package.
"""
+ try:
+ from mpl_toolkits.natgrid import _natgrid
+ _use_natgrid = True
+ except ImportError:
+ import matplotlib.delaunay as delaunay
+ _use_natgrid = False
if xi.ndim != yi.ndim:
raise TypeError("inputs xi and yi must have same number of dimensions (1 or 2)")
if xi.ndim != 1 and xi.ndim != 2:
Modified: trunk/matplotlib/lib/matplotlib/pylab.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/pylab.py 2008-07-22 19:47:04 UTC (rev 5813)
+++ trunk/matplotlib/lib/matplotlib/pylab.py 2008-07-23 00:24:55 UTC (rev 5814)
@@ -184,6 +184,7 @@
_Other
angle - the angle of a complex array
+ griddata - interpolate irregularly distributed data to a regular grid
load - load ASCII data into array
polyfit - fit x, y to an n-th order polynomial
polyval - evaluate an n-th order polynomial
@@ -219,7 +220,7 @@
from matplotlib.mlab import window_hanning, window_none,\
conv, detrend, detrend_mean, detrend_none, detrend_linear,\
- polyfit, polyval, entropy, normpdf,\
+ polyfit, polyval, entropy, normpdf, griddata,\
levypdf, find, trapz, prepca, fix, rem, norm, orth, rank,\
sqrtm, prctile, center_matrix, rk4, exp_safe, amap,\
sum_flat, mean_flat, rms_flat, l1norm, l2norm, norm, frange,\
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <as...@us...> - 2008-07-22 19:47:09
|
Revision: 5813
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5813&view=rev
Author: astraw
Date: 2008-07-22 19:47:04 +0000 (Tue, 22 Jul 2008)
Log Message:
-----------
minor docstring fix
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/axes.py
Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py 2008-07-22 18:43:38 UTC (rev 5812)
+++ trunk/matplotlib/lib/matplotlib/axes.py 2008-07-22 19:47:04 UTC (rev 5813)
@@ -4724,7 +4724,7 @@
arguments will be used only if *c* is an array of floats.
*cmap*: [ None | Colormap ]
- A :class:`matplotlib.cm.Colormap` instance. If *None*,
+ A :class:`matplotlib.colors.Colormap` instance. If *None*,
defaults to rc ``image.cmap``. *cmap* is only used if *c*
is an array of floats.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ef...@us...> - 2008-07-22 18:43:43
|
Revision: 5812
http://matplotlib.svn.sourceforge.net/matplotlib/?rev=5812&view=rev
Author: efiring
Date: 2008-07-22 18:43:38 +0000 (Tue, 22 Jul 2008)
Log Message:
-----------
Moved unmasked_index_ranges from lines.py to cbook.py
Modified Paths:
--------------
trunk/matplotlib/lib/matplotlib/cbook.py
Modified: trunk/matplotlib/lib/matplotlib/cbook.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cbook.py 2008-07-22 18:05:32 UTC (rev 5811)
+++ trunk/matplotlib/lib/matplotlib/cbook.py 2008-07-22 18:43:38 UTC (rev 5812)
@@ -1244,7 +1244,57 @@
margs[i] = x.filled()
return margs
+def unmasked_index_ranges(mask, compressed = True):
+ '''
+ Find index ranges where *mask* is *False*.
+ *mask* will be flattened if it is not already 1-D.
+
+ Returns Nx2 :class:`numpy.ndarray` with each row the start and stop
+ indices for slices of the compressed :class:`numpy.ndarray`
+ corresponding to each of *N* uninterrupted runs of unmasked
+ values. If optional argument *compressed* is *False*, it returns
+ the start and stop indices into the original :class:`numpy.ndarray`,
+ not the compressed :class:`numpy.ndarray`. Returns *None* if there
+ are no unmasked values.
+
+ Example::
+
+ y = ma.array(np.arange(5), mask = [0,0,1,0,0])
+ ii = unmasked_index_ranges(ma.getmaskarray(y))
+ # returns array [[0,2,] [2,4,]]
+
+ y.compressed()[ii[1,0]:ii[1,1]]
+ # returns array [3,4,]
+
+ ii = unmasked_index_ranges(ma.getmaskarray(y), compressed=False)
+ # returns array [[0, 2], [3, 5]]
+
+ y.filled()[ii[1,0]:ii[1,1]]
+ # returns array [3,4,]
+
+ Prior to the transforms refactoring, this was used to support
+ masked arrays in Line2D.
+
+ '''
+ mask = mask.reshape(mask.size)
+ m = np.concatenate(((1,), mask, (1,)))
+ indices = np.arange(len(mask) + 1)
+ mdif = m[1:] - m[:-1]
+ i0 = np.compress(mdif == -1, indices)
+ i1 = np.compress(mdif == 1, indices)
+ assert len(i0) == len(i1)
+ if len(i1) == 0:
+ return None # Maybe this should be np.zeros((0,2), dtype=int)
+ if not compressed:
+ return np.concatenate((i0[:, np.newaxis], i1[:, np.newaxis]), axis=1)
+ seglengths = i1 - i0
+ breakpoints = np.cumsum(seglengths)
+ ic0 = np.concatenate(((0,), breakpoints[:-1]))
+ ic1 = breakpoints
+ return np.concatenate((ic0[:, np.newaxis], ic1[:, np.newaxis]), axis=1)
+
+
# a dict to cross-map linestyle arguments
_linestyles = [('-', 'solid'),
('--', 'dashed'),
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|